diff --git a/backend/src/demo/extended.rs b/backend/src/demo/extended.rs index 56885dee..aa39e490 100644 --- a/backend/src/demo/extended.rs +++ b/backend/src/demo/extended.rs @@ -709,6 +709,7 @@ async fn bike_flea_market(demo: &mut Demo<'_>, people: &People) -> anyhow::Resul categories: &[Cat::Bikes], cover: "cover_bikes", features: json!({ + "eventType": "bikeExchange", "directSale": true, "discounts": false, "priceOffers": false, @@ -813,6 +814,7 @@ async fn kids_bazaar(demo: &mut Demo<'_>, people: &People) -> anyhow::Result<()> categories: &[Cat::Clothing, Cat::Shoes, Cat::Toys, Cat::Books, Cat::Other, Cat::BabyKids, Cat::Bikes, Cat::Sports, Cat::Furniture], cover: "cover_clothes", features: json!({ + "eventType": "kidsBazaar", "discounts": true, "discountStartsAt": millis(now - Duration::minutes(30)), "maxDiscountPercent": 50, @@ -1114,6 +1116,7 @@ async fn ski_bazaar(demo: &mut Demo<'_>, people: &People) -> anyhow::Result<()> categories: &[Cat::Sports, Cat::Shoes, Cat::Clothing, Cat::Accessories], cover: "cover_winter", features: json!({ + "eventType": "skiBazaar", "discounts": false, "priceOffers": true, "minimumPrice": true, diff --git a/backend/src/modules/events.rs b/backend/src/modules/events.rs index 8867550a..7982159c 100644 --- a/backend/src/modules/events.rs +++ b/backend/src/modules/events.rs @@ -55,6 +55,9 @@ const SERVICES: [&str; 6] = [ const VISIBILITIES: [&str; 3] = ["public", "logged-in", "approved"]; const LABEL_FORMATS: [&str; 2] = ["standard", "small"]; const LABEL_MARKS: [&str; 2] = ["universal", "none"]; +/// Kinds of bazaars of the creation wizard (`EVENT_TYPES` in src/lib/eventTypes.ts); the +/// conditions pick their worked example by it (#303) +const EVENT_TYPES: [&str; 4] = ["kidsBazaar", "clothingBazaar", "skiBazaar", "bikeExchange"]; /// What viewers outside the team see instead of the access code const HIDDEN_ACCESS_CODE: &str = "••••"; @@ -774,6 +777,9 @@ struct FeaturesArgs { registration_ends_at: Option, /// Absent (older apps): the stored groups stay fee_groups: Option>, + /// The kind of bazaar (#303); null clears it, left out the stored one stays + #[serde(default, with = "serde_with::rust::double_option")] + event_type: Option>, } /// One fee group as the form sends it (#302) @@ -943,6 +949,11 @@ fn sanitize_features( { return Err(invalid("labelMark")); } + if let Some(Some(kind)) = &features.event_type + && !EVENT_TYPES.contains(&kind.as_str()) + { + return Err(invalid("eventType")); + } let previous_bool = |key: &str| previous.and_then(|p| p.get(key)).and_then(Value::as_bool); let previous_number = |key: &str| previous.and_then(|p| p.get(key)).and_then(Value::as_f64); let required_fields: Option> = match features.required_fields { @@ -1140,6 +1151,16 @@ fn sanitize_features( .unwrap_or(Value::Null), }, ); + put( + "eventType", + match features.event_type { + Some(kind) => json!(kind), + None => previous + .and_then(|p| p.get("eventType")) + .cloned() + .unwrap_or(Value::Null), + }, + ); Ok(Value::Object(stored)) } @@ -2206,6 +2227,34 @@ mod tests { assert!(cleared.get("maxFeesPerSeller").is_none()); } + #[test] + fn event_type_is_known_and_stays_unless_cleared() { + let sanitize = |event_type, previous: Option<&Value>| { + sanitize_features( + FeaturesArgs { + event_type, + ..FeaturesArgs::default() + }, + previous, + &known(), + ) + }; + let stored = sanitize(Some(Some("bikeExchange".into())), None).unwrap(); + assert_eq!(stored["eventType"], "bikeExchange"); + // Not sent by an older client: kept + assert_eq!( + sanitize(None, Some(&stored)).unwrap()["eventType"], + "bikeExchange" + ); + assert!( + sanitize(Some(None), Some(&stored)) + .unwrap() + .get("eventType") + .is_none() + ); + assert!(sanitize(Some(Some("flea".into())), None).is_err()); + } + #[test] fn feature_ranges_are_checked() { let err = |features: FeaturesArgs| { diff --git a/src/components/events/SellerConditions.test.tsx b/src/components/events/SellerConditions.test.tsx index bfac2ff4..c0720944 100644 --- a/src/components/events/SellerConditions.test.tsx +++ b/src/components/events/SellerConditions.test.tsx @@ -16,29 +16,43 @@ vi.mock('../../lib/api/react', () => ({ })); describe('SellerConditions', () => { - it('shows fees, a worked example, the rules and the times', () => { - render( + it('shows fees, a worked example, the times, then duties and options', () => { + const { container } = render( ); - expect(screen.getByText(/10 % Provision vom Verkaufspreis/)).toBeInTheDocument(); + expect(screen.getByText(/10 % Provision auf jeden verkauften Artikel/)).toBeInTheDocument(); expect(screen.getByText(/2,00 € Annahmegebühr pro angenommenem Artikel/)).toBeInTheDocument(); expect(screen.getByText('Rechenbeispiel')).toBeInTheDocument(); - expect(screen.getByText('Annahmegebühr 10 × 2,00 €')).toBeInTheDocument(); - expect(screen.getByText('−20,00 €')).toBeInTheDocument(); - expect(screen.getByText('Du bekommst')).toBeInTheDocument(); - expect(screen.getByText('7,00 €')).toBeInTheDocument(); + expect( + screen.getByText( + 'Gibst du 2 Räder ab und verkaufst davon ein Rad für 150,00 €, bekommst du 131,00 € ' + + '(150,00 € − 15,00 € Provision − 4,00 € Annahmegebühr).' + ) + ).toBeInTheDocument(); expect(screen.getByText('Bis zu 25 Artikel pro Verkäufer')).toBeInTheDocument(); expect(screen.getByText(/online Preise vorschlagen/)).toBeInTheDocument(); expect(screen.getByText('Abholung')).toBeInTheDocument(); + // Fees, times, what applies, what is possible + expect([...container.querySelectorAll('h4')].map((h) => h.textContent)).toEqual([ + 'Gebühren', + 'Abgabe & Abholung', + 'Das gilt für dich', + 'Das ist möglich', + ]); }); - it('leaves out the example and what is not offered when compact', () => { + it('leaves out the example when compact, and never names what is not offered', () => { render( { ); expect(screen.getByText(/10 % Provision/)).toBeInTheDocument(); expect(screen.queryByText('Rechenbeispiel')).not.toBeInTheDocument(); - expect(screen.queryByText('Keine Rabatte während des Basars')).not.toBeInTheDocument(); + expect(screen.queryByText(/Keine Rabatte|Kein Verhandeln/)).not.toBeInTheDocument(); expect(screen.getByText(/online Preise vorschlagen/)).toBeInTheDocument(); }); - it('names required details, private sellers, fixed data and late questions', () => { + it('names required details, ID, private sellers and late questions, details on request', () => { render( { }} /> ); - expect(screen.getByText('Pflichtangaben für jeden Artikel: Rahmennummer')).toBeInTheDocument(); + expect(screen.getByText('Pflichtangaben je Artikel: Rahmennummer')).toBeInTheDocument(); expect(screen.getByText(/Nur für Privatleute/)).toBeInTheDocument(); - expect(screen.getByText(/Bring deinen Ausweis mit/)).toBeInTheDocument(); + expect(screen.getByText(/Ausweis mitbringen/)).toBeInTheDocument(); + expect(screen.getByText('Mehr dazu').closest('details')).not.toHaveAttribute('open'); expect(screen.getByText(/Käufer können während des Basars/)).toBeInTheDocument(); }); it('says so when there are no fees', () => { - render(); + render(); expect(screen.getByText(/Keine Gebühren/)).toBeInTheDocument(); expect(screen.queryByText('Rechenbeispiel')).not.toBeInTheDocument(); + expect(screen.queryByText('Das ist möglich')).not.toBeInTheDocument(); }); }); diff --git a/src/components/events/SellerConditions.tsx b/src/components/events/SellerConditions.tsx index 7347e0e4..d0a1116c 100644 --- a/src/components/events/SellerConditions.tsx +++ b/src/components/events/SellerConditions.tsx @@ -5,21 +5,19 @@ import { describeSellerFees, describeSellerRules, describeSellerSchedule, - formatSignedEuro, type SellerConditionsEvent, } from '../../lib/sellerFees'; -import { resolveEventFeatures } from '../../shared/eventFeatures'; import { useCategoryFieldDefinitions } from '../../hooks/useCategoryFields'; -import { cn, formatPriceDE } from '../../lib/utils'; +import { cn } 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 - * features and hand-in/pickup times. Shown before registering and to registered - * sellers; `compact` (bazaar page sidebar) leaves out the example and what the - * bazaar does not offer. + * What sellers agree to at a bazaar, only what applies (#303): fees with a worked example + * that fits the kind of bazaar, hand-in and pickup times, what sellers must do and what + * they can do. Shown before registering and to registered sellers; `compact` (bazaar page + * sidebar) leaves out the example. */ export function SellerConditions({ event, @@ -36,16 +34,9 @@ export function SellerConditions({ eventId?: Id<'events'>; }) { const { t } = useTranslation('events'); - const { intakeFee, maxFeesPerSeller } = resolveEventFeatures(event); - const { lines, example } = describeSellerFees({ - commission: event.commission, - intakeFee, - maxFeesPerSeller, - }); + const { lines, example } = describeSellerFees(event); const fieldDefinitions = useCategoryFieldDefinitions(); - const rules = describeSellerRules(event, fieldDefinitions).filter( - (rule) => !compact || rule.allowed - ); + const { duties, options } = describeSellerRules(event, fieldDefinitions); const schedule = describeSellerSchedule(event); const groups = describeFeeGroups(event); @@ -73,45 +64,16 @@ export function SellerConditions({ {example && !compact && (

{t('conditions.example')}

-

{example.intro}

- - - {example.rows.map((row) => ( - - - - - ))} - - - - - -
{row.label} - {formatSignedEuro(row.amount)} -
- {example.total >= 0 ? t('conditions.youGet') : t('conditions.youPay')} - - {formatPriceDE(Math.abs(example.total))} € -
+

{example.text}

+ {example.groups.map((group) => ( +

+ {group} +

+ ))}
)} - -
    - {rules.map((rule) => ( - - ))} -
-
- {(schedule.rows.length > 0 || schedule.note) && ( {schedule.rows.length > 0 && ( @@ -131,6 +93,31 @@ export function SellerConditions({ )} )} + + {[ + { key: 'duties', rules: duties }, + { key: 'options', rules: options }, + ].map( + ({ key, rules }) => + rules.length > 0 && ( + +
    + {rules.map((rule) => ( + + {rule.details && ( +
    + + {t('conditions.details')} + +

    {rule.details}

    +
    + )} +
    + ))} +
+
+ ) + )} ); @@ -151,10 +138,13 @@ function ConditionLine({ text, allowed = true, icon, + children, }: { text: string; allowed?: boolean; icon?: LucideIcon; + /** More about it below the text */ + children?: ReactNode; }) { const Icon = icon ?? (allowed ? Check : X); return ( @@ -165,7 +155,10 @@ function ConditionLine({ icon ? 'text-muted-foreground' : allowed && 'text-green-600' )} /> - {text} +
+ {text} + {children} +
); } diff --git a/src/lib/eventTypes.ts b/src/lib/eventTypes.ts index 32874903..f04da3cb 100644 --- a/src/lib/eventTypes.ts +++ b/src/lib/eventTypes.ts @@ -9,12 +9,33 @@ import { compactSelection, groupCategories } from '../shared/categoryTree'; */ export type EventTypeId = 'kidsBazaar' | 'clothingBazaar' | 'skiBazaar' | 'bikeExchange'; +/** + * The worked example of the conditions (#303): what a typical seller hands in and sells. + * `noun` names the items in it (events: conditions.exampleItems.). + */ +export interface FeeExampleCase { + handedIn: number; + sold: number; + price: number; + noun: 'item' | 'piece' | 'bike'; +} + +/** For a bazaar of no known kind */ +export const NEUTRAL_FEE_EXAMPLE: FeeExampleCase = { + handedIn: 5, + sold: 3, + price: 20, + noun: 'item', +}; + export interface EventType { id: EventTypeId; /** Drawing for the picker and the previews of the wizard */ item: ItemKind; /** Prices of the example items in the previews (titles: eventTypes..exampleItems) */ examplePrices: [number, number, number]; + /** What sellers of such a bazaar typically hand in and sell, for the worked example */ + feeExample: FeeExampleCase; commission: number; features: StoredEventFeatures; /** @@ -35,6 +56,7 @@ export const EVENT_TYPES: EventType[] = [ // Many small items per seller: small labels, no photos needed, discounts at the end id: 'kidsBazaar', item: 'kids', + feeExample: { handedIn: 10, sold: 6, price: 5, noun: 'piece' }, examplePrices: [9, 15, 6], commission: 15, features: { @@ -57,6 +79,7 @@ export const EVENT_TYPES: EventType[] = [ // Second-hand for everyone, e.g. a women's clothing bazaar or a flea market id: 'clothingBazaar', item: 'clothing', + feeExample: { handedIn: 8, sold: 5, price: 12, noun: 'piece' }, examplePrices: [35, 24, 28], commission: 10, features: { @@ -78,6 +101,7 @@ export const EVENT_TYPES: EventType[] = [ // Fewer, pricier items: a negotiable price and questions about size and condition id: 'skiBazaar', item: 'ski', + feeExample: { handedIn: 3, sold: 2, price: 60, noun: 'item' }, examplePrices: [90, 45, 25], commission: 10, features: { @@ -98,6 +122,7 @@ export const EVENT_TYPES: EventType[] = [ // same plus private sellers only, fixed data and a limit, switched on by the organizer. id: 'bikeExchange', item: 'bike', + feeExample: { handedIn: 2, sold: 1, price: 150, noun: 'bike' }, examplePrices: [140, 65, 25], commission: 10, features: { @@ -124,6 +149,11 @@ export function findEventType(id: string | undefined): EventType | undefined { return EVENT_TYPES.find((type) => type.id === id); } +/** The worked example for a kind of bazaar (`features.eventType`); neutral without one. */ +export function feeExampleFor(eventType: string | undefined): FeeExampleCase { + return findEventType(eventType)?.feeExample ?? NEUTRAL_FEE_EXAMPLE; +} + /** * The categories a kind of bazaar preselects, as a bazaar stores them: the sub-categories * whose name or main category matches, unless the kind excludes them; a main category diff --git a/src/lib/sellerFees.test.ts b/src/lib/sellerFees.test.ts index f9f7c288..a38058fb 100644 --- a/src/lib/sellerFees.test.ts +++ b/src/lib/sellerFees.test.ts @@ -5,62 +5,138 @@ import { describeSellerFees, describeSellerRules, describeSellerSchedule, + feesFromForm, } from './sellerFees'; describe('describeSellerFees', () => { - it('explains commission and intake fee with an example', () => { - const { lines, example } = describeSellerFees({ commission: 10, intakeFee: 0.5 }); + it('explains commission and intake fee with a neutral example without a kind', () => { + const { lines, example } = describeSellerFees({ + commission: 10, + features: { intakeFee: 0.5 }, + }); expect(lines).toEqual([ - '10 % Provision vom Verkaufspreis jedes verkauften Artikels', - '0,50 € Annahmegebühr pro angenommenem Artikel, auch wenn er nicht verkauft wird', + '10 % Provision auf jeden verkauften Artikel', + '0,50 € Annahmegebühr pro angenommenem Artikel, verkauft oder nicht', ]); expect(example).toEqual({ - intro: 'Du gibst 10 Artikel ab, 6 davon werden für je 5,00 € verkauft.', - rows: [ - { label: '6 × 5,00 € verkauft', amount: 30 }, - { label: '10 % Provision', amount: -3 }, - { label: 'Annahmegebühr 10 × 0,50 €', amount: -5 }, - ], - total: 22, + text: + 'Gibst du 5 Artikel ab und verkaufst davon 3 Artikel für je 20,00 €, bekommst du ' + + '51,50 € (60,00 € − 6,00 € Provision − 2,50 € Annahmegebühr).', + total: 51.5, + groups: [], }); }); - it('names the fee cap and gives back what is above it in the example', () => { + it('fits the example to the kind of bazaar (#303)', () => { + const bike = (features = {}) => + describeSellerFees({ commission: 10, features: { eventType: 'bikeExchange', ...features } }) + .example?.text; + // Without an intake fee, what is not sold costs nothing: only the sale counts + expect(bike()).toBe( + 'Verkaufst du ein Rad für 150,00 €, bekommst du 135,00 € (150,00 € − 15,00 € Provision).' + ); + expect(bike({ intakeFee: 3 })).toBe( + 'Gibst du 2 Räder ab und verkaufst davon ein Rad für 150,00 €, bekommst du 129,00 € ' + + '(150,00 € − 15,00 € Provision − 6,00 € Annahmegebühr).' + ); + expect( + describeSellerFees({ commission: 15, features: { eventType: 'kidsBazaar' } }).example?.text + ).toBe('Verkaufst du 6 Teile für je 5,00 €, bekommst du 25,50 € (30,00 € − 4,50 € Provision).'); + // A kind that no longer exists: neutral + expect( + describeSellerFees({ commission: 10, features: { eventType: 'gone' } }).example?.text + ).toMatch(/^Verkaufst du 3 Artikel für je 20,00 €/); + }); + + it('names the fee cap and takes it into the example', () => { const { lines, example } = describeSellerFees({ commission: 10, - intakeFee: 3, - maxFeesPerSeller: 20, + features: { intakeFee: 3, maxFeesPerSeller: 20, eventType: 'kidsBazaar' }, + }); + expect(lines.at(-1)).toBe('Höchstens 20,00 € Gebühren insgesamt'); + // 3 € commission + 30 € intake fee, capped at 20 € + expect(example?.text).toBe( + 'Gibst du 10 Teile ab und verkaufst davon 6 Teile für je 5,00 €, bekommst du 10,00 € ' + + '(30,00 € − 20,00 € Gebühren, gedeckelt).' + ); + // Below the cap the fees are listed one by one + const below = describeSellerFees({ + commission: 10, + features: { intakeFee: 0.5, maxFeesPerSeller: 20 }, }); - expect(lines.at(-1)).toBe('Du zahlst höchstens 20,00 € Gebühren, alles zusammen'); - // 3 € commission + 30 € intake fee: 13 € come back - expect(example?.rows.at(-1)).toEqual({ - label: 'Gebühren-Deckel 20,00 €', - amount: 13, - credit: true, + expect(below.example?.text).toMatch(/− 6,00 € Provision − 2,50 € Annahmegebühr\)\.$/); + }); + + it('says what the seller pays when the fees are higher than the sales', () => { + const { example } = describeSellerFees({ + commission: 0, + features: { intakeFee: 4, eventType: 'kidsBazaar' }, }); - expect(example?.total).toBe(10); - // Below the cap the example has nothing to give back - const below = describeSellerFees({ commission: 10, intakeFee: 0.5, maxFeesPerSeller: 20 }); - expect(below.example?.rows).toHaveLength(3); + expect(example?.total).toBe(-10); + expect(example?.text).toMatch(/, zahlst du 10,00 € \(30,00 € − 40,00 € Annahmegebühr\)\.$/); }); - it('goes negative when the fee is higher than the sales', () => { - expect(describeSellerFees({ commission: 0, intakeFee: 4 }).example?.total).toBe(-10); + it('adds the payout of fee groups that pay less (#302)', () => { + const { example } = describeSellerFees({ + commission: 10, + features: { + eventType: 'bikeExchange', + feeGroups: [ + { id: 'm', label: 'Vereinsmitglieder', commission: 5, assignment: 'selfDeclared' }, + // Same fees, more items: nothing to add + { + id: 'h', + label: 'Helfer', + commission: 10, + maxItemsPerSeller: 9, + assignment: 'helpers', + }, + ], + }, + }); + expect(example?.groups).toEqual(['Für Vereinsmitglieder: 142,50 €.']); }); it('has nothing to explain without fees', () => { expect(describeSellerFees({ commission: 0 })).toEqual({ lines: [], example: null }); expect(describeSellerFees({ commission: 7.5 }).lines[0]).toMatch(/^7,5 % Provision/); }); + + it('reads the event form the same way, where empty numbers are NaN', () => { + const event = feesFromForm({ + commission: 10, + features: { + intakeFee: NaN, + maxFeesPerSeller: NaN, + eventType: 'bikeExchange', + feeGroups: [ + { + id: 'm', + label: 'Mitglieder', + commission: NaN, + intakeFee: NaN, + maxFeesPerSeller: NaN, + maxItemsPerSeller: NaN, + assignment: 'selfDeclared', + }, + ], + }, + }); + const { example } = describeSellerFees(event); + expect(example?.text).toMatch(/^Verkaufst du ein Rad für 150,00 €, bekommst du 135,00 €/); + expect(example?.groups).toEqual(['Für Mitglieder: 150,00 €.']); + }); }); describe('describeSellerRules', () => { - it('names the item limit and every price feature', () => { - const rules = describeSellerRules({ + it('splits what sellers must do from what they can do', () => { + const { duties, options } = describeSellerRules({ commission: 0, features: { maxItemsPerSeller: 40, photosOptional: true, + fixedSellerData: true, + privateSellersOnly: true, discounts: true, maxDiscountPercent: 30, // 15:00 in Berlin (summer time) @@ -70,40 +146,43 @@ describe('describeSellerRules', () => { questions: true, }, }); - expect(rules.map((rule) => rule.text)).toEqual([ + expect(duties.map((rule) => rule.text)).toEqual([ 'Bis zu 40 Artikel pro Verkäufer', - 'Fotos sind freiwillig', - 'Während des Basars ab 15:00 Uhr kannst du deine Preise um bis zu 30 % senken', + 'Ausweis mitbringen: Name und Anschrift werden vor Ort geprüft', + 'Nur für Privatleute, nicht gewerblich', + ]); + expect(duties[1].details).toMatch(/^Ab deinem ersten angenommenen Artikel/); + expect(options.map((rule) => rule.text)).toEqual([ + 'Rabatte bis 30 % während des Basars, ab 15:00 Uhr', 'Käufer können dir online Preise vorschlagen, du entscheidest', - 'Verhandeln an der Kasse: Du legst einen Mindestpreis fest, bis zu dem die Kasse heruntergehen darf', - 'Käufer können öffentlich Fragen zu deinen Artikeln stellen', + 'Verhandeln an der Kasse bis zu deinem Mindestpreis', + 'Käufer können online Fragen zu deinen Artikeln stellen', ]); - expect(rules.every((rule) => rule.allowed)).toBe(true); + expect([...duties, ...options].every((rule) => rule.allowed)).toBe(true); }); it('tells how many places of the whole market are left', () => { const rules = (itemPlacesLeft?: number) => - describeSellerRules({ commission: 0, features: { maxItemsTotal: 200 }, itemPlacesLeft })[1]; + describeSellerRules({ + commission: 0, + features: { maxItemsTotal: 200, photosOptional: true }, + itemPlacesLeft, + }).duties[0]; expect(rules().text).toBe('Höchstens 200 Artikel auf dem ganzen Basar'); expect(rules(23).text).toBe('Höchstens 200 Artikel auf dem ganzen Basar, noch 23 Plätze frei'); - expect(rules(0)).toEqual({ + expect(rules(0)).toMatchObject({ text: 'Der Basar ist voll: Alle 200 Plätze für Artikel sind vergeben', allowed: false, }); }); - it('says what is not offered', () => { - const rules = describeSellerRules({ + it('leaves out what the bazaar does not offer (#303)', () => { + const { duties, options } = describeSellerRules({ commission: 0, features: { discounts: false, priceOffers: false, minimumPrice: false }, }); - expect(rules[0].text).toBe('Beliebig viele Artikel pro Verkäufer'); - expect(rules[1].text).toBe('Jeder Artikel braucht mindestens ein Foto'); - expect(rules.filter((rule) => !rule.allowed).map((rule) => rule.text)).toEqual([ - 'Keine Rabatte während des Basars', - 'Keine Preisvorschläge von Käufern', - 'Kein Verhandeln an der Kasse, es gilt dein Preis', - ]); + expect(duties.map((rule) => rule.text)).toEqual(['Mindestens ein Foto pro Artikel']); + expect(options).toEqual([]); }); }); diff --git a/src/lib/sellerFees.ts b/src/lib/sellerFees.ts index 61924d84..70affd7d 100644 --- a/src/lib/sellerFees.ts +++ b/src/lib/sellerFees.ts @@ -3,6 +3,7 @@ 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 { feeExampleFor, type FeeExampleCase } from './eventTypes'; import i18n, { currentLocale } from '../i18n'; import { dateLocale } from '../i18n/format'; import { requirableFields, type CategoryField } from '../shared/categoryFields'; @@ -43,29 +44,50 @@ export function feeLockHint(lock: 'running' | 'sellers'): string { return i18n.t(`feeLock.${lock}` as never, { ns: 'organizer' }) as string; } -/** Example for sellers: 10 items handed in, 6 of them sold for 5 € each. */ -const EXAMPLE = { handedIn: 10, sold: 6, price: 5 }; - -export interface ExampleRow { - label: string; - /** Signed: income positive, fees negative */ - amount: number; - /** Fees given back by the cap */ - credit?: boolean; -} - export interface FeeExample { - intro: string; - rows: ExampleRow[]; + /** + * One sentence, e.g. "Verkaufst du ein Rad für 150,00 €, bekommst du 135,00 € + * (150,00 € − 15,00 € Provision)." + */ + text: string; /** Payout when positive, otherwise what the seller pays */ total: number; + /** The same for the fee groups whose payout differs, e.g. "Für Mitglieder: 142,50 €." */ + groups: string[]; +} + +/** What one seller pays for the example: the fees together and what the cap gives back. */ +function exampleFees( + { commission, intakeFee = 0, maxFeesPerSeller }: SellerFees, + { handedIn, sold, price }: FeeExampleCase +) { + const revenue = sold * price; + const commissionFee = commission > 0 ? Math.round(revenue * commission) / 100 : 0; + const intake = intakeFee > 0 ? Math.round(handedIn * intakeFee * 100) / 100 : 0; + const full = commissionFee + intake; + const fees = full - feeCapCredit(full, maxFeesPerSeller); + return { + revenue, + commissionFee, + intake, + fees, + total: Math.round((revenue - fees) * 100) / 100, + }; } -/** What sellers pay, in plain words, with a worked example; empty without fees. */ -export function describeSellerFees({ commission, intakeFee = 0, maxFeesPerSeller }: SellerFees): { +const euro = (amount: number) => `${formatPriceDE(amount)} €`; + +/** + * What sellers pay, in plain words, with a worked example in one sentence that fits the + * kind of bazaar (`features.eventType`, #303); empty without fees. Intake fee, cap and + * fee groups only show up when the bazaar has them. + */ +export function describeSellerFees(event: SellerConditionsEvent): { lines: string[]; example: FeeExample | null; } { + const fees = eventFees(event); + const { commission, intakeFee = 0, maxFeesPerSeller } = fees; const lines: string[] = []; if (commission > 0) { lines.push(text('commissionLine', { percent: formatPercent(commission) })); @@ -78,51 +100,36 @@ export function describeSellerFees({ commission, intakeFee = 0, maxFeesPerSeller lines.push(text('feeCapLine', { fee: formatPriceDE(maxFeesPerSeller) })); } - const revenue = EXAMPLE.sold * EXAMPLE.price; - const rows: ExampleRow[] = [ - { - label: text('exampleSold', { sold: EXAMPLE.sold, price: formatPriceDE(EXAMPLE.price) }), - amount: revenue, - }, - ]; - if (commission > 0) { - rows.push({ - label: text('exampleCommission', { percent: formatPercent(commission) }), - amount: -Math.round(revenue * commission) / 100, - }); - } - if (intakeFee > 0) { - rows.push({ - label: text('exampleIntakeFee', { - handedIn: EXAMPLE.handedIn, - fee: formatPriceDE(intakeFee), - }), - amount: -Math.round(EXAMPLE.handedIn * intakeFee * 100) / 100, - }); - } - // Fees are the negative rows; what is above the cap comes back - const fees = -rows.reduce((sum, row) => sum + Math.min(row.amount, 0), 0); - const credit = feeCapCredit(fees, maxFeesPerSeller); - if (credit > 0) { - rows.push({ - label: text('exampleFeeCap', { fee: formatPriceDE(maxFeesPerSeller ?? 0) }), - amount: credit, - credit: true, - }); - } - const total = Math.round(rows.reduce((sum, row) => sum + row.amount, 0) * 100) / 100; - return { - lines, - example: { - intro: text('exampleIntro', { - handedIn: EXAMPLE.handedIn, - sold: EXAMPLE.sold, - price: formatPriceDE(EXAMPLE.price), - }), - rows, - total, - }, - }; + const kind = feeExampleFor(event.features?.eventType); + const { revenue, commissionFee, intake, fees: paid, total } = exampleFees(fees, kind); + const items = text(`exampleItems.${kind.noun}`, { count: kind.sold, price: euro(kind.price) }); + // Without an intake fee, what is handed in but not sold costs nothing: leave it out + const sale = + intake > 0 + ? text('exampleHandIn', { + handedIn: text(`exampleHandedIn.${kind.noun}`, { count: kind.handedIn }), + items, + }) + : text('exampleSale', { items }); + const parts = + paid < commissionFee + intake + ? [text('exampleCapped', { amount: euro(paid) })] + : [ + commissionFee > 0 ? text('exampleCommission', { amount: euro(commissionFee) }) : '', + intake > 0 ? text('exampleIntakeFee', { amount: euro(intake) }) : '', + ].filter(Boolean); + const exampleText = text('exampleSentence', { + sale, + result: text(total >= 0 ? 'exampleGet' : 'examplePay', { amount: euro(Math.abs(total)) }), + parts: [euro(revenue), ...parts].join(' − '), + }); + const groups = (event.features?.feeGroups ?? []).flatMap((group) => { + const own = exampleFees(groupFees(event, group), kind).total; + return own === total || !group.label.trim() + ? [] + : [text('exampleGroup', { label: group.label.trim(), amount: euro(own) })]; + }); + return { lines, example: { text: exampleText, total, groups } }; } export interface FeeGroupTerms { @@ -171,35 +178,49 @@ export function feeGroupAdvantages(event: SellerConditionsEvent, group: FeeGroup const givenNumber = (value: number | undefined) => typeof value === 'number' && Number.isFinite(value) ? value : undefined; +interface FormFeeValues { + commission?: number; + features?: { + intakeFee?: number; + maxFeesPerSeller?: number; + maxItemsPerSeller?: number; + feeGroups?: FeeGroup[]; + eventType?: string; + }; +} + +const formGroup = (group: FeeGroup): FeeGroup => ({ + ...group, + commission: givenNumber(group.commission) ?? 0, + intakeFee: givenNumber(group.intakeFee), + maxFeesPerSeller: givenNumber(group.maxFeesPerSeller), + maxItemsPerSeller: givenNumber(group.maxItemsPerSeller), +}); + /** - * `feeGroupAdvantages` from the values of the event form, where empty numbers are NaN, - * e.g. "5 % Provision statt 10 % · bis zu 40 Artikel". + * The fees of the event form as an event, where empty numbers are NaN: for the previews of + * the wizard, which explain them the same way as the conditions. */ -export function formGroupAdvantages( - values: { - commission?: number; - features?: { intakeFee?: number; maxFeesPerSeller?: number; maxItemsPerSeller?: number }; - }, - group: FeeGroup -): string { +export function feesFromForm(values: FormFeeValues): SellerConditionsEvent { const features = values.features ?? {}; - return feeGroupAdvantages( - { - commission: givenNumber(values.commission) ?? 0, - features: { - intakeFee: givenNumber(features.intakeFee), - maxFeesPerSeller: givenNumber(features.maxFeesPerSeller), - maxItemsPerSeller: givenNumber(features.maxItemsPerSeller), - }, + return { + commission: Math.min(Math.max(givenNumber(values.commission) ?? 0, 0), 100), + features: { + intakeFee: Math.max(givenNumber(features.intakeFee) ?? 0, 0) || undefined, + maxFeesPerSeller: givenNumber(features.maxFeesPerSeller), + maxItemsPerSeller: givenNumber(features.maxItemsPerSeller), + feeGroups: (features.feeGroups ?? []).map(formGroup), + eventType: features.eventType || undefined, }, - { - ...group, - commission: givenNumber(group.commission) ?? 0, - intakeFee: givenNumber(group.intakeFee), - maxFeesPerSeller: givenNumber(group.maxFeesPerSeller), - maxItemsPerSeller: givenNumber(group.maxItemsPerSeller), - } - ).join(' · '); + }; +} + +/** + * `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: FormFeeValues, group: FeeGroup): string { + return feeGroupAdvantages(feesFromForm(values), formGroup(group)).join(' · '); } /** The fee groups as sellers read them (#302): each with its advantages and how to get in. */ @@ -220,94 +241,78 @@ export function describeFeeGroups(event: SellerConditionsEvent): FeeGroupTerms[] export interface SellerRule { text: string; - /** false for something the bazaar does not offer */ + /** More about it, shown on request */ + details?: string; + /** false when it keeps the seller out, e.g. a full market */ allowed: boolean; } -/** Item limit, photos and the price features of the bazaar, as sellers read them. */ +/** + * What applies to sellers besides the fees (#303), only what the bazaar has, not what it + * lacks: `duties` (limits, required details, ID, private sale), then `options` (discounts, + * offers, minimum price, questions). + */ export function describeSellerRules( event: SellerConditionsEvent, fieldDefinitions?: readonly CategoryField[] -): SellerRule[] { +): { duties: SellerRule[]; options: SellerRule[] } { const features = resolveEventFeatures(event); - const rules: SellerRule[] = [ - { - text: features.maxItemsPerSeller - ? text('maxItems', { max: features.maxItemsPerSeller }) - : text('unlimitedItems'), - allowed: true, - }, - { - text: features.photosOptional ? text('photosOptional') : text('photosRequired'), - allowed: true, - }, - ]; + const rule = (key: string, values?: Record, details?: string): SellerRule => ({ + text: text(key, values), + details: details && text(details), + allowed: true, + }); + const duties: SellerRule[] = []; + if (features.maxItemsPerSeller) { + duties.push(rule('maxItems', { max: features.maxItemsPerSeller })); + } if (features.maxItemsTotal) { const left = event.itemPlacesLeft; - rules.splice(1, 0, { - text: - left === 0 - ? text('marketFull', { max: features.maxItemsTotal }) - : left !== undefined - ? text('placesLeft', { count: left, max: features.maxItemsTotal }) - : text('maxItemsTotal', { max: features.maxItemsTotal }), + duties.push({ + ...rule(left === 0 ? 'marketFull' : left !== undefined ? 'placesLeft' : 'maxItemsTotal', { + count: left, + max: features.maxItemsTotal, + }), allowed: left !== 0, }); } - if (!features.publicCatalog) { - rules.push({ text: text('noPublicCatalog'), allowed: true }); - } + if (!features.photosOptional) duties.push(rule('photosRequired')); const required = requirableFields(fieldDefinitions).filter((field) => features.requiredFields?.includes(field.key) ); if (required.length > 0) { - rules.push({ - text: text('requiredFields', { + duties.push( + rule('requiredFields', { fields: required .map((field) => categoryFieldText(field, 'label') ?? field.label) .join(', '), - }), - allowed: true, - }); - } - if (features.directSale) { - rules.push({ text: text('directSale'), allowed: true }); + }) + ); } - if (features.privateSellersOnly) { - rules.push({ text: text('privateSellers'), allowed: true }); - } - if (features.fixedSellerData) { - rules.push({ text: text('fixedData'), allowed: true }); + if (features.fixedSellerData) duties.push(rule('fixedData', undefined, 'fixedDataDetails')); + if (features.privateSellersOnly) duties.push(rule('privateSellers')); + if (features.directSale) duties.push(rule('directSale', undefined, 'directSaleDetails')); + if (!features.publicCatalog) { + duties.push(rule('noPublicCatalog', undefined, 'noPublicCatalogDetails')); } + + const options: SellerRule[] = []; if (features.discounts) { - rules.push({ - text: - features.discountStartsAt !== undefined - ? text('discountsFrom', { - time: formatBerlinTime(features.discountStartsAt), - percent: features.maxDiscountPercent, - }) - : text('discounts', { percent: features.maxDiscountPercent }), - allowed: true, - }); - } else { - rules.push({ text: text('noDiscounts'), allowed: false }); + options.push( + features.discountStartsAt !== undefined + ? rule('discountsFrom', { + time: formatBerlinTime(features.discountStartsAt), + percent: features.maxDiscountPercent, + }) + : rule('discounts', { percent: features.maxDiscountPercent }) + ); } - rules.push( - features.priceOffers - ? { text: text('offers'), allowed: true } - : { text: text('noOffers'), allowed: false }, - features.minimumPrice - ? { text: text('minimumPrice'), allowed: true } - : { text: text('noMinimumPrice'), allowed: false } - ); + if (features.priceOffers) options.push(rule('offers')); + if (features.minimumPrice) options.push(rule('minimumPrice')); if (features.questions) { - rules.push({ - text: features.questionsDuringEventOnly ? text('questionsDuringEvent') : text('questions'), - allowed: true, - }); + options.push(rule(features.questionsDuringEventOnly ? 'questionsDuringEvent' : 'questions')); } - return rules; + return { duties, options }; } /** diff --git a/src/locales/de/events.json b/src/locales/de/events.json index 922435d2..f54eaa42 100644 --- a/src/locales/de/events.json +++ b/src/locales/de/events.json @@ -86,41 +86,30 @@ "fees": "Gebühren", "noFees": "Keine Gebühren: Du bekommst den vollen Verkaufspreis.", "example": "Rechenbeispiel", - "youGet": "Du bekommst", - "youPay": "Du zahlst", - "itemsAndPrices": "Artikel & Preise", "schedule": "Abgabe & Abholung", "scheduleDirect": "Aufbau & Abbau", - "commissionLine": "{{percent}} % Provision vom Verkaufspreis jedes verkauften Artikels", - "intakeFeeLine": "{{fee}} € Annahmegebühr pro angenommenem Artikel, auch wenn er nicht verkauft wird", - "exampleSold": "{{sold}} × {{price}} € verkauft", - "exampleCommission": "{{percent}} % Provision", - "exampleIntakeFee": "Annahmegebühr {{handedIn}} × {{fee}} €", - "exampleIntro": "Du gibst {{handedIn}} Artikel ab, {{sold}} davon werden für je {{price}} € verkauft.", + "commissionLine": "{{percent}} % Provision auf jeden verkauften Artikel", + "intakeFeeLine": "{{fee}} € Annahmegebühr pro angenommenem Artikel, verkauft oder nicht", + "exampleCommission": "{{amount}} Provision", + "exampleIntakeFee": "{{amount}} Annahmegebühr", "maxItems": "Bis zu {{max}} Artikel pro Verkäufer", - "unlimitedItems": "Beliebig viele Artikel pro Verkäufer", - "photosOptional": "Fotos sind freiwillig", - "photosRequired": "Jeder Artikel braucht mindestens ein Foto", - "noPublicCatalog": "Keine Online-Liste: Käufer sehen deine Artikel erst vor Ort, das QR-Etikett zeigt dort den Preis", - "discounts": "Während des Basars kannst du deine Preise um bis zu {{percent}} % senken", - "discountsFrom": "Während des Basars ab {{time}} Uhr kannst du deine Preise um bis zu {{percent}} % senken", - "noDiscounts": "Keine Rabatte während des Basars", + "photosRequired": "Mindestens ein Foto pro Artikel", + "noPublicCatalog": "Deine Artikel stehen nicht online", + "discounts": "Rabatte bis {{percent}} % während des Basars", + "discountsFrom": "Rabatte bis {{percent}} % während des Basars, ab {{time}} Uhr", "offers": "Käufer können dir online Preise vorschlagen, du entscheidest", - "noOffers": "Keine Preisvorschläge von Käufern", - "minimumPrice": "Verhandeln an der Kasse: Du legst einen Mindestpreis fest, bis zu dem die Kasse heruntergehen darf", - "noMinimumPrice": "Kein Verhandeln an der Kasse, es gilt dein Preis", - "questions": "Käufer können öffentlich Fragen zu deinen Artikeln stellen", + "minimumPrice": "Verhandeln an der Kasse bis zu deinem Mindestpreis", + "questions": "Käufer können online Fragen zu deinen Artikeln stellen", "dropoff": "Abgabe", "pickup": "Abholung", "setup": "Aufbau", "teardown": "Abbau", - "requiredFields": "Pflichtangaben für jeden Artikel: {{fields}}", - "questionsDuringEvent": "Käufer können während des Basars öffentlich Fragen zu deinen Artikeln stellen", - "privateSellers": "Nur für Privatleute: Du bestätigst beim Anmelden, dass du nicht gewerblich verkaufst", - "fixedData": "Bring deinen Ausweis mit: Der Veranstalter prüft vor Ort Name und Anschrift. Sobald er deinen ersten Artikel annimmt, sind sie fest, ebenso die Angaben zu angenommenen Artikeln. Der Veranstalter führt darüber einen Nachweis", - "directSale": "Direktverkauf: Du bist bei deinem Artikel, Käufer einigen sich mit dir auf den Preis und bezahlen dich direkt. Danach bucht die Kasse den Verkauf zum vereinbarten Preis, dort zahlst du nur die Provision", - "feeCapLine": "Du zahlst höchstens {{fee}} € Gebühren, alles zusammen", - "exampleFeeCap": "Gebühren-Deckel {{fee}} €", + "requiredFields": "Pflichtangaben je Artikel: {{fields}}", + "questionsDuringEvent": "Käufer können während des Basars Fragen zu deinen Artikeln stellen", + "privateSellers": "Nur für Privatleute, nicht gewerblich", + "fixedData": "Ausweis mitbringen: Name und Anschrift werden vor Ort geprüft", + "directSale": "Direktverkauf: Käufer bezahlen dich direkt an deinem Artikel", + "feeCapLine": "Höchstens {{fee}} € Gebühren insgesamt", "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", @@ -149,7 +138,36 @@ "choiceDialogTitle": "Deine Gebührengruppe", "choiceSave": "Speichern", "groupIntakeFeeInstead": "{{fee}} € pro Artikel statt {{base}} €", - "groupSame": "gleiche Gebühren wie alle" + "groupSame": "gleiche Gebühren wie alle", + "duties": "Das gilt für dich", + "options": "Das ist möglich", + "details": "Mehr dazu", + "exampleSentence": "{{sale}}, {{result}} ({{parts}}).", + "exampleSale": "Verkaufst du {{items}}", + "exampleHandIn": "Gibst du {{handedIn}} ab und verkaufst davon {{items}}", + "exampleItems": { + "item_one": "einen Artikel für {{price}}", + "item_other": "{{count}} Artikel für je {{price}}", + "piece_one": "ein Teil für {{price}}", + "piece_other": "{{count}} Teile für je {{price}}", + "bike_one": "ein Rad für {{price}}", + "bike_other": "{{count}} Räder für je {{price}}" + }, + "exampleHandedIn": { + "item_one": "einen Artikel", + "item_other": "{{count}} Artikel", + "piece_one": "ein Teil", + "piece_other": "{{count}} Teile", + "bike_one": "ein Rad", + "bike_other": "{{count}} Räder" + }, + "exampleGet": "bekommst du {{amount}}", + "examplePay": "zahlst du {{amount}}", + "exampleCapped": "{{amount}} Gebühren, gedeckelt", + "exampleGroup": "Für {{label}}: {{amount}}.", + "noPublicCatalogDetails": "Käufer sehen sie erst vor Ort, das QR-Etikett zeigt dort den Preis.", + "fixedDataDetails": "Ab deinem ersten angenommenen Artikel sind sie fest, ebenso die Angaben zu angenommenen Artikeln. Der Veranstalter führt darüber einen Nachweis.", + "directSaleDetails": "Ihr einigt euch auf den Preis, danach bucht die Kasse den Verkauf zum vereinbarten Preis. Dort zahlst du nur die Provision." }, "sidebar": { "details": "Basar-Details", diff --git a/src/locales/de/organizer.json b/src/locales/de/organizer.json index 7f5d872e..cf6aa519 100644 --- a/src/locales/de/organizer.json +++ b/src/locales/de/organizer.json @@ -201,7 +201,10 @@ "maxFees": "Gebühren-Deckel pro Verkäufer in € (optional)", "noCap": "kein Deckel", "maxFeesHint": "Ein Verkäufer zahlt insgesamt höchstens so viel Provision und Annahmegebühr, z. B. 20 € bei teuren Rädern. Was darüber liegt, geht bei der Abrechnung an ihn zurück. Beim Direktverkauf nimmt die Kasse dann keine Provision mehr.", - "maxFeesLater": "Sobald sich der erste Verkäufer angemeldet hat, kannst du ihn nur noch senken." + "maxFeesLater": "Sobald sich der erste Verkäufer angemeldet hat, kannst du ihn nur noch senken.", + "feeExample": "Rechenbeispiel für Verkäufer", + "feeExampleHint": "Die Bedingungen rechnen ein Beispiel, das zur Art des Basars passt, z. B. ein Rad für 150 € statt sechs Teile für je 5 €.", + "feeExampleNeutral": "Allgemein" }, "logistics": { "title": "Abgabe & Abholung", @@ -1059,7 +1062,8 @@ "maxItemsTotal": "{{count}} Plätze für Artikel insgesamt", "feeCap": "Höchstens {{fee}} Gebühren pro Verkäufer", "feeCapExample": "Gebühren-Deckel {{fee}}", - "feeGroup": "{{label}}: {{advantages}}" + "feeGroup": "{{label}}: {{advantages}}", + "example": "Rechenbeispiel" }, "short": { "type": "Art", diff --git a/src/locales/en/events.json b/src/locales/en/events.json index dcb8a10b..84b88b56 100644 --- a/src/locales/en/events.json +++ b/src/locales/en/events.json @@ -86,41 +86,30 @@ "fees": "Fees", "noFees": "No fees: you get the full sale price.", "example": "Example", - "youGet": "You get", - "youPay": "You pay", - "itemsAndPrices": "Items & prices", "schedule": "Hand-in & pickup", "scheduleDirect": "Setup & teardown", - "commissionLine": "{{percent}} % commission on the sale price of every item sold", - "intakeFeeLine": "{{fee}} € intake fee per accepted item, even if it is not sold", - "exampleSold": "{{sold}} × {{price}} € sold", - "exampleCommission": "{{percent}} % commission", - "exampleIntakeFee": "Intake fee {{handedIn}} × {{fee}} €", - "exampleIntro": "You hand in {{handedIn}} items, {{sold}} of them sell for {{price}} € each.", + "commissionLine": "{{percent}} % commission on every item sold", + "intakeFeeLine": "{{fee}} € intake fee per accepted item, sold or not", + "exampleCommission": "{{amount}} commission", + "exampleIntakeFee": "{{amount}} intake fee", "maxItems": "Up to {{max}} items per seller", - "unlimitedItems": "Any number of items per seller", - "photosOptional": "Photos are optional", - "photosRequired": "Every item needs at least one photo", - "noPublicCatalog": "No online list: buyers see your items on site only, where the QR label shows the price", - "discounts": "During the bazaar you can lower your prices by up to {{percent}} %", - "discountsFrom": "During the bazaar from {{time}} you can lower your prices by up to {{percent}} %", - "noDiscounts": "No discounts during the bazaar", + "photosRequired": "At least one photo per item", + "noPublicCatalog": "Your items are not listed online", + "discounts": "Discounts of up to {{percent}} % during the bazaar", + "discountsFrom": "Discounts of up to {{percent}} % during the bazaar, from {{time}}", "offers": "Buyers can suggest prices to you online, you decide", - "noOffers": "No price offers from buyers", - "minimumPrice": "Haggling at the cash desk: you set a minimum price the cash desk may go down to", - "noMinimumPrice": "No haggling at the cash desk, your price applies", - "questions": "Buyers can ask public questions about your items", + "minimumPrice": "Haggling at the cash desk down to your minimum price", + "questions": "Buyers can ask questions about your items online", "dropoff": "Hand-in", "pickup": "Pickup", "setup": "Setup", "teardown": "Teardown", "requiredFields": "Required for every item: {{fields}}", - "questionsDuringEvent": "During the bazaar, buyers can ask public questions about your items", - "privateSellers": "Private persons only: you confirm when registering that you do not sell commercially", - "fixedData": "Bring your ID: the organizer checks your name and address on site. Once your first item is accepted, they are fixed, and so are the details of accepted items. The organizer keeps a record of them", - "directSale": "Direct sale: you stay with your item, buyers agree on the price with you and pay you directly. Then the cash desk books the sale at the agreed price, where you only pay the commission", - "feeCapLine": "You pay at most {{fee}} € of fees, all together", - "exampleFeeCap": "Fee cap {{fee}} €", + "questionsDuringEvent": "During the bazaar, buyers can ask questions about your items", + "privateSellers": "Private persons only, not commercial", + "fixedData": "Bring your ID: name and address are checked on site", + "directSale": "Direct sale: buyers pay you directly at your item", + "feeCapLine": "At most {{fee}} € of fees in total", "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", @@ -149,7 +138,36 @@ "choiceDialogTitle": "Your fee group", "choiceSave": "Save", "groupIntakeFeeInstead": "{{fee}} € per item instead of {{base}} €", - "groupSame": "same fees as everyone" + "groupSame": "same fees as everyone", + "duties": "What applies to you", + "options": "What you can do", + "details": "More", + "exampleSentence": "{{sale}}, {{result}} ({{parts}}).", + "exampleSale": "If you sell {{items}}", + "exampleHandIn": "If you hand in {{handedIn}} and sell {{items}}", + "exampleItems": { + "item_one": "one item for {{price}}", + "item_other": "{{count}} items for {{price}} each", + "piece_one": "one item for {{price}}", + "piece_other": "{{count}} items for {{price}} each", + "bike_one": "one bike for {{price}}", + "bike_other": "{{count}} bikes for {{price}} each" + }, + "exampleHandedIn": { + "item_one": "one item", + "item_other": "{{count}} items", + "piece_one": "one item", + "piece_other": "{{count}} items", + "bike_one": "one bike", + "bike_other": "{{count}} bikes" + }, + "exampleGet": "you get {{amount}}", + "examplePay": "you pay {{amount}}", + "exampleCapped": "{{amount}} fees, capped", + "exampleGroup": "For {{label}}: {{amount}}.", + "noPublicCatalogDetails": "Buyers see them on site only, where the QR label shows the price.", + "fixedDataDetails": "Once your first item is accepted, they are fixed, and so are the details of accepted items. The organizer keeps a record of them.", + "directSaleDetails": "You agree on the price, then the cash desk books the sale at that price. There you only pay the commission." }, "sidebar": { "details": "Bazaar details", diff --git a/src/locales/en/organizer.json b/src/locales/en/organizer.json index 31d80106..df1e2994 100644 --- a/src/locales/en/organizer.json +++ b/src/locales/en/organizer.json @@ -201,7 +201,10 @@ "maxFees": "Fee cap per seller in € (optional)", "noCap": "no cap", "maxFeesHint": "A seller pays at most this much commission and intake fee in total, e.g. €20 for expensive bikes. Whatever is above it goes back to them with the settlement. At a direct sale the cash desk then takes no more commission.", - "maxFeesLater": "Once the first seller has registered, you can only lower it." + "maxFeesLater": "Once the first seller has registered, you can only lower it.", + "feeExample": "Worked example for sellers", + "feeExampleHint": "The conditions work out an example that fits the kind of bazaar, e.g. one bike for 150 € instead of six items for 5 € each.", + "feeExampleNeutral": "General" }, "logistics": { "title": "Drop-off & pickup", @@ -1059,7 +1062,8 @@ "maxItemsTotal": "{{count}} places for items in total", "feeCap": "At most {{fee}} of fees per seller", "feeCapExample": "Fee cap {{fee}}", - "feeGroup": "{{label}}: {{advantages}}" + "feeGroup": "{{label}}: {{advantages}}", + "example": "Worked example" }, "short": { "type": "Kind", diff --git a/src/pages/organizer/events/EditEventForm.tsx b/src/pages/organizer/events/EditEventForm.tsx index a7ca8b48..658d2b95 100644 --- a/src/pages/organizer/events/EditEventForm.tsx +++ b/src/pages/organizer/events/EditEventForm.tsx @@ -197,6 +197,8 @@ const buildEventSchema = ( registrationOpen: z.boolean(), registrationStartsAt: z.string(), registrationEndsAt: z.string(), + /** The kind of bazaar (#303); empty: none */ + eventType: z.string(), intakeFee: z .number() .min(0, zodMessage('form.feeNegative', 'organizer')) @@ -461,6 +463,7 @@ function featuresToForm(stored: StoredEventFeatures | undefined): FeatureFormDat registrationEndsAt: features.registrationEndsAt ? formatForDateTimeLocal(features.registrationEndsAt) : '', + eventType: findEventType(features.eventType)?.id ?? '', }; } @@ -474,9 +477,13 @@ function givenNumber(value: number | undefined): number | undefined { * the fee cap are sent as null when empty: the backend keeps a value that is left out, so * an older app that does not know them cannot delete them. */ -type FeaturesArgs = Omit & { +type FeaturesArgs = Omit< + StoredEventFeatures, + 'maxItemsTotal' | 'maxFeesPerSeller' | 'eventType' +> & { maxItemsTotal: number | null; maxFeesPerSeller: number | null; + eventType: string | null; }; function featuresFromForm(features: FeatureFormData): FeaturesArgs { @@ -525,15 +532,17 @@ function featuresFromForm(features: FeatureFormData): FeaturesArgs { registrationOpen: features.registrationOpen, registrationStartsAt: timeFromForm(features.registrationOpen, features.registrationStartsAt), registrationEndsAt: timeFromForm(features.registrationOpen, features.registrationEndsAt), + eventType: features.eventType || null, }; } /** The features as stored, for previews: a cleared value is just not there. */ -function storedFeatures({ maxItemsTotal, maxFeesPerSeller, ...rest }: FeaturesArgs) { +function storedFeatures({ maxItemsTotal, maxFeesPerSeller, eventType, ...rest }: FeaturesArgs) { return { ...rest, maxItemsTotal: maxItemsTotal ?? undefined, maxFeesPerSeller: maxFeesPerSeller ?? undefined, + eventType: eventType ?? undefined, } satisfies StoredEventFeatures; } @@ -803,7 +812,13 @@ function EventSection({ return ( - + ); @@ -1095,7 +1110,8 @@ export function EditEventForm({ after }: { after?: ReactNode } = {}) { coverTemplate: current.coverImageFile ? undefined : coverForKind(type.item), commission: type.commission, categories: matching.length > 0 ? matching : current.categories, - features: featuresToForm(type.features), + // Kept with the bazaar: the conditions show an example that fits it (#303) + features: featuresToForm({ ...type.features, eventType: type.id }), }); setEventType(id); setStep(1); @@ -1251,7 +1267,12 @@ export function EditEventForm({ after }: { after?: ReactNode } = {}) { ...current, ...draft.values, coverTemplate: draft.values.coverTemplate ?? undefined, - features: { ...current.features, ...withoutNulls(draft.values.features) }, + features: { + ...current.features, + ...withoutNulls(draft.values.features), + // Drafts from before #303 only knew the kind beside the values + eventType: draft.values.features?.eventType ?? findEventType(draft.eventType)?.id ?? '', + }, }); setPendingLocationCategories(draft.pendingLocationCategories); setEventType(findEventType(draft.eventType)?.id); diff --git a/src/pages/organizer/events/components/EditEventFeatures.tsx b/src/pages/organizer/events/components/EditEventFeatures.tsx index f5676b59..6e121f82 100644 --- a/src/pages/organizer/events/components/EditEventFeatures.tsx +++ b/src/pages/organizer/events/components/EditEventFeatures.tsx @@ -1,5 +1,6 @@ import { FormSection, FORM_ROWS } from '../../../../components/ui/form-section'; import { NativeSelect } from '../../../../components/ui/native-select'; +import { EVENT_TYPES } from '../../../../lib/eventTypes'; import { FieldError } from '../../../../components/ui/field-error'; import type { ReactNode } from 'react'; import { Controller, useFormContext } from 'react-hook-form'; @@ -365,8 +366,11 @@ export function EditEventFeatures({ parts = ALL_PARTS, showHeader = true, bare = false, + feeExampleKind = false, }: { feeLock?: FeeLock; + /** The kind of bazaar for the worked example of the conditions (#303); the wizard asks first */ + feeExampleKind?: boolean; parts?: FeaturePart[]; showHeader?: boolean; /** Without its own card, e.g. the intake fee next to the commission */ @@ -609,6 +613,21 @@ export function EditEventFeatures({ feeLock={feeLock} error={featureErrors?.maxFeesPerSeller?.message} /> + {feeExampleKind && ( +
+ + {t('features.feeExample')} + + + + {EVENT_TYPES.map((type) => ( + + ))} + +
+ )} )} diff --git a/src/pages/organizer/events/components/wizard/WizardPreviews.tsx b/src/pages/organizer/events/components/wizard/WizardPreviews.tsx index 552a7b18..dfe41fbb 100644 --- a/src/pages/organizer/events/components/wizard/WizardPreviews.tsx +++ b/src/pages/organizer/events/components/wizard/WizardPreviews.tsx @@ -41,7 +41,7 @@ import { coverUrl } from '../../../../../lib/eventCovers'; import { EVENT_TYPES, type EventType } from '../../../../../lib/eventTypes'; import { describeSellerFees, - formatSignedEuro, + feesFromForm, type SellerConditionsEvent, formGroupAdvantages, } from '../../../../../lib/sellerFees'; @@ -100,6 +100,7 @@ interface WizardValues { privateSellersOnly?: boolean; fixedSellerData?: boolean; directSale?: boolean; + eventType?: string; }; sellerLogistics?: { dropoffStart?: string; @@ -518,8 +519,13 @@ export function FeesPreview({ type }: { type?: EventType }) { const kept = cap === undefined ? fullCommission : Math.min(fullCommission, Math.max(cap, 0)); const sellerGets = Math.max(price - kept, 0); const sellerShare = price > 0 ? (sellerGets / price) * 100 : 100; - // The worked example sellers also see in the conditions - const { example } = describeSellerFees({ commission, intakeFee, maxFeesPerSeller: cap }); + // The worked example sellers also see in the conditions, for the chosen kind of bazaar + const { example } = describeSellerFees( + feesFromForm({ + ...values, + features: { ...values.features, eventType: values.features?.eventType || type?.id }, + }) + ); return ( @@ -585,26 +591,14 @@ export function FeesPreview({ type }: { type?: EventType }) { ))} {example && ( -
-

{example.intro}

-
- {example.rows.map((row) => ( -
-
{row.label}
-
{formatSignedEuro(row.amount)}
-
- ))} -
-
{t('wizard.preview.sellerGets')}
-
{formatPriceDE(example.total)} €
-
-
+
+

{t('wizard.preview.example')}

+

{example.text}

+ {example.groups.map((group) => ( +

+ {group} +

+ ))}
)} diff --git a/src/shared/eventFeatures.ts b/src/shared/eventFeatures.ts index f26ccbdb..0a5b672f 100644 --- a/src/shared/eventFeatures.ts +++ b/src/shared/eventFeatures.ts @@ -84,6 +84,11 @@ export interface EventFeatures { registrationStartsAt?: number; /** Joining ends at this time; unset: with the bazaar. */ registrationEndsAt?: number; + /** + * The kind of bazaar chosen in the creation wizard (`EVENT_TYPES` in src/lib/eventTypes.ts), + * e.g. "bikeExchange"; the conditions pick their worked example by it (#303). Unset: none. + */ + eventType?: string; } export type StoredEventFeatures = Partial;