Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions backend/migrations/0036_fee_groups.sql
Original file line number Diff line number Diff line change
@@ -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;
4 changes: 4 additions & 0 deletions backend/migrations/0037_payout_commission_percent.sql
Original file line number Diff line number Diff line change
@@ -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;
11 changes: 11 additions & 0 deletions backend/src/demo/extended.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down
21 changes: 16 additions & 5 deletions backend/src/modules/docs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -539,6 +539,15 @@ pub struct EventSeller {
pub intake_fee_items: Option<i32>,
/// Fees above the cap given back at the payout (#301)
pub fee_cap_credit: Option<Decimal>,
/// Fee group the seller chose or the team put them in (#302)
pub fee_group_id: Option<String>,
/// When the team confirmed, assigned or took away the group
#[serde(with = "ms_opt")]
pub fee_group_decided_at: Option<DateTime<Utc>>,
/// The group applied at the payout
pub fee_group_label: Option<String>,
/// The commission percent applied at the payout
pub commission_percent: Option<Decimal>,
#[serde(with = "ms_opt")]
pub private_seller_confirmed_at: Option<DateTime<Utc>>,
pub seller_snapshot: Option<Value>,
Expand All @@ -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,
Expand Down Expand Up @@ -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)
}
Expand Down
2 changes: 2 additions & 0 deletions backend/src/modules/event_exclusions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,8 @@ async fn exclude(ctx: &mut Ctx, args: ExcludeArgs) -> AppResult<Success> {
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?;
}
Expand Down
2 changes: 2 additions & 0 deletions backend/src/modules/event_invitations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(())
Expand Down
9 changes: 9 additions & 0 deletions backend/src/modules/event_products.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -1027,6 +1028,10 @@ async fn update_product_status(ctx: &mut Ctx, args: StatusArgs) -> AppResult<Uui
let product = docs::product(ctx.conn(), relation.product_id).await?;
if let Some(product) = &product {
assert_vendor_not_paid_out(ctx.conn(), relation.event_id, product.vendor_id).await?;
// The intake checks a self-declared fee group first (#302)
if args.status == Status::Available && relation.status == "announced" {
fee_groups::assert_group_decided(ctx.conn(), &event, product.vendor_id).await?;
}
}
if let Some(location) = args.location_category_id {
if args.status != Status::Available {
Expand Down Expand Up @@ -1117,6 +1122,10 @@ async fn mark_all_vendor_products_available(
let (event, vendor) = (args.event_id.0, args.vendor_id.0);
require_permission(ctx, event, Permission::Intake).await?;
assert_vendor_not_paid_out(ctx.conn(), event, vendor).await?;
{
let event = event_of(ctx, event).await?;
fee_groups::assert_group_decided(ctx.conn(), &event, vendor).await?;
}
let seen: Option<Vec<Uuid>> = args
.seen_product_ids
.map(|ids| ids.into_iter().map(|id| id.0).collect());
Expand Down
89 changes: 81 additions & 8 deletions backend/src/modules/event_roles.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -435,6 +436,26 @@ pub struct VendorWithCalculations {
pub details_recorded: Option<bool>,
/// The organizer took the seller out of the bazaar
pub excluded: Option<Exclusion>,
/// The fee group whose fees apply (#302)
pub fee_group: Option<VendorFeeGroup>,
/// 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<String>,
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<String>,
}

/// Sellers of an event with their sales totals and payout state. No permission check.
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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,
Expand All @@ -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(),
Expand All @@ -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)
Expand Down Expand Up @@ -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 })
}

Expand Down Expand Up @@ -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 })
Expand All @@ -777,6 +848,8 @@ async fn transfer_organizer(ctx: &mut Ctx, args: EventUserArgs) -> AppResult<Suc
add_role(ctx, event, user, Role::Organizer).await?;
remove_role(ctx, event, organizer, Role::Organizer).await?;
add_role(ctx, event, organizer, Role::Coorganizer).await?;
fee_groups::after_role_change(ctx, event, user).await?;
fee_groups::after_role_change(ctx, event, organizer).await?;
ctx.touch(Topic::Events);
Ok(Success { success: true })
}
29 changes: 22 additions & 7 deletions backend/src/modules/event_seller.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ use super::event_exclusions::assert_not_excluded;
use super::event_invitations;
use super::event_roles::{self, Permission, Role};
use super::features::registration_unavailable;
use super::fee_groups;
use super::offers::close_offers_for_event_product;
use super::sales::{self, intake_fee_for_seller};
use super::seller_numbers::next_seller_number;
Expand Down Expand Up @@ -88,6 +89,8 @@ struct JoinArgs {
private_seller: Option<bool>,
/// The link of an invitation by mail: replaces the access code
invitation: Option<String>,
/// A fee group the seller says they belong to, checked at the intake (#302)
fee_group_id: Option<String>,
}

/// The current user joins the event as seller and gets the next seller number.
Expand Down Expand Up @@ -138,6 +141,7 @@ async fn join_event(ctx: &mut Ctx, args: JoinArgs) -> AppResult<Uuid> {
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"));
}
Expand All @@ -162,14 +166,15 @@ async fn join_event(ctx: &mut Ctx, args: JoinArgs) -> AppResult<Uuid> {
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?;
Expand Down Expand Up @@ -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)
Expand All @@ -426,15 +435,18 @@ 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?;
}
None => {
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)
Expand All @@ -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?;
Expand All @@ -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)
Expand Down
Loading
Loading