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/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/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..c9589c0f 100644 --- a/backend/src/modules/docs.rs +++ b/backend/src/modules/docs.rs @@ -539,6 +539,15 @@ 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, + /// 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, @@ -547,7 +556,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, + commission_percent, private_seller_confirmed_at, seller_snapshot"; pub async fn event_seller( conn: &mut PgConnection, @@ -600,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_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..f5008938 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,26 @@ 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, + /// 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. +#[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 +483,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 +526,63 @@ 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); + // 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 ( + &shown.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, + 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 +591,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 +604,8 @@ pub async fn load_vendors_with_calculations( seller_number: seller.and_then(|seller| seller.number), sort_code, excluded: exclusions.remove(&vendor), + fee_group, + commission_percent, }); } Ok(vendors) @@ -703,6 +771,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 +822,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 +848,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.as_ref().map(|group| group.label.clone()); 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, + commission_percent = $8, payout_received = true WHERE id = $1", ) .bind(row.id) @@ -426,6 +435,8 @@ 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(fees.commission) .execute(ctx.conn()) .await?; } @@ -433,8 +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, 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, commission_percent, + payout_received, number) + VALUES ($1, $2, 0, $3, $4, $5, $6, $7, $8, $9, true, $10)", ) .bind(event.id) .bind(vendor) @@ -443,6 +455,8 @@ 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(fees.commission) .bind(number) .execute(ctx.conn()) .await?; @@ -460,7 +474,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, commission_percent = 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..8867550a 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,105 @@ 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 = 4; + +/// 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")); + } + // 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(); + 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 +1130,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 +1260,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 +1582,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..d337a68d 100644 --- a/backend/src/modules/features.rs +++ b/backend/src/modules/features.rs @@ -39,6 +39,54 @@ 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. + /// 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). +/// 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 +124,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 +172,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 +320,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 +427,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..299612de --- /dev/null +++ b/backend/src/modules/fee_groups.rs @@ -0,0 +1,662 @@ +//! 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 (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| { + ( + 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, + } + } + + /// 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 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()) + }) + } + + /// 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 { + 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)) +} + +/// 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 { + 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 = 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, s.fee_group_decided_at", + ) + .bind(event.id) + .fetch_all(conn) + .await?; + 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 }) + } + + 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?; + if let Some(group) = member.pending(event) { + 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 pending = member.pending(&event).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 { + // A pending group shows as applied, marked as still to be checked + applied: member.claimed(&event).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(()) +} + +/// Who may confirm or take away the seller's group: helpers with the intake right only a +/// self-declared group still to be checked, anything else changes money the organizer set, +/// so organizers only. Returns who decides and the stored group; none stored is refused. +async fn require_decider(ctx: &mut Ctx, event: &Event, seller: Uuid) -> 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 while the group is still to be checked. +async fn confirm_fee_group(ctx: &mut Ctx, args: SellerArgs) -> AppResult<()> { + 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 + .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 = 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 +} + +#[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, + }; + 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; + 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()); + assert!(member.pending(&event).is_none()); + assert_eq!(member.fees(&event).commission, Decimal::new(5, 0)); + } + + #[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..f0cfffa1 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,25 @@ 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); + // 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.commission, + ) + }; let payout: Decimal = items.iter().map(|i| i.sale.payout).sum::() - intake_fee.total + fee_cap_credit; @@ -1454,7 +1499,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, + 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..0d51e413 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); a self-declared one only once checked + 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..fa774c9a --- /dev/null +++ b/backend/tests/api/fee_groups.rs @@ -0,0 +1,760 @@ +//! 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, bakers (only by the team) 3 %. +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" }, + { "id": "bakers", "label": "Kuchenspender", "commission": 3, + "assignment": "manual" } + ] + }) +} + +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")); + // 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( + "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"); + // 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| { + 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 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; + 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" + ); + // 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() + .map(|label| group(label, 5.0)) + .collect(); + assert_eq!(save(json!(five)).await["code"], "event.feeGroupsTooMany"); + assert_eq!(save(json!(five[..4])).await["value"], Value::Null); + 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); +} + +#[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/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; 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 && (
({ 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\. 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' })); + 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/events/FeeGroups.tsx b/src/components/events/FeeGroups.tsx new file mode 100644 index 00000000..1d6c33d1 --- /dev/null +++ b/src/components/events/FeeGroups.tsx @@ -0,0 +1,194 @@ +import { useState } from 'react'; +import { BadgeCheck, Clock, Users } from 'lucide-react'; +import { toast } from 'sonner'; +import { useTranslation } from 'react-i18next'; +import { + describeFeeGroups, + type FeeGroupTerms, + type SellerConditionsEvent, +} from '../../lib/sellerFees'; +import { useMutation, useQuery } from '../../lib/api/react'; +import { api } from '../../lib/api/functions'; +import type { Id } from '../../lib/api/types'; +import { getUserFacingErrorMessage } from '../../lib/errors'; +import { cn } from '../../lib/utils'; +import { RadioGroup, RadioGroupItem } from '../ui/radio-group'; +import { Label } from '../ui/label'; +import { Button } from '../ui/button'; +import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '../ui/dialog'; + +/** The groups with own fees, under the bazaar's fees in the conditions (#302). */ +export function FeeGroupList({ groups }: { groups: FeeGroupTerms[] }) { + const { t } = useTranslation('events'); + if (groups.length === 0) return null; + return ( +
+

{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..eed7bcea --- /dev/null +++ b/src/components/sellers/FeeGroupBadge.tsx @@ -0,0 +1,123 @@ +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 { + DropdownMenuLabel, + DropdownMenuPortal, + DropdownMenuRadioGroup, + DropdownMenuRadioItem, + DropdownMenuSeparator, + DropdownMenuSub, + DropdownMenuSubContent, + DropdownMenuSubTrigger, +} 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 ( + + + + ); +} + +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?.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' + ); +} + +function BadgeContent({ group }: { group: NonNullable }) { + const { t } = useTranslation('organizer'); + 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. + * A submenu for the seller's "…" menu; nothing once paid out, the group is settled then. + */ +export function FeeGroupSubMenu({ + eventId, + vendor, + groups, +}: { + eventId: Id<'events'>; + vendor: VendorWithCalculations; + groups: FeeGroup[]; +}) { + 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 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 ( + + + + {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 new file mode 100644 index 00000000..90d63a23 --- /dev/null +++ b/src/components/sellers/FeeGroupCheck.test.tsx @@ -0,0 +1,145 @@ +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, 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() } })); + +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\. Bestätige/)).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(); + }); +}); + +/** 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 () => { + renderSubMenu(vendor()); + openSubMenu(); + 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 () => { + renderSubMenu( + vendor({ id: 'helpers', label: 'Helfer', pending: false, byRole: true, chosen: 'members' }) + ); + 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' })); + 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 { unmount } = renderSubMenu(vendor(pending, true)); + expect(screen.queryByRole('menuitem')).not.toBeInTheDocument(); + unmount(); + renderSubMenu(vendor(), []); + expect(screen.queryByRole('menuitem')).not.toBeInTheDocument(); + }); +}); diff --git a/src/components/sellers/FeeGroupCheck.tsx b/src/components/sellers/FeeGroupCheck.tsx new file mode 100644 index 00000000..32505aee --- /dev/null +++ b/src/components/sellers/FeeGroupCheck.tsx @@ -0,0 +1,86 @@ +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 + ? // The sentence brings its own full stop + t('feeGroupCheck.textWithProof', { proof: group.proofHint.replace(/[.!\s]+$/, '') }) + : t('feeGroupCheck.text')} +

+
+ + +
+
+ ); +} diff --git a/src/components/ui/alert-dialog.tsx b/src/components/ui/alert-dialog.tsx index 4bdb56be..1dd9c489 100644 --- a/src/components/ui/alert-dialog.tsx +++ b/src/components/ui/alert-dialog.tsx @@ -47,7 +47,7 @@ function AlertDialogContent({ ; }, Id<'eventSeller'> @@ -1114,6 +1152,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 +1230,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 +1305,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 +1382,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 +1459,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 +1546,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 +1626,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 +1701,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 +1763,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 +1823,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 +1907,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 +2669,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 +2769,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/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 f364e3bd..f9f7c288 100644 --- a/src/lib/sellerFees.test.ts +++ b/src/lib/sellerFees.test.ts @@ -1,5 +1,11 @@ import { describe, expect, it } from 'vitest'; -import { describeSellerFees, describeSellerRules, describeSellerSchedule } from './sellerFees'; +import { + describeFeeGroups, + formGroupAdvantages, + describeSellerFees, + describeSellerRules, + describeSellerSchedule, +} from './sellerFees'; describe('describeSellerFees', () => { it('explains commission and intake fee with an example', () => { @@ -131,3 +137,83 @@ describe('describeSellerSchedule', () => { expect(schedule.rows.map((row) => row.label)).toEqual(['Aufbau', 'Abbau']); }); }); + +describe('describeFeeGroups', () => { + 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', + label: 'Vereinsmitglieder', + commission: 5, + assignment: 'selfDeclared', + proofHint: 'Mitgliedsausweis zeigen', + }, + // Same commission: only the item limit and the intake fee count + { + id: 'helpers', + label: 'Helfer', + commission: 10, + intakeFee: 0.5, + 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: 'manual', + }, + ], + }, + }); + expect(groups.map(({ fees, how }) => ({ fees, how }))).toEqual([ + { + fees: '5 % Provision statt 10 % · keine Annahmegebühr', + how: 'Nachweis bei der Abgabe: Mitgliedsausweis zeigen', + }, + { + 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: 'Vergibt der Veranstalter', + }, + ]); + }); + + 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 83e60882..61924d84 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,99 @@ 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; +} + +/** + * 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 feeGroupAdvantages(event: SellerConditionsEvent, group: FeeGroup): string[] { + const base = eventFees(event); + 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.assignment === 'manual' + ? text('groupManual') + : 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..e6b204b5 100644 --- a/src/locales/de/errors.json +++ b/src/locales/de/errors.json @@ -90,7 +90,14 @@ "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 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." }, "feature": { "disabled": "Diese Aktion ist derzeit deaktiviert.", @@ -271,5 +278,14 @@ }, "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.", + "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 306fefe8..922435d2 100644 --- a/src/locales/de/events.json +++ b/src/locales/de/events.json @@ -124,7 +124,32 @@ "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", + "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", + "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}}", + "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", + "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", + "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 4571444d..7f5d872e 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}}: {{advantages}}" }, "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}}: {{advantages}}" }, "short": { "type": "Art", @@ -1364,5 +1372,68 @@ "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. 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", + "label": "Name der Gruppe", + "labelPlaceholder": "z. B. Vereinsmitglieder", + "assignmentLabel": "Wer gehört dazu?", + "assignment": { + "selfDeclared": "Angabe bei der Anmeldung", + "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. 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", + "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", + "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.", + "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.", + "remove": "Gruppe entfernen", + "add": "Gebührengruppe hinzufügen", + "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.", + "helpersTwice": "Es gibt schon eine Gruppe für die Helfer des Basars." + }, + "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.", + "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.", + "filter": "Nach Gebührengruppe filtern", + "allGroups": "Alle Gruppen", + "withPending": "{{group}} ({{count}} prüfen)" } } 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..cd2c0a4f 100644 --- a/src/locales/en/errors.json +++ b/src/locales/en/errors.json @@ -90,7 +90,14 @@ "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 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." }, "feature": { "disabled": "This action is currently disabled.", @@ -271,5 +278,14 @@ }, "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.", + "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 6af4b824..dcb8a10b 100644 --- a/src/locales/en/events.json +++ b/src/locales/en/events.json @@ -124,7 +124,32 @@ "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", + "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", + "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}}", + "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", + "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", + "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 96b84f57..31d80106 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}}: {{advantages}}" }, "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}}: {{advantages}}" }, "short": { "type": "Kind", @@ -1364,5 +1372,68 @@ "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. 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", + "label": "Name of the group", + "labelPlaceholder": "e.g. Club members", + "assignmentLabel": "Who belongs to it?", + "assignment": { + "selfDeclared": "Given at registration", + "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. 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", + "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", + "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.", + "remove": "Remove group", + "add": "Add fee group", + "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.", + "helpersTwice": "There is already a group for the helpers of the bazaar." + }, + "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.", + "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.", + "filter": "Filter by fee group", + "allGroups": "All groups", + "withPending": "{{group}} ({{count}} to check)" } } 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.edit.test.tsx b/src/pages/organizer/events/EditEventForm.edit.test.tsx index bdf4ea46..4bbd3add 100644 --- a/src/pages/organizer/events/EditEventForm.edit.test.tsx +++ b/src/pages/organizer/events/EditEventForm.edit.test.tsx @@ -92,6 +92,8 @@ function renderAt(path: string) { beforeEach(() => { editEvent.mockClear(); createEvent.mockClear(); + // The wizard keeps every change as draft in the browser; each test starts afresh + localStorage.clear(); }); describe('editing an event', () => { diff --git a/src/pages/organizer/events/EditEventForm.tsx b/src/pages/organizer/events/EditEventForm.tsx index 29556aaa..a7ca8b48 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. */ @@ -58,6 +60,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 +87,8 @@ import { SalePreview, } from './components/wizard/WizardPreviews'; import { WizardSummary } from './components/wizard/WizardSummary'; +import { EditEventFeeGroups } from './components/EditEventFeeGroups'; +import { MAX_FEE_GROUPS, extraHelperGroups, type FeeGroup } from '../../../shared/feeGroups'; import { PageSkeleton } from '../../../components/ui/loading'; import { isEventRunning } from '../../../shared/eventPhase'; @@ -203,6 +209,63 @@ 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', 'manual']), + 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); + }); + for (const index of extraHelperGroups(groups)) { + ctx.addIssue({ + code: 'custom', + message: i18n.t('feeGroups.helpersTwice', { ns: 'organizer' }), + path: [index, 'assignment'], + }); + } + }), }), sellerLogistics: z.object({ dropoffStart: z.string(), @@ -294,6 +357,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 +444,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 +507,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 +605,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'], @@ -497,11 +624,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'); @@ -517,10 +649,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) => ( @@ -588,6 +745,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 +804,7 @@ function EventSection({ + ); case 'registration': @@ -751,6 +911,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( @@ -904,6 +1065,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); @@ -955,6 +1118,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()), @@ -962,6 +1126,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 @@ -969,7 +1134,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 () => { @@ -977,13 +1141,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') }); @@ -999,7 +1164,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); }; @@ -1009,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)}`); }; @@ -1069,7 +1237,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 @@ -1082,7 +1251,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); @@ -1094,6 +1263,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, guestSubmitted.current); + }, 600); + }); + return () => { + clearTimeout(timer); + subscription.unsubscribe(); + }; + }, [isEditing, methods]); // Next render: onSubmit then sees the restored storage locations useEffect(() => { if (!creatingDraft) return; @@ -1317,6 +1506,7 @@ export function EditEventForm({ after }: { after?: ReactNode } = {}) { eventMapImageUrl: event?.eventMapImageUrl, isRunning, feeLock, + registeredFeeGroups: registeredTerms.current?.feeGroups.map((g) => g.id), }} /> @@ -1395,6 +1585,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 && ( + {(isOpen || hasError) && ( +
    +
    + + + + + + + {/* Helpers are in their group by role: one such group per bazaar */} + + + + +
    +
    + + + + + + + + + + + + +
    + {group.assignment === 'selfDeclared' && ( + + + + )} +
    +

    + {fixed && t('feeGroups.fixed')} +

    + +
    +
    + )} + + ); + })} + + )} + {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..552a7b18 100644 --- a/src/pages/organizer/events/components/wizard/WizardPreviews.tsx +++ b/src/pages/organizer/events/components/wizard/WizardPreviews.tsx @@ -43,7 +43,9 @@ import { describeSellerFees, formatSignedEuro, type SellerConditionsEvent, + formGroupAdvantages, } from '../../../../../lib/sellerFees'; +import type { FeeGroup } from '../../../../../shared/feeGroups'; import { cn, formatDateRangeDE, formatPriceDE } from '../../../../../lib/utils'; import { categoryFieldText } from '../../../../../i18n/categoryFields'; import { useRequirableFields } from '../../../../../hooks/useCategoryFields'; @@ -94,6 +96,7 @@ interface WizardValues { labelMark?: LabelMark; intakeFee?: number; maxFeesPerSeller?: number; + feeGroups?: FeeGroup[]; privateSellersOnly?: boolean; fixedSellerData?: boolean; directSale?: boolean; @@ -565,6 +568,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(), + advantages: formGroupAdvantages(values, group), + })} +

+ ))}
{example && (
diff --git a/src/pages/organizer/events/components/wizard/WizardSummary.tsx b/src/pages/organizer/events/components/wizard/WizardSummary.tsx index b0b06509..9ad64383 100644 --- a/src/pages/organizer/events/components/wizard/WizardSummary.tsx +++ b/src/pages/organizer/events/components/wizard/WizardSummary.tsx @@ -17,6 +17,8 @@ import { VISIBILITY_OPTIONS } from '../../../../../constants/records'; import type { EventVisibility } from '../../../../../shared/constants'; import { cn, formatDateRangeDE, formatPriceDE } from '../../../../../lib/utils'; import { localTime } from '../../../../../lib/eventDates'; +import type { FeeGroup } from '../../../../../shared/feeGroups'; +import { formGroupAdvantages } from '../../../../../lib/sellerFees'; /** The steps a fact of the summary leads back to. */ export type SummaryStep = @@ -50,6 +52,7 @@ interface SummaryValues { maxItemsTotal?: number; maxFeesPerSeller?: number; intakeFee?: number; + feeGroups?: FeeGroup[]; registrationOpen?: boolean; }; sellerLogistics?: { @@ -164,6 +167,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(), + advantages: formGroupAdvantages(values, group), + }) + ), ].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..3fa21de4 100644 --- a/src/pages/organizer/events/dashboard/ProductManagementPage.tsx +++ b/src/pages/organizer/events/dashboard/ProductManagementPage.tsx @@ -71,6 +71,8 @@ import { type SellerPrintoutKind, } from '../../../../lib/sellerPrintout'; import { SellerIdCheck } from '../../../../components/sellers/SellerIdCheck'; +import { FeeGroupCheck } from '../../../../components/sellers/FeeGroupCheck'; +import { FeeGroupBadge, FeeGroupSubMenu } from '../../../../components/sellers/FeeGroupBadge'; import { useAssignMissingSellerNumbers } from '../../../../hooks/useAssignMissingSellerNumbers'; import { matchingVendors, productMatcher } from '../../../../lib/productSearch'; import { addToCachedCart } from '../../../../lib/checkout'; @@ -225,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; @@ -662,6 +670,7 @@ export function ProductManagementPage() { {selectedVendor.managedByEventId && } {selectedVendor.excluded && } +
+ {pendingGroups > 0 && ( +

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

+ )} + {/* Table only where it fits; the side menu takes room on tablets, too */}
@@ -264,9 +321,7 @@ export function SellerManagementPage() { {filteredVendors.length === 0 ? ( - {activeFilter === 'helpers' && !searchTerm - ? t('sellers.noHelpers') - : t('sellers.noneForFilter')} + {emptyText ?? t('sellers.noneForFilter')} ) : ( @@ -293,6 +348,7 @@ export function SellerManagementPage() { {v.managedByEventId && } {v.excluded && } + {v.isHelper && !isOwner && ( )} @@ -334,17 +390,9 @@ export function SellerManagementPage() { {t('sellers.owner')} ) : v.isHelper ? ( - - - {t('sellers.helpers')} - - {canManageHelpers && ( - setHelperAction({ mode: 'edit', vendor: v })} - /> - )} - + + {t('sellers.helpers')} + ) : null} @@ -361,9 +409,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 +435,7 @@ export function SellerManagementPage() { {v.managedByEventId && } {v.excluded && } + {isOwner && } {v.isHelper && !isOwner && ( @@ -414,14 +461,6 @@ export function SellerManagementPage() {
- - {canManageHelpers && !isOwner && v.isHelper && ( -
- setHelperAction({ mode: 'edit', vendor: v })} - /> -
- )}
); }) @@ -494,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/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) { @@ -121,12 +125,15 @@ export function InventoryConfirmDialog({ confirmLabel={isSubmitting ? t('confirm.processing') : content.actionLabel} loading={isSubmitting} destructive={type === 'undoSale' || type === 'undoReturn'} + // A self-declared fee group is confirmed or removed first + disabled={type === 'markAvailable' && !!feeGroupCheck} onConfirm={(e) => { e.preventDefault(); runConfirm(); }} > {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..75bcf47d --- /dev/null +++ b/src/shared/feeGroups.test.ts @@ -0,0 +1,71 @@ +import { describe, expect, it } from 'vitest'; +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 = { + 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); + }); + + 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 new file mode 100644 index 00000000..66badbce --- /dev/null +++ b/src/shared/feeGroups.ts @@ -0,0 +1,103 @@ +/** + * 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' | 'manual'; + +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. 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" */ + proofHint?: string; +} + +export const MAX_FEE_GROUPS = 4; + +/** 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]; +} + +/** 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)}`; +} diff --git a/src/tests/auth/fee-groups.spec.ts b/src/tests/auth/fee-groups.spec.ts new file mode 100644 index 00000000..a0ddf8bd --- /dev/null +++ b/src/tests/auth/fee-groups.spec.ts @@ -0,0 +1,97 @@ +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('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(); + 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'); + + // 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 expectToast(organizer, /: keine Gruppe$/); + await expect(badge).toBeHidden(); +}); 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 {