From 9ec1afb7d218567796f38e2bb7c86566e275293a Mon Sep 17 00:00:00 2001 From: Ivo Zeitz Date: Mon, 2 Nov 2026 10:21:45 +0100 Subject: [PATCH 01/14] feat(labels): the bazaar decides whether labels carry the seller number Without a number a label holds nothing specific to one bazaar, so sellers can reuse it at the next one. On by default, older clients keep the value. Drafts saved before a new switch existed take its default. Co-Authored-By: Claude Opus 5.5 --- backend/src/modules/events.rs | 13 +++++++- backend/src/modules/features.rs | 5 +++ backend/src/modules/labels.rs | 11 ++++--- backend/src/modules/products.rs | 1 + backend/tests/api/reminders.rs | 32 +++++++++++++++++++ src/lib/api/types.ts | 12 +++++++ src/locales/de/company.json | 2 +- src/locales/de/organizer.json | 6 +++- src/locales/de/seller.json | 1 + src/locales/en/company.json | 2 +- src/locales/en/organizer.json | 6 +++- src/locales/en/seller.json | 1 + src/pages/organizer/events/EditEventForm.tsx | 11 ++++++- .../events/components/EditEventFeatures.tsx | 7 ++++ .../components/wizard/WizardPreviews.tsx | 22 +++++++++++-- .../components/EventSettingsSummary.tsx | 1 + .../components/LabelPrintDialog.test.tsx | 17 ++++++++++ .../products/components/LabelPrintDialog.tsx | 3 ++ src/shared/eventFeatures.ts | 6 ++++ 19 files changed, 146 insertions(+), 13 deletions(-) diff --git a/backend/src/modules/events.rs b/backend/src/modules/events.rs index 43220e24..b0d92de7 100644 --- a/backend/src/modules/events.rs +++ b/backend/src/modules/events.rs @@ -578,6 +578,7 @@ struct FeaturesArgs { max_items_per_seller: Option, label_format: Option, price_on_label: Option, + seller_number_on_label: Option, intake_fee: Option, private_sellers_only: Option, fixed_seller_data: Option, @@ -701,6 +702,15 @@ fn sanitize_features(features: FeaturesArgs, previous: Option<&Value>) -> AppRes "priceOnLabel", json!(features.price_on_label.unwrap_or(false)), ); + put( + "sellerNumberOnLabel", + json!( + features + .seller_number_on_label + .or(previous_bool("sellerNumberOnLabel")) + .unwrap_or(true) + ), + ); put( "intakeFee", json!(sanitize_intake_fee(features.intake_fee)?), @@ -1483,7 +1493,7 @@ mod tests { intake_fee: Some(0.555), ..FeaturesArgs::default() }, - Some(&json!({ "fixedSellerData": true })), + Some(&json!({ "fixedSellerData": true, "sellerNumberOnLabel": false })), ) .unwrap(); assert_eq!(stored["discounts"], false); @@ -1492,6 +1502,7 @@ mod tests { assert_eq!(stored["intakeFee"], 0.56); // Not sent by an older client: kept assert_eq!(stored["fixedSellerData"], true); + assert_eq!(stored["sellerNumberOnLabel"], false); assert_eq!(stored["labelFormat"], "standard"); } diff --git a/backend/src/modules/features.rs b/backend/src/modules/features.rs index 820c833a..921dc6c9 100644 --- a/backend/src/modules/features.rs +++ b/backend/src/modules/features.rs @@ -28,6 +28,7 @@ struct Stored { max_items_per_seller: Option, label_format: Option, price_on_label: Option, + seller_number_on_label: Option, intake_fee: Option, private_sellers_only: Option, fixed_seller_data: Option, @@ -47,6 +48,8 @@ pub struct EventFeatures { pub max_items_per_seller: Option, pub label_format: String, pub price_on_label: bool, + /// Off: labels carry no seller number, so they stay valid for the seller's next bazaar + pub seller_number_on_label: bool, /// Fixed fee in € per accepted item, kept from the payout pub intake_fee: Option, pub private_sellers_only: bool, @@ -76,6 +79,7 @@ pub fn resolve(features: Option<&Value>) -> EventFeatures { max_items_per_seller: stored.max_items_per_seller.map(|n| n.max(0.0) as u32), label_format: stored.label_format.unwrap_or_else(|| "standard".to_owned()), price_on_label: stored.price_on_label.unwrap_or(false), + seller_number_on_label: stored.seller_number_on_label.unwrap_or(true), intake_fee: stored .intake_fee .and_then(Decimal::from_f64_retain) @@ -147,6 +151,7 @@ mod tests { assert_eq!(features.max_discount_percent, 50); assert!(!features.price_offers && !features.questions && !features.fixed_seller_data); assert_eq!(features.label_format, "standard"); + assert!(features.seller_number_on_label); } #[test] diff --git a/backend/src/modules/labels.rs b/backend/src/modules/labels.rs index 199aba40..c0a1b04e 100644 --- a/backend/src/modules/labels.rs +++ b/backend/src/modules/labels.rs @@ -98,10 +98,13 @@ async fn get_label_data(ctx: &mut Ctx, args: LabelArgs) -> AppResult { let mut seller_number = None; let mut price = None; if let Some(label_event) = &label_event { - seller_number = docs::event_seller(ctx.conn(), label_event.id, product.vendor_id) - .await? - .and_then(|row| row.number); - let format = label_event.resolved_features().label_format; + let features = label_event.resolved_features(); + if features.seller_number_on_label { + seller_number = docs::event_seller(ctx.conn(), label_event.id, product.vendor_id) + .await? + .and_then(|row| row.number); + } + let format = features.label_format; if !formats.contains(&format) { formats.push(format); } diff --git a/backend/src/modules/products.rs b/backend/src/modules/products.rs index 3e3fbfa9..6835b5cd 100644 --- a/backend/src/modules/products.rs +++ b/backend/src/modules/products.rs @@ -653,6 +653,7 @@ fn features_json(event: &Event) -> Value { "photosOptional": f.photos_optional, "labelFormat": f.label_format, "priceOnLabel": f.price_on_label, + "sellerNumberOnLabel": f.seller_number_on_label, "privateSellersOnly": f.private_sellers_only, "fixedSellerData": f.fixed_seller_data, }); diff --git a/backend/tests/api/reminders.rs b/backend/tests/api/reminders.rs index 3557096e..6a28aeb8 100644 --- a/backend/tests/api/reminders.rs +++ b/backend/tests/api/reminders.rs @@ -382,6 +382,38 @@ async fn label_data_for_sellers_and_the_team(db: PgPool) { ); } +#[sqlx::test(migrator = "bazarpro_backend::MIGRATOR")] +async fn labels_without_the_seller_number_when_the_bazaar_turns_it_off(db: PgPool) { + let app = TestApp::new(db.clone()); + let organizer = fixtures::user(&db, "Orga").await; + let seller = fixtures::user(&db, "Seller").await; + let event = fixtures::event( + &db, + EventSpec { + features: json!({ "sellerNumberOnLabel": false }), + ..EventSpec::new("Basar", organizer) + }, + ) + .await; + fixtures::role(&db, event, seller, "seller").await; + fixtures::event_seller(&db, event, seller, 12, false).await; + let jacket = fixtures::product(&db, seller, "Jacke", 15.0).await; + fixtures::event_product(&db, event, jacket, "announced").await; + + let as_seller = fixtures::session(&db, seller).await; + let data = app + .query( + "labels.getLabelData", + json!({ "productIds": [jacket], "eventId": event }), + Some(&as_seller), + ) + .await + .body["value"] + .clone(); + assert_eq!(data["labels"][0]["title"], "Jacke"); + assert!(data["labels"][0].get("sellerNumber").is_none()); +} + async fn end_days_ago(db: &PgPool, event: Uuid, days: i32) { sqlx::query( "UPDATE events SET start_date = now() - make_interval(days => $2, hours => 6), diff --git a/src/lib/api/types.ts b/src/lib/api/types.ts index eaf0ea9a..9dc8a8a8 100644 --- a/src/lib/api/types.ts +++ b/src/lib/api/types.ts @@ -104,6 +104,7 @@ export interface Docs { maxItemsPerSeller?: number | undefined; labelFormat?: 'small' | 'standard' | undefined; priceOnLabel?: boolean | undefined; + sellerNumberOnLabel?: boolean | undefined; intakeFee?: number | undefined; privateSellersOnly?: boolean | undefined; fixedSellerData?: boolean | undefined; @@ -368,6 +369,7 @@ export type EventFeatures = { maxItemsPerSeller?: number | undefined; labelFormat: 'small' | 'standard'; priceOnLabel: boolean; + sellerNumberOnLabel: boolean; intakeFee?: number | undefined; privateSellersOnly: boolean; fixedSellerData: boolean; @@ -977,6 +979,7 @@ export interface Api { maxItemsPerSeller?: number | undefined; labelFormat?: 'small' | 'standard' | undefined; priceOnLabel?: boolean | undefined; + sellerNumberOnLabel?: boolean | undefined; intakeFee?: number | undefined; privateSellersOnly?: boolean | undefined; fixedSellerData?: boolean | undefined; @@ -1044,6 +1047,7 @@ export interface Api { maxItemsPerSeller?: number | undefined; labelFormat?: 'small' | 'standard' | undefined; priceOnLabel?: boolean | undefined; + sellerNumberOnLabel?: boolean | undefined; intakeFee?: number | undefined; privateSellersOnly?: boolean | undefined; fixedSellerData?: boolean | undefined; @@ -1113,6 +1117,7 @@ export interface Api { maxItemsPerSeller?: number | undefined; labelFormat?: 'small' | 'standard' | undefined; priceOnLabel?: boolean | undefined; + sellerNumberOnLabel?: boolean | undefined; intakeFee?: number | undefined; privateSellersOnly?: boolean | undefined; fixedSellerData?: boolean | undefined; @@ -1182,6 +1187,7 @@ export interface Api { maxItemsPerSeller?: number | undefined; labelFormat?: 'small' | 'standard' | undefined; priceOnLabel?: boolean | undefined; + sellerNumberOnLabel?: boolean | undefined; intakeFee?: number | undefined; privateSellersOnly?: boolean | undefined; fixedSellerData?: boolean | undefined; @@ -1259,6 +1265,7 @@ export interface Api { maxItemsPerSeller?: number | undefined; labelFormat?: 'small' | 'standard' | undefined; priceOnLabel?: boolean | undefined; + sellerNumberOnLabel?: boolean | undefined; intakeFee?: number | undefined; privateSellersOnly?: boolean | undefined; fixedSellerData?: boolean | undefined; @@ -1329,6 +1336,7 @@ export interface Api { maxItemsPerSeller?: number | undefined; labelFormat?: 'small' | 'standard' | undefined; priceOnLabel?: boolean | undefined; + sellerNumberOnLabel?: boolean | undefined; intakeFee?: number | undefined; privateSellersOnly?: boolean | undefined; fixedSellerData?: boolean | undefined; @@ -1396,6 +1404,7 @@ export interface Api { maxItemsPerSeller?: number | undefined; labelFormat?: 'small' | 'standard' | undefined; priceOnLabel?: boolean | undefined; + sellerNumberOnLabel?: boolean | undefined; intakeFee?: number | undefined; privateSellersOnly?: boolean | undefined; fixedSellerData?: boolean | undefined; @@ -1449,6 +1458,7 @@ export interface Api { maxItemsPerSeller?: number | undefined; labelFormat?: 'small' | 'standard' | undefined; priceOnLabel?: boolean | undefined; + sellerNumberOnLabel?: boolean | undefined; intakeFee?: number | undefined; privateSellersOnly?: boolean | undefined; fixedSellerData?: boolean | undefined; @@ -1500,6 +1510,7 @@ export interface Api { maxItemsPerSeller?: number | undefined; labelFormat?: 'small' | 'standard' | undefined; priceOnLabel?: boolean | undefined; + sellerNumberOnLabel?: boolean | undefined; intakeFee?: number | undefined; privateSellersOnly?: boolean | undefined; fixedSellerData?: boolean | undefined; @@ -1569,6 +1580,7 @@ export interface Api { maxItemsPerSeller?: number | undefined; labelFormat?: 'small' | 'standard' | undefined; priceOnLabel?: boolean | undefined; + sellerNumberOnLabel?: boolean | undefined; intakeFee?: number | undefined; privateSellersOnly?: boolean | undefined; fixedSellerData?: boolean | undefined; diff --git a/src/locales/de/company.json b/src/locales/de/company.json index f2a71453..1329b728 100644 --- a/src/locales/de/company.json +++ b/src/locales/de/company.json @@ -13,7 +13,7 @@ }, "qrLabels": { "title": "QR-Etiketten in zwei Größen", - "text": "Verkäufer drucken ihre Etiketten selbst: groß für Fahrräder, klein mit 40 pro Seite für Kleidung, immer mit Verkäufernummer. Ohne Preis darauf gehen Rabatte ohne Neudruck." + "text": "Verkäufer drucken ihre Etiketten selbst: groß für Fahrräder, klein mit 40 pro Seite für Kleidung, mit Verkäufernummer oder zum Wiederverwenden ohne. Ohne Preis darauf gehen Rabatte ohne Neudruck." }, "phoneCheckout": { "title": "Kasse mit Warenkorb", diff --git a/src/locales/de/organizer.json b/src/locales/de/organizer.json index 2ec052b0..110ad16d 100644 --- a/src/locales/de/organizer.json +++ b/src/locales/de/organizer.json @@ -138,7 +138,9 @@ "labels": "Etiketten", "labelsLarge": "Groß – 12 pro A4-Seite (z. B. Fahrräder)", "labelsSmall": "Klein – 40 pro A4-Seite (z. B. Kleidung)", - "labelsHint": "Auf jedem Etikett stehen QR-Code, Verkäufernummer, Titel und – wenn angegeben – die Größe.", + "labelsHint": "Auf jedem Etikett stehen QR-Code, Titel und – wenn angegeben – die Größe.", + "sellerNumberOnLabel": "Verkäufernummer aufs Etikett drucken", + "sellerNumberOnLabelText": "Hilft beim Zurücksortieren nach dem Basar. Ausgeschaltet können Verkäufer ihre Etiketten beim nächsten Basar wiederverwenden. Der QR-Code bleibt gültig.", "priceOnLabel": "Preis aufs Etikett drucken", "priceOnLabelText": "Hilft an der Kasse ohne Scanner. Der Preis auf dem Etikett ist fest – bei Rabatten wird er deshalb nicht gedruckt.", "priceOnLabelDiscounts": "Rabatte sind eingeschaltet, deshalb erscheint kein Preis auf den Etiketten.", @@ -259,6 +261,7 @@ "labelsSmall": "Kleine Etiketten (40 pro Seite)", "labelsLarge": "Große Etiketten (12 pro Seite)", "priceOnLabel": "Preis auf dem Etikett", + "sellerNumberOnLabel": "Verkäufernummer auf dem Etikett", "questionsDuringEvent": "erst während des Basars", "requiredFields": "Pflichtangaben: {{fields}}", "privateSellers": "Nur Privatverkäufer", @@ -812,6 +815,7 @@ "labelSmall": "Kleines Etikett · 40 pro A4-Seite", "labelPriceHidden": "Ohne Preis: Rabatte ändern ihn ja noch.", "labelNumber": "Nr. {{seller}}-{{item}}", + "labelReusable": "Ohne Verkäufernummer: Das Etikett passt auch beim nächsten Basar.", "photoRequired": "Foto Pflicht", "photoOptional": "Ohne Foto", "maxItems": "Bis zu {{count}} Artikel pro Verkäufer", diff --git a/src/locales/de/seller.json b/src/locales/de/seller.json index 7ad5b52d..91223956 100644 --- a/src/locales/de/seller.json +++ b/src/locales/de/seller.json @@ -198,6 +198,7 @@ "formatStandard": "Format Standard: {{perPage}} große Etiketten pro Seite", "formatSmall": "Format Klein: {{perPage}} kleine Etiketten pro Seite", "formatPerItem": "Format und Verkäufernummer nach dem jeweils nächsten Basar des Artikels, sonst Standard", + "reusable": "Ohne Verkäufernummer: Du kannst diese Etiketten beim nächsten Basar wiederverwenden.", "download": "PDF herunterladen", "created_one": "{{count}} Etikett erstellt", "created_other": "{{count}} Etiketten erstellt", diff --git a/src/locales/en/company.json b/src/locales/en/company.json index e078fcb5..72786b72 100644 --- a/src/locales/en/company.json +++ b/src/locales/en/company.json @@ -13,7 +13,7 @@ }, "qrLabels": { "title": "QR labels in two sizes", - "text": "Sellers print their own labels: large for bikes, small with 40 per page for clothes, always with the seller number. Without a price on them, discounts work without reprinting." + "text": "Sellers print their own labels: large for bikes, small with 40 per page for clothes, with the seller number or without it for reuse. Without a price on them, discounts work without reprinting." }, "phoneCheckout": { "title": "Checkout with a cart", diff --git a/src/locales/en/organizer.json b/src/locales/en/organizer.json index 8f11f2bf..0726310d 100644 --- a/src/locales/en/organizer.json +++ b/src/locales/en/organizer.json @@ -138,7 +138,9 @@ "labels": "Labels", "labelsLarge": "Large – 12 per A4 page (e.g. bikes)", "labelsSmall": "Small – 40 per A4 page (e.g. clothes)", - "labelsHint": "Every label shows QR code, seller number, title and – if given – the size.", + "labelsHint": "Every label shows QR code, title and – if given – the size.", + "sellerNumberOnLabel": "Print the seller number on the label", + "sellerNumberOnLabelText": "Helps sorting items back after the bazaar. Switched off, sellers can reuse their labels at the next bazaar. The QR code stays valid.", "priceOnLabel": "Print the price on the label", "priceOnLabelText": "Helps at a cash desk without scanner. The printed price is fixed – so it is not printed when discounts are on.", "priceOnLabelDiscounts": "Discounts are switched on, so no price appears on the labels.", @@ -259,6 +261,7 @@ "labelsSmall": "Small labels (40 per page)", "labelsLarge": "Large labels (12 per page)", "priceOnLabel": "Price on the label", + "sellerNumberOnLabel": "Seller number on the label", "questionsDuringEvent": "only during the bazaar", "requiredFields": "Required details: {{fields}}", "privateSellers": "Private sellers only", @@ -812,6 +815,7 @@ "labelSmall": "Small label · 40 per A4 page", "labelPriceHidden": "No price: discounts may still change it.", "labelNumber": "No. {{seller}}-{{item}}", + "labelReusable": "No seller number: the label also works at the next bazaar.", "photoRequired": "Photo required", "photoOptional": "No photo", "maxItems": "Up to {{count}} items per seller", diff --git a/src/locales/en/seller.json b/src/locales/en/seller.json index efe152c2..458d6969 100644 --- a/src/locales/en/seller.json +++ b/src/locales/en/seller.json @@ -198,6 +198,7 @@ "formatStandard": "Standard format: {{perPage}} large labels per page", "formatSmall": "Small format: {{perPage}} small labels per page", "formatPerItem": "Format and seller number from each item's next bazaar, otherwise standard", + "reusable": "No seller number: you can reuse these labels at the next bazaar.", "download": "Download PDF", "created_one": "{{count}} label created", "created_other": "{{count}} labels created", diff --git a/src/pages/organizer/events/EditEventForm.tsx b/src/pages/organizer/events/EditEventForm.tsx index 63125252..998a9197 100644 --- a/src/pages/organizer/events/EditEventForm.tsx +++ b/src/pages/organizer/events/EditEventForm.tsx @@ -163,6 +163,7 @@ const buildEventSchema = ( .or(z.nan()), labelFormat: z.enum(LABEL_FORMATS), priceOnLabel: z.boolean(), + sellerNumberOnLabel: z.boolean(), privateSellersOnly: z.boolean(), fixedSellerData: z.boolean(), intakeFee: z @@ -270,6 +271,7 @@ function featuresToForm(stored: StoredEventFeatures | undefined): FeatureFormDat maxItemsPerSeller: features.maxItemsPerSeller, labelFormat: features.labelFormat, priceOnLabel: features.priceOnLabel, + sellerNumberOnLabel: features.sellerNumberOnLabel, intakeFee: features.intakeFee, privateSellersOnly: features.privateSellersOnly, fixedSellerData: features.fixedSellerData, @@ -296,6 +298,7 @@ function featuresFromForm(features: FeatureFormData): StoredEventFeatures { : undefined, labelFormat: features.labelFormat, priceOnLabel: features.priceOnLabel, + sellerNumberOnLabel: features.sellerNumberOnLabel, intakeFee: typeof features.intakeFee === 'number' && !isNaN(features.intakeFee) && features.intakeFee > 0 ? features.intakeFee @@ -717,7 +720,13 @@ export function EditEventForm() { } return; } - reset({ ...methods.getValues(), ...draft.values }); + // Switches added after the draft was saved keep their default + const current = methods.getValues(); + reset({ + ...current, + ...draft.values, + features: { ...current.features, ...draft.values.features }, + }); setPendingLocationCategories(draft.pendingLocationCategories); setEventType(findEventType(draft.eventType)?.id); setStep(WIZARD_STEPS.length - 1); diff --git a/src/pages/organizer/events/components/EditEventFeatures.tsx b/src/pages/organizer/events/components/EditEventFeatures.tsx index 6e1e7375..daa59b24 100644 --- a/src/pages/organizer/events/components/EditEventFeatures.tsx +++ b/src/pages/organizer/events/components/EditEventFeatures.tsx @@ -18,6 +18,7 @@ type FeatureKey = | 'questions' | 'photosOptional' | 'priceOnLabel' + | 'sellerNumberOnLabel' | 'privateSellersOnly' | 'fixedSellerData'; @@ -338,6 +339,12 @@ export function EditEventFeatures({

{t('features.labelsHint')}

+ +
- {small &&

Nr. 17

} + {small && withNumber &&

Nr. 17

}

- {[!small && number, price !== undefined && `${formatPriceDE(price)} €`] + {[!small && withNumber && number, price !== undefined && `${formatPriceDE(price)} €`] .filter(Boolean) .join(' · ')}

@@ -396,6 +407,7 @@ export function ItemsPreview({ type }: { type?: EventType }) { const limit = given(features.maxItemsPerSeller); const small = features.labelFormat === 'small'; const showPrice = !!features.priceOnLabel && !features.discounts; + const withNumber = features.sellerNumberOnLabel !== false; return ( · {t('wizard.preview.labelPriceHidden')}} + {!withNumber && ( + }>{t('wizard.preview.labelReusable')} + )} }> {chosen.length > 0 ? t('wizard.preview.categories', { categories: chosen.join(', ') }) @@ -455,6 +470,7 @@ export function ItemsPreview({ type }: { type?: EventType }) { small={small} title={items[0].title} price={showPrice ? items[0].price : undefined} + withNumber={withNumber} />
diff --git a/src/pages/organizer/events/dashboard/components/EventSettingsSummary.tsx b/src/pages/organizer/events/dashboard/components/EventSettingsSummary.tsx index b4319ac0..c2b0c9ba 100644 --- a/src/pages/organizer/events/dashboard/components/EventSettingsSummary.tsx +++ b/src/pages/organizer/events/dashboard/components/EventSettingsSummary.tsx @@ -155,6 +155,7 @@ export function EventSettingsSummary({ event }: { event: EventWithLabels }) { features.labelFormat === 'small' ? t('summary.labelsSmall') : t('summary.labelsLarge') } /> + { ); }); + it('tells the seller when the labels of a bazaar can be reused', async () => { + const reusable = { + ...events[0], + features: { sellerNumberOnLabel: false }, + } as unknown as Doc<'events'>; + render( + {}} + events={[reusable]} + products={products} + eventId="later" + /> + ); + expect(await screen.findByText(/beim nächsten Basar wiederverwenden/)).toBeInTheDocument(); + }); + it('prints the unsold items of the chosen bazaar for that bazaar', async () => { renderDialog('later'); expect(await screen.findByText('1 Etikett auf 1 A4-Seite')).toBeInTheDocument(); diff --git a/src/pages/seller/products/components/LabelPrintDialog.tsx b/src/pages/seller/products/components/LabelPrintDialog.tsx index 2d4ad2b5..657149ec 100644 --- a/src/pages/seller/products/components/LabelPrintDialog.tsx +++ b/src/pages/seller/products/components/LabelPrintDialog.tsx @@ -128,6 +128,9 @@ export function LabelPrintDialog({ }) : t('labels.formatPerItem')}

+ {bazaar?.event.features?.sellerNumberOnLabel === false && ( +

{t('labels.reusable')}

+ )} diff --git a/src/shared/eventFeatures.ts b/src/shared/eventFeatures.ts index d4403fac..1a44c4b6 100644 --- a/src/shared/eventFeatures.ts +++ b/src/shared/eventFeatures.ts @@ -37,6 +37,11 @@ export interface EventFeatures { labelFormat: LabelFormat; /** Print the price on labels; only takes effect while discounts are off. */ priceOnLabel: boolean; + /** + * Print the seller number on labels. Off, a label holds nothing specific to this bazaar + * (the QR code only links to the item), so sellers can reuse it at their next one. + */ + sellerNumberOnLabel: boolean; /** Fixed fee in € per accepted item (sold or not), kept from the payout; unset means none. */ intakeFee?: number; /** Sellers confirm when joining that they sell as private persons, not as traders. */ @@ -65,6 +70,7 @@ export const DEFAULT_EVENT_FEATURES: EventFeatures = { photosOptional: false, labelFormat: 'standard', priceOnLabel: false, + sellerNumberOnLabel: true, privateSellersOnly: false, fixedSellerData: false, }; From 67db16a0eb437b962c8d8c2aa8bc909fc9f11f9b Mon Sep 17 00:00:00 2001 From: Ivo Zeitz Date: Mon, 2 Nov 2026 10:27:36 +0100 Subject: [PATCH 02/14] fix(events): address everywhere, drafts that stay out of the way, pages that load again - Reminders, calendar, exports and lists name the full address; address parts count as repeated only as whole words; a street alone reaches the JSON-LD - A draft returns to its step and can be discarded; ?type= beats an old draft; only a finished draft is created by itself; cancel and sign-out clear it - Missing draft after the sign-up says where it is; a removed cover stays removed - Failed page chunks load again without a manual reload; a reload only when the server answers; preloading retries; no onboarding prompt after the wizard - Wizard preview prints the label number as the real label does Co-Authored-By: Claude Opus 5.5 --- backend/src/modules/features.rs | 76 +++++++++++++++++++ backend/src/modules/reminders.rs | 7 +- backend/src/modules/seller_records.rs | 2 +- backend/src/modules/settlement.rs | 2 +- src/components/layout/PageErrorBoundary.tsx | 4 +- src/lib/api/react.tsx | 7 +- src/lib/eventDraft.ts | 4 + src/lib/lazyPage.test.ts | 26 +++++++ src/lib/lazyPage.ts | 74 ++++++++++++++---- src/locales/de/organizer.json | 4 +- src/locales/en/organizer.json | 4 +- src/pages/administrator/AdminEventsPage.tsx | 2 +- src/pages/organizer/events/EditEventForm.tsx | 76 ++++++++++++++----- .../events/EditEventForm.wizard.test.tsx | 51 +++++++++++++ .../events/components/EventPageSidebar.tsx | 4 +- .../components/wizard/WizardPreviews.tsx | 2 +- src/pages/public/auth/RegisterPage.tsx | 8 +- .../components/MyProductSelectEvents.tsx | 3 +- src/shared/eventJsonLd.test.ts | 32 ++++++++ src/shared/eventJsonLd.ts | 14 +++- src/shared/reminderContent.ts | 10 ++- 21 files changed, 355 insertions(+), 57 deletions(-) create mode 100644 src/lib/lazyPage.test.ts diff --git a/backend/src/modules/features.rs b/backend/src/modules/features.rs index 921dc6c9..f581bbf4 100644 --- a/backend/src/modules/features.rs +++ b/backend/src/modules/features.rs @@ -93,6 +93,51 @@ impl Event { pub fn resolved_features(&self) -> EventFeatures { resolve(self.features.as_ref()) } + + /// "Turnhalle Nord, Hauptstr. 5, 89073 Ulm" (formatEventPlace in the app). + pub fn place(&self) -> String { + format_place( + &self.location, + self.street.as_deref(), + self.postal_code.as_deref(), + self.city.as_deref(), + ) + } +} + +/// Whether `part` stands in `text` as whole words: "Ulm" is not in "Ulmer Halle". +fn contains_words(text: &str, part: &str) -> bool { + let text = text.to_lowercase(); + let part = part.to_lowercase(); + text.match_indices(&part).any(|(start, _)| { + let before = text[..start].chars().next_back(); + let after = text[start + part.len()..].chars().next(); + !before.is_some_and(char::is_alphanumeric) && !after.is_some_and(char::is_alphanumeric) + }) +} + +fn format_place( + location: &str, + street: Option<&str>, + postal_code: Option<&str>, + city: Option<&str>, +) -> String { + let location = location.trim(); + let town = [postal_code, city] + .into_iter() + .flatten() + .map(str::trim) + .filter(|part| !part.is_empty()) + .collect::>() + .join(" "); + let mut parts = vec![location.to_owned()]; + for part in [street.unwrap_or_default().trim(), town.as_str()] { + if !part.is_empty() && !contains_words(location, part) { + parts.push(part.to_owned()); + } + } + parts.retain(|part| !part.is_empty()); + parts.join(", ") } /// Whether questions on items of this event can be asked right now. @@ -170,6 +215,37 @@ mod tests { ); } + #[test] + fn the_place_names_venue_and_address_once() { + assert_eq!( + format_place( + "Turnhalle Nord", + Some("Hauptstr. 5"), + Some("89073"), + Some("Ulm") + ), + "Turnhalle Nord, Hauptstr. 5, 89073 Ulm" + ); + assert_eq!( + format_place( + "Halle, Hauptstr. 5, 89073 Ulm", + Some("hauptstr. 5"), + Some("89073"), + Some("Ulm") + ), + "Halle, Hauptstr. 5, 89073 Ulm" + ); + // Only whole words count as already there + assert_eq!( + format_place("Ulmer Stadthalle", None, None, Some("Ulm")), + "Ulmer Stadthalle, Ulm" + ); + assert_eq!( + format_place("Halle, Hauptstr. 50", Some("Hauptstr. 5"), None, None), + "Halle, Hauptstr. 50, Hauptstr. 5" + ); + } + #[test] fn discounted_prices() { assert_eq!( diff --git a/backend/src/modules/reminders.rs b/backend/src/modules/reminders.rs index 06dcd45b..3a8ab30c 100644 --- a/backend/src/modules/reminders.rs +++ b/backend/src/modules/reminders.rs @@ -247,7 +247,7 @@ pub fn day_before_info( }, Detail { label: t.t("reminder.location", &[]), - value: event.location.clone(), + value: event.place(), }, ]; if let Some(dropoff) = &dropoff { @@ -312,12 +312,13 @@ pub fn pickup_reminder( if !unsold.is_empty() { paragraphs.push(t.t("reminder.pickup.toPickUp", &[("items", &listed)])); } + let place = event.place(); paragraphs.push(match &pickup { Some(pickup) => t.t( "reminder.pickup.when", - &[("pickup", pickup), ("location", &event.location)], + &[("pickup", pickup), ("location", &place)], ), - None => t.t("reminder.pickup.where", &[("location", &event.location)]), + None => t.t("reminder.pickup.where", &[("location", &place)]), }); paragraphs.extend(note_paragraphs(event)); paragraphs.extend(contact_paragraph(event, t)); diff --git a/backend/src/modules/seller_records.rs b/backend/src/modules/seller_records.rs index c7e0d060..69783f0d 100644 --- a/backend/src/modules/seller_records.rs +++ b/backend/src/modules/seller_records.rs @@ -504,8 +504,8 @@ async fn get_proof_of_offers(ctx: &mut Ctx, args: EventArgs) -> AppResult }); Ok(Proof { event: ProofEvent { + location: event.place(), title: event.title, - location: event.location, start_date: event.start_date, end_date: event.end_date, }, diff --git a/backend/src/modules/settlement.rs b/backend/src/modules/settlement.rs index bd82c685..d29226d5 100644 --- a/backend/src/modules/settlement.rs +++ b/backend/src/modules/settlement.rs @@ -140,8 +140,8 @@ async fn get_export(ctx: &mut Ctx, args: EventArgs) -> AppResult { sellers.sort_by_key(|seller| seller.seller_number.unwrap_or(i32::MAX)); Ok(Export { event: ExportEvent { + location: event.place(), title: event.title, - location: event.location, start_date: event.start_date, end_date: event.end_date, commission: event.commission, diff --git a/src/components/layout/PageErrorBoundary.tsx b/src/components/layout/PageErrorBoundary.tsx index d764b643..3efc1844 100644 --- a/src/components/layout/PageErrorBoundary.tsx +++ b/src/components/layout/PageErrorBoundary.tsx @@ -5,6 +5,7 @@ import { AlertTriangle } from 'lucide-react'; import { ApiError } from '../../lib/api/client'; import { useApiClient } from '../../lib/api/react'; import { getUserFacingErrorMessage } from '../../lib/errors'; +import { PageLoadError, retryPageLoad } from '../../lib/lazyPage'; import { RetryButton } from '../ui/loading'; function PageError({ error, onRetry }: { error: unknown; onRetry: () => void }) { @@ -22,7 +23,8 @@ function PageError({ error, onRetry }: { error: unknown; onRetry: () => void }) { client.retryFailed(); - onRetry(); + if (error instanceof PageLoadError) void retryPageLoad().finally(onRetry); + else onRetry(); }} /> diff --git a/src/lib/api/react.tsx b/src/lib/api/react.tsx index 6ea9dc23..f2998a6b 100644 --- a/src/lib/api/react.tsx +++ b/src/lib/api/react.tsx @@ -1,3 +1,4 @@ +import { clearEventDraft } from '../eventDraft'; import { createContext, useCallback, @@ -132,7 +133,11 @@ export function useAuthActions() { () => ({ signIn: (provider: string, params?: Record) => client.signIn(provider, params), - signOut: () => client.signOut(), + signOut: () => { + // A draft in this browser must not wait for the next person signing in + clearEventDraft(); + return client.signOut(); + }, changePassword: (oldPassword: string, newPassword: string) => client.changePassword(oldPassword, newPassword), }), diff --git a/src/lib/eventDraft.ts b/src/lib/eventDraft.ts index dfc98056..f9ba429b 100644 --- a/src/lib/eventDraft.ts +++ b/src/lib/eventDraft.ts @@ -14,6 +14,10 @@ export interface EventDraft { values: Values; pendingLocationCategories: string[]; eventType?: string; + /** The wizard step to come back to; drafts without one go to the last step */ + step?: number; + /** The guest finished the wizard: only then the sign-up creates the bazaar by itself */ + submitted?: boolean; savedAt: number; } diff --git a/src/lib/lazyPage.test.ts b/src/lib/lazyPage.test.ts new file mode 100644 index 00000000..2f721689 --- /dev/null +++ b/src/lib/lazyPage.test.ts @@ -0,0 +1,26 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { isServerReachable } from './lazyPage'; + +describe('isServerReachable', () => { + afterEach(() => vi.restoreAllMocks()); + + it('asks the server even when the browser says online', async () => { + vi.spyOn(navigator, 'onLine', 'get').mockReturnValue(true); + const fetchMock = vi.spyOn(globalThis, 'fetch').mockRejectedValue(new TypeError('no internet')); + await expect(isServerReachable()).resolves.toBe(false); + expect(fetchMock).toHaveBeenCalledTimes(1); + }); + + it('is fine with any answer of the server', async () => { + vi.spyOn(navigator, 'onLine', 'get').mockReturnValue(true); + vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response(null, { status: 404 })); + await expect(isServerReachable()).resolves.toBe(true); + }); + + it('does not ask while the browser is offline', async () => { + vi.spyOn(navigator, 'onLine', 'get').mockReturnValue(false); + const fetchMock = vi.spyOn(globalThis, 'fetch'); + await expect(isServerReachable()).resolves.toBe(false); + expect(fetchMock).not.toHaveBeenCalled(); + }); +}); diff --git a/src/lib/lazyPage.ts b/src/lib/lazyPage.ts index ad89003a..7e95a99a 100644 --- a/src/lib/lazyPage.ts +++ b/src/lib/lazyPage.ts @@ -1,4 +1,4 @@ -import { lazy, type ComponentType } from 'react'; +import { createElement, lazy, type ComponentType } from 'react'; /** * Pages behind the sign-in load as their own chunks, so visitors of the public pages @@ -10,13 +10,36 @@ const loaders: (() => Promise)[] = []; const RELOADED_KEY = 'bazarpro.chunkReload'; const RELOAD_PAUSE_MS = 10_000; +const PRELOAD_RETRY_MS = 60_000; + +/** A page's code could not be loaded: the connection is gone or a new version is out. */ +export class PageLoadError extends Error { + constructor(cause: unknown) { + super('Page could not be loaded', { cause }); + this.name = 'PageLoadError'; + } +} + +/** + * navigator.onLine also says yes on a hall Wi-Fi without internet, where a reload would + * end on the browser's error page and lose the running app: ask the server first. + */ +export async function isServerReachable(): Promise { + if (typeof navigator !== 'undefined' && !navigator.onLine) return false; + try { + await fetch(window.location.origin, { method: 'HEAD', cache: 'no-store' }); + return true; + } catch { + return false; + } +} /** - * A chunk that fails to load while online is from an older deploy: its file is gone. - * Loading the page again fetches the current ones, once; offline the error stays. + * A chunk that fails to load while the server answers is from an older deploy: its file + * is gone. Loading the page again fetches the current ones, once. */ -function reloadForNewDeploy(error: unknown): never { - if (typeof navigator !== 'undefined' && navigator.onLine) { +async function reloadForNewDeploy(error: unknown): Promise { + if (await isServerReachable()) { try { const last = Number(sessionStorage.getItem(RELOADED_KEY) ?? 0); if (Date.now() - last > RELOAD_PAUSE_MS) { @@ -27,25 +50,44 @@ function reloadForNewDeploy(error: unknown): never { // No session storage: show the error instead of risking a reload loop } } - throw error; + throw new PageLoadError(error); +} + +/** "Try again" after a failed page: browsers may keep a failed import until a reload. */ +export async function retryPageLoad(): Promise { + if (await isServerReachable()) window.location.reload(); } /** A named page export as lazy component: `lazyPage(() => import('./X'), 'X')`. */ export function lazyPage(load: () => Promise, name: K) { loaders.push(load); - return lazy(() => - load().then( - (module) => ({ default: module[name] as ComponentType> }), - reloadForNewDeploy - ) - ); + // React.lazy keeps a failure for good: after one, the next render starts a new attempt + const create = () => + lazy(() => + load().then( + (module) => ({ default: module[name] as ComponentType> }), + (error: unknown) => { + current = create(); + return reloadForNewDeploy(error); + } + ) + ); + let current = create(); + return function LazyPage() { + return createElement(current); + }; } let preloaded = false; +let preloading = false; -/** Loads all lazy pages in the background, once. */ +/** Loads all lazy pages in the background, until all are there. */ export function preloadPages() { - if (preloaded) return; - preloaded = true; - for (const load of loaders) void load().catch(() => undefined); + if (preloaded || preloading) return; + preloading = true; + void Promise.allSettled(loaders.map((load) => load())).then((results) => { + preloading = false; + if (results.every((result) => result.status === 'fulfilled')) preloaded = true; + else setTimeout(preloadPages, PRELOAD_RETRY_MS); + }); } diff --git a/src/locales/de/organizer.json b/src/locales/de/organizer.json index 110ad16d..b1c0aab7 100644 --- a/src/locales/de/organizer.json +++ b/src/locales/de/organizer.json @@ -791,6 +791,8 @@ "fixErrors": "Bitte prüfe die markierten Angaben.", "guestCreate": "Konto anlegen und Basar erstellen", "draftRestored": "Dein Entwurf ist wieder da.", + "draftElsewhere": "Dein Entwurf liegt im Browser, in dem du den Basar eingerichtet hast. Öffne BazarPro dort, um ihn anzulegen, oder beginne hier neu.", + "draftDiscard": "Neu beginnen", "creatingDraft": "Dein Basar wird angelegt …", "preview": { "label": "Vorschau", @@ -814,7 +816,7 @@ "labelLarge": "Großes Etikett · 12 pro A4-Seite", "labelSmall": "Kleines Etikett · 40 pro A4-Seite", "labelPriceHidden": "Ohne Preis: Rabatte ändern ihn ja noch.", - "labelNumber": "Nr. {{seller}}-{{item}}", + "labelNumber": "Nr. {{seller}}", "labelReusable": "Ohne Verkäufernummer: Das Etikett passt auch beim nächsten Basar.", "photoRequired": "Foto Pflicht", "photoOptional": "Ohne Foto", diff --git a/src/locales/en/organizer.json b/src/locales/en/organizer.json index 0726310d..02724ddf 100644 --- a/src/locales/en/organizer.json +++ b/src/locales/en/organizer.json @@ -791,6 +791,8 @@ "fixErrors": "Please check the marked details.", "guestCreate": "Sign up and create bazaar", "draftRestored": "Your draft is back.", + "draftElsewhere": "Your draft is in the browser where you set up the bazaar. Open BazarPro there to create it, or start again here.", + "draftDiscard": "Start over", "creatingDraft": "Creating your bazaar …", "preview": { "label": "Preview", @@ -814,7 +816,7 @@ "labelLarge": "Large label · 12 per A4 page", "labelSmall": "Small label · 40 per A4 page", "labelPriceHidden": "No price: discounts may still change it.", - "labelNumber": "No. {{seller}}-{{item}}", + "labelNumber": "No. {{seller}}", "labelReusable": "No seller number: the label also works at the next bazaar.", "photoRequired": "Photo required", "photoOptional": "No photo", diff --git a/src/pages/administrator/AdminEventsPage.tsx b/src/pages/administrator/AdminEventsPage.tsx index d5f0a170..46cb32c4 100644 --- a/src/pages/administrator/AdminEventsPage.tsx +++ b/src/pages/administrator/AdminEventsPage.tsx @@ -206,7 +206,7 @@ function Events() {
{event.title}
-
{event.location}
+
{formatEventPlace(event)}
{event.moderation && (
{t('events.blockedReason', { reason: event.moderation.reason })} diff --git a/src/pages/organizer/events/EditEventForm.tsx b/src/pages/organizer/events/EditEventForm.tsx index 998a9197..842ddb4c 100644 --- a/src/pages/organizer/events/EditEventForm.tsx +++ b/src/pages/organizer/events/EditEventForm.tsx @@ -244,14 +244,19 @@ type FeatureFormData = EventFormData['features']; /** What a draft keeps: everything but own pictures, which cannot wait in the browser */ type DraftValues = Omit< EventFormData, - 'coverImageFile' | 'eventMapImageFile' | 'removeCoverImage' | 'removeEventMapImage' ->; + | 'coverImageFile' + | 'eventMapImageFile' + | 'removeCoverImage' + | 'removeEventMapImage' + | 'coverTemplate' +> & { coverTemplate: EventFormData['coverTemplate'] | null }; function draftValues(data: EventFormData): DraftValues { // eslint-disable-next-line @typescript-eslint/no-unused-vars -- left out on purpose const { coverImageFile, eventMapImageFile, removeCoverImage, removeEventMapImage, ...rest } = data; - return rest; + // null: JSON would drop undefined, and a removed cover would come back as the default + return { ...rest, coverTemplate: rest.coverTemplate ?? null }; } function featuresToForm(stored: StoredEventFeatures | undefined): FeatureFormData { @@ -676,48 +681,67 @@ export function EditEventForm() { if (index >= 0) setStep(index); toast.error(t('wizard.fixErrors')); }; - const keepDraft = () => + const keepDraft = (draftStep: number, submitted = false) => saveEventDraft({ values: draftValues(methods.getValues()), pendingLocationCategories, eventType, + step: draftStep, + submitted, }); const goToStep = async (next: number) => { if (next > step) { const fields = WIZARD_STEPS[step].fields; if (fields.length > 0 && !(await methods.trigger(fields as never))) return; } - if (isGuest) keepDraft(); + if (isGuest) keepDraft(next); setStep(next); }; // Own pictures need an account: back here after the login, the draft is still there const loginForPictures = () => { - keepDraft(); + keepDraft(step); navigate(`/login?redirect=${encodeURIComponent('/events/new')}`); }; // Last step without an account: keep the bazaar and create it right after the sign-up const onGuestSubmit = () => { - keepDraft(); + keepDraft(step, true); navigate(`/register?redirect=${encodeURIComponent(CREATE_DRAFT_PATH)}`); }; // A waiting draft comes back once the form is ready; after the sign-up it is created const draftHandled = useRef(false); const [creatingDraft, setCreatingDraft] = useState(false); + const [draftRestored, setDraftRestored] = useState(false); + const discardDraft = () => { + clearEventDraft(); + reset(); + setPendingLocationCategories([]); + setEventType(undefined); + setDraftRestored(false); + setStep(0); + }; useEffect(() => { if (isEditing || isAuthLoading || !categories || draftHandled.current) return; draftHandled.current = true; + const wantsDraft = searchParams.get('draft') === '1'; + if (wantsDraft) searchParams.delete('draft'); + // From the landing page: start with the kind of bazaar the visitor picked there, + // even over an older draft + const type = wantsDraft ? undefined : findEventType(searchParams.get('type') ?? undefined); + if (type) { + clearEventDraft(); + searchParams.delete('type'); + setSearchParams(searchParams, { replace: true }); + applyEventType(type.id); + return; + } + if (wantsDraft) setSearchParams(searchParams, { replace: true }); const draft = loadEventDraft(); if (!draft) { - // From the landing page: start with the kind of bazaar the visitor picked there - const type = findEventType(searchParams.get('type') ?? undefined); - if (type) { - searchParams.delete('type'); - setSearchParams(searchParams, { replace: true }); - applyEventType(type.id); - } + // The link of the confirmation mail may open in another browser than the wizard + if (wantsDraft) toast.warning(t('wizard.draftElsewhere'), { duration: 15_000 }); return; } // Switches added after the draft was saved keep their default @@ -725,17 +749,16 @@ export function EditEventForm() { reset({ ...current, ...draft.values, + coverTemplate: draft.values.coverTemplate ?? undefined, features: { ...current.features, ...draft.values.features }, }); setPendingLocationCategories(draft.pendingLocationCategories); setEventType(findEventType(draft.eventType)?.id); - setStep(WIZARD_STEPS.length - 1); - if (isAuthenticated && searchParams.get('draft') === '1') { - searchParams.delete('draft'); - setSearchParams(searchParams, { replace: true }); + setStep(Math.min(draft.step ?? WIZARD_STEPS.length - 1, WIZARD_STEPS.length - 1)); + if (isAuthenticated && wantsDraft && draft.submitted) { setCreatingDraft(true); } else { - toast.info(t('wizard.draftRestored')); + setDraftRestored(true); } // eslint-disable-next-line react-hooks/exhaustive-deps -- once, when auth and categories are known }, [isEditing, isAuthLoading, categories, isAuthenticated]); @@ -962,6 +985,16 @@ export function EditEventForm() { }} className="space-y-6" > + {draftRestored && ( + + + {t('wizard.draftRestored')} + + + + )} void goToStep(index)} />
navigate('/')} + onClick={() => { + clearEventDraft(); + navigate('/'); + }} disabled={isSubmitting} > {t('actions.cancel', { ns: 'common' })} diff --git a/src/pages/organizer/events/EditEventForm.wizard.test.tsx b/src/pages/organizer/events/EditEventForm.wizard.test.tsx index 9a8138d3..0c0260bb 100644 --- a/src/pages/organizer/events/EditEventForm.wizard.test.tsx +++ b/src/pages/organizer/events/EditEventForm.wizard.test.tsx @@ -301,6 +301,57 @@ describe('event creation wizard', () => { consoleError.mockRestore(); }, 20_000); + const storeDraft = (extra: Record) => + localStorage.setItem( + 'bazarpro.eventDraft', + JSON.stringify({ + values: { title: 'Alter Entwurf', coverTemplate: 'market' }, + pendingLocationCategories: [], + savedAt: Date.now(), + ...extra, + }) + ); + + it('comes back to the step of the draft and can start over', async () => { + auth.current = { isLoading: false, isAuthenticated: false }; + storeDraft({ step: 1 }); + renderWizard(); + expect(await screen.findByText('Wie wird verkauft?')).toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: 'Neu beginnen' })); + expect(localStorage.getItem('bazarpro.eventDraft')).toBeNull(); + expect(screen.queryByText('Wie wird verkauft?')).toBeNull(); + expect(screen.queryByRole('button', { name: 'Neu beginnen' })).toBeNull(); + }, 20_000); + + it('takes the kind picked on the landing page over an older draft', async () => { + auth.current = { isLoading: false, isAuthenticated: false }; + storeDraft({ step: 7 }); + renderWizard('/events/new?type=kidsBazaar'); + expect(await screen.findByText('Wie wird verkauft?')).toBeInTheDocument(); + expect(localStorage.getItem('bazarpro.eventDraft')).toBeNull(); + }, 20_000); + + it('does not create an unfinished draft by itself', async () => { + storeDraft({ step: 7 }); + renderWizard('/events/new?draft=1'); + expect(await screen.findByRole('button', { name: 'Neu beginnen' })).toBeInTheDocument(); + expect(createEvent).not.toHaveBeenCalled(); + }, 20_000); + + it('keeps a removed cover removed in the draft', async () => { + auth.current = { isLoading: false, isAuthenticated: false }; + storeDraft({ values: { title: 'Basar', coverTemplate: 'ski' } }); + renderWizard(); + const chosen = await screen.findByRole('button', { name: 'Vorlage „Skipiste“ wählen' }); + fireEvent.click(chosen); + expect(chosen).toHaveAttribute('aria-pressed', 'false'); + fireEvent.click(screen.getAllByRole('button', { name: 'Anmelden und hochladen' })[0]); + expect(await screen.findByText(/^Registrierung/)).toBeInTheDocument(); + expect( + JSON.parse(localStorage.getItem('bazarpro.eventDraft')!).values.coverTemplate + ).toBeNull(); + }, 20_000); + it('lets visitors pick a template, but own pictures need the login', async () => { auth.current = { isLoading: false, isAuthenticated: false }; localStorage.setItem( diff --git a/src/pages/organizer/events/components/EventPageSidebar.tsx b/src/pages/organizer/events/components/EventPageSidebar.tsx index e58d4a9f..0c1cd83b 100644 --- a/src/pages/organizer/events/components/EventPageSidebar.tsx +++ b/src/pages/organizer/events/components/EventPageSidebar.tsx @@ -49,7 +49,7 @@ export function EventPageSidebar({ event, conditions }: EventPageSidebarProps) { const googleCalendarUrl = createGoogleCalendarUrl({ title: event.title, description: event.description, - location: event.location, + location: formatEventPlace(event), startDate: event.startDate, endDate: event.endDate, url: eventUrl, @@ -155,7 +155,7 @@ export function EventPageSidebar({ event, conditions }: EventPageSidebarProps) { downloadIcsEvent({ title: event.title, description: event.description, - location: event.location, + location: formatEventPlace(event), startDate: event.startDate, endDate: event.endDate, url: eventUrl, diff --git a/src/pages/organizer/events/components/wizard/WizardPreviews.tsx b/src/pages/organizer/events/components/wizard/WizardPreviews.tsx index b1202ece..09ae56c2 100644 --- a/src/pages/organizer/events/components/wizard/WizardPreviews.tsx +++ b/src/pages/organizer/events/components/wizard/WizardPreviews.tsx @@ -351,7 +351,7 @@ function LabelPreview({ withNumber: boolean; }) { const { t } = useTranslation('organizer'); - const number = t('wizard.preview.labelNumber', { seller: 17, item: 42 }); + const number = t('wizard.preview.labelNumber', { seller: 17 }); return (
diff --git a/src/pages/public/auth/RegisterPage.tsx b/src/pages/public/auth/RegisterPage.tsx index e7d6e1ba..a1be9ec4 100644 --- a/src/pages/public/auth/RegisterPage.tsx +++ b/src/pages/public/auth/RegisterPage.tsx @@ -1,3 +1,4 @@ +import { CREATE_DRAFT_PATH } from '../../../lib/eventDraft'; import { PasswordInput } from '../../../components/auth/PasswordInput'; import { MIN_PASSWORD_LENGTH } from '../../../shared/constants'; import { BackButton } from '../../../components/navigation/BackButton'; @@ -72,9 +73,12 @@ export function RegisterPage() { : (returnTo ?? BROWSE_EVENTS_PATH); useEffect(() => { - if (!redirectAfterLogin || verificationEmail || joinEventId) return; + // Coming from the wizard the choice is made: the user is creating a bazaar + if (!redirectAfterLogin || verificationEmail || joinEventId || returnTo === CREATE_DRAFT_PATH) { + return; + } setFlowSelectionOnboardingPending(); - }, [redirectAfterLogin, verificationEmail, joinEventId]); + }, [redirectAfterLogin, verificationEmail, joinEventId, returnTo]); const { register, diff --git a/src/pages/seller/products/components/MyProductSelectEvents.tsx b/src/pages/seller/products/components/MyProductSelectEvents.tsx index 78eac2cf..cc618720 100644 --- a/src/pages/seller/products/components/MyProductSelectEvents.tsx +++ b/src/pages/seller/products/components/MyProductSelectEvents.tsx @@ -1,3 +1,4 @@ +import { formatEventPlace } from '../../../../shared/eventJsonLd'; import { useFormContext } from 'react-hook-form'; import { Label } from '../../../../components/ui/label'; import { Checkbox } from '../../../../components/ui/checkbox'; @@ -97,7 +98,7 @@ export function MyProductSelectEvents({ {event.title} {isPast && t('form.ended')}
- {formatDateRangeDE(event.startDate, event.endDate)} - {event.location} + {formatDateRangeDE(event.startDate, event.endDate)} - {formatEventPlace(event)}
diff --git a/src/shared/eventJsonLd.test.ts b/src/shared/eventJsonLd.test.ts index 09883ce0..c1578051 100644 --- a/src/shared/eventJsonLd.test.ts +++ b/src/shared/eventJsonLd.test.ts @@ -121,3 +121,35 @@ describe('formatEventPlace and eventTown', () => { expect(eventTown({ location: 'Halle Ulm', city: ' ' })).toBe('Halle Ulm'); }); }); + +describe('formatEventPlace with whole words', () => { + it('keeps a town that only looks like part of the venue', () => { + expect(formatEventPlace({ location: 'Ulmer Stadthalle', city: 'Ulm' })).toBe( + 'Ulmer Stadthalle, Ulm' + ); + expect(formatEventPlace({ location: 'Halle, Hauptstr. 50', street: 'Hauptstr. 5' })).toBe( + 'Halle, Hauptstr. 50, Hauptstr. 5' + ); + }); + + it('does not repeat what the venue already says', () => { + expect( + formatEventPlace({ + location: 'Halle, Hauptstr. 5, 89073 Ulm', + street: 'hauptstr. 5', + postalCode: '89073', + city: 'Ulm', + }) + ).toBe('Halle, Hauptstr. 5, 89073 Ulm'); + }); +}); + +describe('placeOf with a street only', () => { + it('keeps street and country', () => { + expect(placeOf({ location: 'Halle', street: 'Hauptstr. 5', country: 'AT' }).address).toEqual({ + '@type': 'PostalAddress', + streetAddress: 'Hauptstr. 5', + addressCountry: 'AT', + }); + }); +}); diff --git a/src/shared/eventJsonLd.ts b/src/shared/eventJsonLd.ts index 08f8544c..9b8e11f2 100644 --- a/src/shared/eventJsonLd.ts +++ b/src/shared/eventJsonLd.ts @@ -10,6 +10,12 @@ export interface EventPlace { country?: string | null; } +/** Whether `part` stands in `text` as whole words: "Ulm" is not in "Ulmer Stadthalle". */ +function containsWords(text: string, part: string): boolean { + const escaped = part.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + return new RegExp(`(^|[^\\p{L}\\p{N}])${escaped}($|[^\\p{L}\\p{N}])`, 'iu').test(text); +} + /** "Turnhalle Nord, Hauptstr. 5, 89073 Ulm"; parts already in the location are not repeated. */ export function formatEventPlace(event: EventPlace): string { const location = event.location.trim(); @@ -19,7 +25,7 @@ export function formatEventPlace(event: EventPlace): string { .join(' '); const parts = [location]; for (const part of [event.street?.trim(), town]) { - if (part && !location.toLowerCase().includes(part.toLowerCase())) parts.push(part); + if (part && !containsWords(location, part)) parts.push(part); } return parts.filter(Boolean).join(', '); } @@ -54,7 +60,11 @@ export function placeOf(event: EventPlace): Place { const street = event.street?.trim(); const postalCode = event.postalCode?.trim(); const city = event.city?.trim(); - if (!postalCode && !city) return placeFromLocation(event.location); + if (!postalCode && !city) { + // Only a street is no address yet, unless the location of an older event has the rest + const parsed = placeFromLocation(event.location); + if (!street || typeof parsed.address !== 'string') return parsed; + } return { '@type': 'Place', name: event.location.trim() || formatEventPlace(event), diff --git a/src/shared/reminderContent.ts b/src/shared/reminderContent.ts index 41244adf..685b5fb2 100644 --- a/src/shared/reminderContent.ts +++ b/src/shared/reminderContent.ts @@ -1,5 +1,6 @@ import type { NotificationCategory } from './constants'; import { formatBerlinRange } from './berlinTime'; +import { formatEventPlace } from './eventJsonLd'; import type { MailT } from './i18n'; /** An email of the backend (backend/src/modules/notifications.rs), here for the previews. */ @@ -23,6 +24,9 @@ export interface ReminderEvent { _id: string; title: string; location: string; + street?: string | null; + postalCode?: string | null; + city?: string | null; startDate: number; endDate: number; contactInfo: string; @@ -64,7 +68,7 @@ export function dayBeforeInfo( label: t('reminder.bazaar'), value: formatBerlinRange(event.startDate, event.endDate, t.locale), }, - { label: t('reminder.location'), value: event.location }, + { label: t('reminder.location'), value: formatEventPlace(event) }, ...(dropoff ? [{ label: t('reminder.dropoff'), value: dropoff }] : []), ...(seller.sellerNumber !== undefined ? [{ label: t('reminder.yourNumber'), value: String(seller.sellerNumber) }] @@ -109,8 +113,8 @@ export function pickupReminder( t('reminder.pickup.over', { event: event.title, count: seller.soldCount }), ...(unsold.length > 0 ? [t('reminder.pickup.toPickUp', { items: listed + more })] : []), pickup - ? t('reminder.pickup.when', { pickup, location: event.location }) - : t('reminder.pickup.where', { location: event.location }), + ? t('reminder.pickup.when', { pickup, location: formatEventPlace(event) }) + : t('reminder.pickup.where', { location: formatEventPlace(event) }), ...noteParagraphs(event), ...contactParagraph(event, t), ], From 711736771a8036d710ebeef63793604a0fffb0b6 Mon Sep 17 00:00:00 2001 From: Ivo Zeitz Date: Mon, 2 Nov 2026 10:43:27 +0100 Subject: [PATCH 03/14] feat(labels): universal labels for many small items, start place on the sheet A bazaar chooses what marks the seller on labels: the number, a universal mark or nothing. The universal mark stays with the seller (users.sort_code), so printed labels work at other bazaars: a large digit and three fields to sort by sight. Fields have color and symbol, so black and white prints work and color-blind helpers can tell them apart. Only on the small sheet. The team prints one sheet per basket, in sorting order. Sellers can start on a free place of a partly used sheet (#238). Co-Authored-By: Claude Opus 5.5 --- backend/migrations/0017_user_sort_code.sql | 4 + backend/src/modules/event_roles.rs | 13 +++ backend/src/modules/events.rs | 23 +++-- backend/src/modules/features.rs | 20 +++-- backend/src/modules/labels.rs | 27 ++++-- backend/src/modules/products.rs | 2 +- backend/tests/api/reminders.rs | 55 +++++++----- src/components/sellers/SortMarkBadge.tsx | 49 +++++++++++ src/lib/api/types.ts | 27 +++--- src/lib/productQRCodePdf.test.ts | 20 +++++ src/lib/productQRCodePdf.ts | 31 +++++-- src/lib/sortMarkPdf.ts | 77 +++++++++++++++++ src/lib/sortSheetsPdf.ts | 45 ++++++++++ src/locales/de/company.json | 2 +- src/locales/de/organizer.json | 16 +++- src/locales/de/seller.json | 3 + src/locales/en/company.json | 2 +- src/locales/en/organizer.json | 16 +++- src/locales/en/seller.json | 3 + src/pages/organizer/events/EditEventForm.tsx | 8 +- .../events/components/EditEventFeatures.tsx | 36 ++++++-- .../components/wizard/WizardPreviews.tsx | 30 +++++-- .../events/dashboard/SellerManagementPage.tsx | 27 ++++++ .../components/EventSettingsSummary.tsx | 10 ++- .../components/LabelPrintDialog.test.tsx | 26 +++++- .../products/components/LabelPrintDialog.tsx | 37 ++++++++- src/shared/constants.ts | 4 + src/shared/eventFeatures.ts | 19 +++-- src/shared/sortCode.test.ts | 37 +++++++++ src/shared/sortCode.ts | 83 +++++++++++++++++++ 30 files changed, 652 insertions(+), 100 deletions(-) create mode 100644 backend/migrations/0017_user_sort_code.sql create mode 100644 src/components/sellers/SortMarkBadge.tsx create mode 100644 src/lib/sortMarkPdf.ts create mode 100644 src/lib/sortSheetsPdf.ts create mode 100644 src/shared/sortCode.test.ts create mode 100644 src/shared/sortCode.ts diff --git a/backend/migrations/0017_user_sort_code.sql b/backend/migrations/0017_user_sort_code.sql new file mode 100644 index 00000000..d1b07f00 --- /dev/null +++ b/backend/migrations/0017_user_sort_code.sql @@ -0,0 +1,4 @@ +-- A number that stays with a seller across all bazaars. Universal labels print it as a +-- digit, symbols and colors (src/shared/sortCode.ts), so they can be reused. Numbers are +-- not given out again, also after an account is deleted. +ALTER TABLE users ADD COLUMN sort_code integer GENERATED BY DEFAULT AS IDENTITY UNIQUE; diff --git a/backend/src/modules/event_roles.rs b/backend/src/modules/event_roles.rs index c792d0f7..3cf9dd81 100644 --- a/backend/src/modules/event_roles.rs +++ b/backend/src/modules/event_roles.rs @@ -10,6 +10,7 @@ use uuid::Uuid; use super::access::is_platform_admin; use super::docs::{self, User}; +use super::features::label_mark; use super::sales::{self, IntakeFee}; use super::seller_records::{keeps_seller_record, with_snapshot}; use crate::error::{AppError, AppResult}; @@ -234,6 +235,8 @@ pub struct VendorWithCalculations { pub is_helper: bool, /// Seller number of this event; missing for sellers from before numbers existed pub seller_number: Option, + /// The seller's lasting code, on bazaars with universal labels + pub sort_code: Option, /// Bazaars with fixedSellerData: name and address are recorded (first item accepted). /// Before, the team checks them against the ID card and the seller may still correct them. pub details_recorded: Option, @@ -281,6 +284,7 @@ pub async fn load_vendors_with_calculations( let users = docs::users(ctx.conn(), &vendor_ids).await?; let over = event.end_date < Utc::now(); let keeps_record = keeps_seller_record(&event); + let universal = label_mark(&event) == "universal"; for vendor in vendor_ids { let Some(mut user) = users.iter().find(|user| user.id == vendor).cloned() else { continue; @@ -305,6 +309,14 @@ pub async fn load_vendors_with_calculations( seller.as_ref(), accepted.get(&vendor).copied().unwrap_or(0), ); + let sort_code = if universal { + sqlx::query_scalar("SELECT sort_code FROM users WHERE id = $1") + .bind(vendor) + .fetch_optional(ctx.conn()) + .await? + } else { + None + }; vendors.push(VendorWithCalculations { user, total_revenue, @@ -321,6 +333,7 @@ pub async fn load_vendors_with_calculations( .is_some_and(|seller| seller.seller_snapshot.is_some()) }), seller_number: seller.and_then(|seller| seller.number), + sort_code, }); } Ok(vendors) diff --git a/backend/src/modules/events.rs b/backend/src/modules/events.rs index b0d92de7..de374aee 100644 --- a/backend/src/modules/events.rs +++ b/backend/src/modules/events.rs @@ -48,6 +48,7 @@ const SERVICES: [&str; 5] = [ ]; const VISIBILITIES: [&str; 3] = ["public", "logged-in", "approved"]; const LABEL_FORMATS: [&str; 2] = ["standard", "small"]; +const LABEL_MARKS: [&str; 3] = ["number", "universal", "none"]; /// What viewers outside the team see instead of the access code const HIDDEN_ACCESS_CODE: &str = "••••"; @@ -578,7 +579,7 @@ struct FeaturesArgs { max_items_per_seller: Option, label_format: Option, price_on_label: Option, - seller_number_on_label: Option, + label_mark: Option, intake_fee: Option, private_sellers_only: Option, fixed_seller_data: Option, @@ -624,6 +625,11 @@ fn sanitize_features(features: FeaturesArgs, previous: Option<&Value>) -> AppRes { return Err(invalid("labelFormat")); } + if let Some(mark) = &features.label_mark + && !LABEL_MARKS.contains(&mark.as_str()) + { + return Err(invalid("labelMark")); + } let previous_bool = |key: &str| previous.and_then(|p| p.get(key)).and_then(Value::as_bool); let required_fields: Option> = match features.required_fields { Some(fields) => fields, @@ -703,12 +709,15 @@ fn sanitize_features(features: FeaturesArgs, previous: Option<&Value>) -> AppRes json!(features.price_on_label.unwrap_or(false)), ); put( - "sellerNumberOnLabel", + "labelMark", json!( features - .seller_number_on_label - .or(previous_bool("sellerNumberOnLabel")) - .unwrap_or(true) + .label_mark + .or_else(|| previous + .and_then(|p| p.get("labelMark")) + .and_then(Value::as_str) + .map(str::to_owned)) + .unwrap_or_else(|| "number".to_owned()) ), ); put( @@ -1493,7 +1502,7 @@ mod tests { intake_fee: Some(0.555), ..FeaturesArgs::default() }, - Some(&json!({ "fixedSellerData": true, "sellerNumberOnLabel": false })), + Some(&json!({ "fixedSellerData": true, "labelMark": "universal" })), ) .unwrap(); assert_eq!(stored["discounts"], false); @@ -1502,7 +1511,7 @@ mod tests { assert_eq!(stored["intakeFee"], 0.56); // Not sent by an older client: kept assert_eq!(stored["fixedSellerData"], true); - assert_eq!(stored["sellerNumberOnLabel"], false); + assert_eq!(stored["labelMark"], "universal"); assert_eq!(stored["labelFormat"], "standard"); } diff --git a/backend/src/modules/features.rs b/backend/src/modules/features.rs index f581bbf4..fad0cedb 100644 --- a/backend/src/modules/features.rs +++ b/backend/src/modules/features.rs @@ -28,7 +28,7 @@ struct Stored { max_items_per_seller: Option, label_format: Option, price_on_label: Option, - seller_number_on_label: Option, + label_mark: Option, intake_fee: Option, private_sellers_only: Option, fixed_seller_data: Option, @@ -48,8 +48,8 @@ pub struct EventFeatures { pub max_items_per_seller: Option, pub label_format: String, pub price_on_label: bool, - /// Off: labels carry no seller number, so they stay valid for the seller's next bazaar - pub seller_number_on_label: bool, + /// What tells the sellers' items apart on labels: see `label_mark` + pub label_mark: String, /// Fixed fee in € per accepted item, kept from the payout pub intake_fee: Option, pub private_sellers_only: bool, @@ -79,7 +79,7 @@ pub fn resolve(features: Option<&Value>) -> EventFeatures { max_items_per_seller: stored.max_items_per_seller.map(|n| n.max(0.0) as u32), label_format: stored.label_format.unwrap_or_else(|| "standard".to_owned()), price_on_label: stored.price_on_label.unwrap_or(false), - seller_number_on_label: stored.seller_number_on_label.unwrap_or(true), + label_mark: stored.label_mark.unwrap_or_else(|| "number".to_owned()), intake_fee: stored .intake_fee .and_then(Decimal::from_f64_retain) @@ -178,6 +178,16 @@ pub fn are_offers_open(status: &str, event: &Event, now: DateTime) -> bool status == "available" && event.start_date <= now && now <= event.end_date } +/// The seller's mark on the labels of this bazaar: `number` of this bazaar, `universal` +/// (the seller's lasting sorting code, for the many items on small labels) or `none`. +pub fn label_mark(event: &Event) -> String { + let features = event.resolved_features(); + if features.label_mark == "universal" && features.label_format != "small" { + return "number".to_owned(); + } + features.label_mark +} + /// Labels show the price only without discounts: a discount would make it wrong. pub fn shows_price_on_label(event: &Event) -> bool { let features = event.resolved_features(); @@ -196,7 +206,7 @@ mod tests { assert_eq!(features.max_discount_percent, 50); assert!(!features.price_offers && !features.questions && !features.fixed_seller_data); assert_eq!(features.label_format, "standard"); - assert!(features.seller_number_on_label); + assert_eq!(features.label_mark, "number"); } #[test] diff --git a/backend/src/modules/labels.rs b/backend/src/modules/labels.rs index c0a1b04e..c5e035be 100644 --- a/backend/src/modules/labels.rs +++ b/backend/src/modules/labels.rs @@ -9,7 +9,7 @@ use uuid::Uuid; use super::docs::{self, Event}; use super::event_products::{find_active_listing, relation}; use super::event_roles::{TEAM, has_any_role_or_admin}; -use super::features::shows_price_on_label; +use super::features::{label_mark, shows_price_on_label}; use crate::error::{AppError, AppResult}; use crate::realtime::Topic; use crate::register; @@ -37,6 +37,8 @@ struct Label { product_id: Uuid, title: String, seller_number: Option, + /// The seller's lasting code instead of the number (universal labels) + sort_code: Option, size: Option, price: Option, } @@ -96,15 +98,25 @@ async fn get_label_data(ctx: &mut Ctx, args: LabelArgs) -> AppResult { .map(|(event, _)| event), }; let mut seller_number = None; + let mut sort_code = None; let mut price = None; if let Some(label_event) = &label_event { - let features = label_event.resolved_features(); - if features.seller_number_on_label { - seller_number = docs::event_seller(ctx.conn(), label_event.id, product.vendor_id) - .await? - .and_then(|row| row.number); + match label_mark(label_event).as_str() { + "number" => { + seller_number = + docs::event_seller(ctx.conn(), label_event.id, product.vendor_id) + .await? + .and_then(|row| row.number); + } + "universal" => { + sort_code = sqlx::query_scalar("SELECT sort_code FROM users WHERE id = $1") + .bind(product.vendor_id) + .fetch_optional(ctx.conn()) + .await?; + } + _ => {} } - let format = features.label_format; + let format = label_event.resolved_features().label_format; if !formats.contains(&format) { formats.push(format); } @@ -122,6 +134,7 @@ async fn get_label_data(ctx: &mut Ctx, args: LabelArgs) -> AppResult { .map(str::to_owned), title: product.title, seller_number, + sort_code, price, }); } diff --git a/backend/src/modules/products.rs b/backend/src/modules/products.rs index 6835b5cd..1d44ff7b 100644 --- a/backend/src/modules/products.rs +++ b/backend/src/modules/products.rs @@ -653,7 +653,7 @@ fn features_json(event: &Event) -> Value { "photosOptional": f.photos_optional, "labelFormat": f.label_format, "priceOnLabel": f.price_on_label, - "sellerNumberOnLabel": f.seller_number_on_label, + "labelMark": f.label_mark, "privateSellersOnly": f.private_sellers_only, "fixedSellerData": f.fixed_seller_data, }); diff --git a/backend/tests/api/reminders.rs b/backend/tests/api/reminders.rs index 6a28aeb8..aced5bba 100644 --- a/backend/tests/api/reminders.rs +++ b/backend/tests/api/reminders.rs @@ -383,35 +383,50 @@ async fn label_data_for_sellers_and_the_team(db: PgPool) { } #[sqlx::test(migrator = "bazarpro_backend::MIGRATOR")] -async fn labels_without_the_seller_number_when_the_bazaar_turns_it_off(db: PgPool) { +async fn the_bazaar_decides_what_marks_the_seller_on_labels(db: PgPool) { let app = TestApp::new(db.clone()); let organizer = fixtures::user(&db, "Orga").await; let seller = fixtures::user(&db, "Seller").await; - let event = fixtures::event( - &db, - EventSpec { - features: json!({ "sellerNumberOnLabel": false }), - ..EventSpec::new("Basar", organizer) - }, - ) - .await; - fixtures::role(&db, event, seller, "seller").await; - fixtures::event_seller(&db, event, seller, 12, false).await; - let jacket = fixtures::product(&db, seller, "Jacke", 15.0).await; - fixtures::event_product(&db, event, jacket, "announced").await; - let as_seller = fixtures::session(&db, seller).await; - let data = app - .query( + let code: i32 = sqlx::query_scalar("SELECT sort_code FROM users WHERE id = $1") + .bind(seller) + .fetch_one(&db) + .await + .unwrap(); + let jacket = fixtures::product(&db, seller, "Jacke", 15.0).await; + let label_for = async |features: serde_json::Value| { + let event = fixtures::event( + &db, + EventSpec { + features, + ..EventSpec::new("Basar", organizer) + }, + ) + .await; + fixtures::role(&db, event, seller, "seller").await; + fixtures::event_seller(&db, event, seller, 12, false).await; + fixtures::event_product(&db, event, jacket, "announced").await; + app.query( "labels.getLabelData", json!({ "productIds": [jacket], "eventId": event }), Some(&as_seller), ) .await - .body["value"] - .clone(); - assert_eq!(data["labels"][0]["title"], "Jacke"); - assert!(data["labels"][0].get("sellerNumber").is_none()); + .body["value"]["labels"][0] + .clone() + }; + + let none = label_for(json!({ "labelMark": "none" })).await; + assert!(none.get("sellerNumber").is_none() && none.get("sortCode").is_none()); + + let universal = label_for(json!({ "labelMark": "universal", "labelFormat": "small" })).await; + assert_eq!(universal["sortCode"], code); + assert!(universal.get("sellerNumber").is_none()); + + // Large labels have the number: sorting by sight is for many small items + let large = label_for(json!({ "labelMark": "universal", "labelFormat": "standard" })).await; + assert_eq!(large["sellerNumber"], 12); + assert!(large.get("sortCode").is_none()); } async fn end_days_ago(db: &PgPool, event: Uuid, days: i32) { diff --git a/src/components/sellers/SortMarkBadge.tsx b/src/components/sellers/SortMarkBadge.tsx new file mode 100644 index 00000000..4b0621ae --- /dev/null +++ b/src/components/sellers/SortMarkBadge.tsx @@ -0,0 +1,49 @@ +import { sortMark, type SortSymbol } from '../../shared/sortCode'; +import { cn } from '../../lib/utils'; + +const rgb = (color: readonly [number, number, number]) => `rgb(${color.join(' ')})`; + +function Symbol({ symbol }: { symbol: SortSymbol }) { + const ink = rgb(symbol.ink); + return ( + + ); +} + +function Field({ symbol, className }: { symbol: SortSymbol; className?: string }) { + return ( + + + + ); +} + +/** The sorting code as it is printed: large digit, one wide field over two small ones. */ +export function SortMarkBadge({ code, className }: { code: number; className?: string }) { + const { digit, fields, letter } = sortMark(code); + return ( + + + {digit} + {letter && {letter}} + + + + + + + + ); +} diff --git a/src/lib/api/types.ts b/src/lib/api/types.ts index 9dc8a8a8..518d68db 100644 --- a/src/lib/api/types.ts +++ b/src/lib/api/types.ts @@ -104,7 +104,7 @@ export interface Docs { maxItemsPerSeller?: number | undefined; labelFormat?: 'small' | 'standard' | undefined; priceOnLabel?: boolean | undefined; - sellerNumberOnLabel?: boolean | undefined; + labelMark?: 'number' | 'universal' | 'none' | undefined; intakeFee?: number | undefined; privateSellersOnly?: boolean | undefined; fixedSellerData?: boolean | undefined; @@ -369,7 +369,7 @@ export type EventFeatures = { maxItemsPerSeller?: number | undefined; labelFormat: 'small' | 'standard'; priceOnLabel: boolean; - sellerNumberOnLabel: boolean; + labelMark: 'number' | 'universal' | 'none'; intakeFee?: number | undefined; privateSellersOnly: boolean; fixedSellerData: boolean; @@ -544,6 +544,8 @@ export type VendorWithCalculations = { totalDiscount: number; isHelper: boolean; sellerNumber?: number | undefined; + /** The seller's lasting code, on bazaars with universal labels */ + sortCode?: number | undefined; /** Bazaars with fixedSellerData: name and address are recorded (first item accepted) */ detailsRecorded?: boolean | undefined; }; @@ -979,7 +981,7 @@ export interface Api { maxItemsPerSeller?: number | undefined; labelFormat?: 'small' | 'standard' | undefined; priceOnLabel?: boolean | undefined; - sellerNumberOnLabel?: boolean | undefined; + labelMark?: 'number' | 'universal' | 'none' | undefined; intakeFee?: number | undefined; privateSellersOnly?: boolean | undefined; fixedSellerData?: boolean | undefined; @@ -1047,7 +1049,7 @@ export interface Api { maxItemsPerSeller?: number | undefined; labelFormat?: 'small' | 'standard' | undefined; priceOnLabel?: boolean | undefined; - sellerNumberOnLabel?: boolean | undefined; + labelMark?: 'number' | 'universal' | 'none' | undefined; intakeFee?: number | undefined; privateSellersOnly?: boolean | undefined; fixedSellerData?: boolean | undefined; @@ -1117,7 +1119,7 @@ export interface Api { maxItemsPerSeller?: number | undefined; labelFormat?: 'small' | 'standard' | undefined; priceOnLabel?: boolean | undefined; - sellerNumberOnLabel?: boolean | undefined; + labelMark?: 'number' | 'universal' | 'none' | undefined; intakeFee?: number | undefined; privateSellersOnly?: boolean | undefined; fixedSellerData?: boolean | undefined; @@ -1187,7 +1189,7 @@ export interface Api { maxItemsPerSeller?: number | undefined; labelFormat?: 'small' | 'standard' | undefined; priceOnLabel?: boolean | undefined; - sellerNumberOnLabel?: boolean | undefined; + labelMark?: 'number' | 'universal' | 'none' | undefined; intakeFee?: number | undefined; privateSellersOnly?: boolean | undefined; fixedSellerData?: boolean | undefined; @@ -1265,7 +1267,7 @@ export interface Api { maxItemsPerSeller?: number | undefined; labelFormat?: 'small' | 'standard' | undefined; priceOnLabel?: boolean | undefined; - sellerNumberOnLabel?: boolean | undefined; + labelMark?: 'number' | 'universal' | 'none' | undefined; intakeFee?: number | undefined; privateSellersOnly?: boolean | undefined; fixedSellerData?: boolean | undefined; @@ -1336,7 +1338,7 @@ export interface Api { maxItemsPerSeller?: number | undefined; labelFormat?: 'small' | 'standard' | undefined; priceOnLabel?: boolean | undefined; - sellerNumberOnLabel?: boolean | undefined; + labelMark?: 'number' | 'universal' | 'none' | undefined; intakeFee?: number | undefined; privateSellersOnly?: boolean | undefined; fixedSellerData?: boolean | undefined; @@ -1404,7 +1406,7 @@ export interface Api { maxItemsPerSeller?: number | undefined; labelFormat?: 'small' | 'standard' | undefined; priceOnLabel?: boolean | undefined; - sellerNumberOnLabel?: boolean | undefined; + labelMark?: 'number' | 'universal' | 'none' | undefined; intakeFee?: number | undefined; privateSellersOnly?: boolean | undefined; fixedSellerData?: boolean | undefined; @@ -1458,7 +1460,7 @@ export interface Api { maxItemsPerSeller?: number | undefined; labelFormat?: 'small' | 'standard' | undefined; priceOnLabel?: boolean | undefined; - sellerNumberOnLabel?: boolean | undefined; + labelMark?: 'number' | 'universal' | 'none' | undefined; intakeFee?: number | undefined; privateSellersOnly?: boolean | undefined; fixedSellerData?: boolean | undefined; @@ -1510,7 +1512,7 @@ export interface Api { maxItemsPerSeller?: number | undefined; labelFormat?: 'small' | 'standard' | undefined; priceOnLabel?: boolean | undefined; - sellerNumberOnLabel?: boolean | undefined; + labelMark?: 'number' | 'universal' | 'none' | undefined; intakeFee?: number | undefined; privateSellersOnly?: boolean | undefined; fixedSellerData?: boolean | undefined; @@ -1580,7 +1582,7 @@ export interface Api { maxItemsPerSeller?: number | undefined; labelFormat?: 'small' | 'standard' | undefined; priceOnLabel?: boolean | undefined; - sellerNumberOnLabel?: boolean | undefined; + labelMark?: 'number' | 'universal' | 'none' | undefined; intakeFee?: number | undefined; privateSellersOnly?: boolean | undefined; fixedSellerData?: boolean | undefined; @@ -1693,6 +1695,7 @@ export interface Api { productId: Id<'products'>; title: string; sellerNumber: number | undefined; + sortCode: number | undefined; size: string | undefined; price: number | undefined; }[]; diff --git a/src/lib/productQRCodePdf.test.ts b/src/lib/productQRCodePdf.test.ts index b50ef748..b1c03a69 100644 --- a/src/lib/productQRCodePdf.test.ts +++ b/src/lib/productQRCodePdf.test.ts @@ -60,4 +60,24 @@ describe('labels', () => { expect(save).toHaveBeenCalledWith('BazarPro-Etiketten.pdf'); expect(await downloadLabelsPdf(client, [])).toBe(0); }); + + const label = (n: number) => ({ productId: id(n), title: `Teil ${n}`, sortCode: 175 }); + const pages = (doc: ReturnType) => doc.getNumberOfPages(); + + it('starts on a free place and goes on with a new sheet', () => { + const labels = Array.from({ length: 3 }, (_, i) => label(i)); + expect(pages(buildLabelsPdf(labels, 'small', 38))).toBe(1); + expect(pages(buildLabelsPdf(labels, 'small', 39))).toBe(2); + expect(pages(buildLabelsPdf(labels, 'small', 40))).toBe(2); + expect(pages(buildLabelsPdf(labels, 'small', 999))).toBe(2); + expect(pages(buildLabelsPdf(labels, 'small', -3))).toBe(1); + }); + + it('draws the sorting mark in both formats', () => { + for (const format of ['small', 'standard'] as const) { + const pdf = buildLabelsPdf([label(1)], format).output(); + // The digit of the code 175 + expect(pdf).toContain('(5) Tj'); + } + }); }); diff --git a/src/lib/productQRCodePdf.ts b/src/lib/productQRCodePdf.ts index dc1d0808..25ca7529 100644 --- a/src/lib/productQRCodePdf.ts +++ b/src/lib/productQRCodePdf.ts @@ -4,6 +4,7 @@ import { api } from './api/functions'; import type { Id } from './api/types'; import type { LabelFormat } from '../shared/constants'; import { drawLabelQr, labelUrl } from './labelQr'; +import { drawSortMark } from './sortMarkPdf'; import { formatPriceDE } from './utils'; import { savePdf } from './saveFile'; @@ -23,6 +24,8 @@ export interface LabelData { title: string; /** Seller number at the bazaar, for sorting the items back after the sale */ sellerNumber?: number; + /** Universal labels: the seller's lasting code instead of the number */ + sortCode?: number; size?: string; /** Only when the bazaar prints prices (and has no discounts) */ price?: number; @@ -102,6 +105,11 @@ function drawStandard(doc: jsPDF, label: LabelData, cell: Cell): void { doc.setFontSize(11); doc.text(info, centerX, qrY + qrSize + 4.5 + titleLines.length * 4, { align: 'center' }); } + // Only with items of bazaars with different sheets; the code stays the seller's + if (label.sortCode !== undefined) { + const y = qrY + qrSize + 6 + titleLines.length * 4; + drawSortMark(doc, label.sortCode, centerX - 11, y, 22, 7); + } } /** QR code on the left, large seller number, title and size/price on the right. */ @@ -113,7 +121,10 @@ function drawSmall(doc: jsPDF, label: LabelData, cell: Cell): void { const textX = cell.x + padding + qrSize + 1.5; const textWidth = cell.x + cell.width - padding - textX; let lineY = cell.y + padding + 4; - if (label.sellerNumber !== undefined) { + if (label.sortCode !== undefined) { + drawSortMark(doc, label.sortCode, textX, cell.y + padding, textWidth, 11); + lineY = cell.y + padding + 14; + } else if (label.sellerNumber !== undefined) { doc.setFont('helvetica', 'bold'); doc.setFontSize(13); doc.text(`Nr. ${label.sellerNumber}`, textX, lineY); @@ -140,8 +151,11 @@ function drawSmall(doc: jsPDF, label: LabelData, cell: Cell): void { doc.rect(cell.x, cell.y, cell.width, cell.height); } -/** A4 pages with one label per item in the given format. */ -export function buildLabelsPdf(labels: LabelData[], format: LabelFormat): jsPDF { +/** + * A4 pages with one label per item in the given format. `startAt`: the first free place on + * a sheet that is partly used, counted from 1 row by row. + */ +export function buildLabelsPdf(labels: LabelData[], format: LabelFormat, startAt = 1): jsPDF { const { cols, rows } = LABEL_LAYOUTS[format]; const width = (PAGE_WIDTH - 2 * MARGIN_MM) / cols; const height = (PAGE_HEIGHT - 2 * MARGIN_MM) / rows; @@ -149,9 +163,11 @@ export function buildLabelsPdf(labels: LabelData[], format: LabelFormat): jsPDF const doc = new jsPDF({ orientation: 'portrait', unit: 'mm', format: 'a4' }); doc.setTextColor(0, 0, 0); + const skipped = Math.min(Math.max(Math.trunc(startAt) || 1, 1), perPage) - 1; for (const [i, label] of labels.entries()) { - if (i > 0 && i % perPage === 0) doc.addPage(); - const index = i % perPage; + const place = i + skipped; + if (i > 0 && place % perPage === 0) doc.addPage(); + const index = place % perPage; const cell = { x: MARGIN_MM + (index % cols) * width, y: MARGIN_MM + Math.floor(index / cols) * height, @@ -171,12 +187,13 @@ export function buildLabelsPdf(labels: LabelData[], format: LabelFormat): jsPDF export async function downloadLabelsPdf( client: ApiClient, productIds: Id<'products'>[], - eventId?: Id<'events'> + eventId?: Id<'events'>, + startAt = 1 ): Promise { if (productIds.length === 0) return 0; const data = await client.query(api.labels.getLabelData, { productIds, eventId }); if (data.labels.length === 0) return 0; - const doc = buildLabelsPdf(data.labels, data.format); + const doc = buildLabelsPdf(data.labels, data.format, startAt); await savePdf(doc, 'BazarPro-Etiketten.pdf'); return data.labels.length; } diff --git a/src/lib/sortMarkPdf.ts b/src/lib/sortMarkPdf.ts new file mode 100644 index 00000000..da5fa129 --- /dev/null +++ b/src/lib/sortMarkPdf.ts @@ -0,0 +1,77 @@ +import type { jsPDF } from 'jspdf'; +import { sortMark, type SortSymbol } from '../shared/sortCode'; + +function drawSymbol(doc: jsPDF, symbol: SortSymbol, cx: number, cy: number, size: number) { + const r = size / 2; + doc.setFillColor(...symbol.ink); + switch (symbol.id) { + case 'circle': + doc.circle(cx, cy, r, 'F'); + break; + case 'triangle': + doc.triangle(cx, cy - r, cx - r, cy + r, cx + r, cy + r, 'F'); + break; + case 'square': + doc.rect(cx - r, cy - r, size, size, 'F'); + break; + case 'diamond': + doc.triangle(cx - r, cy, cx + r, cy, cx, cy - r, 'F'); + // A hair of overlap, so PDF viewers show no seam + doc.triangle(cx - r, cy - 0.02, cx + r, cy - 0.02, cx, cy + r, 'F'); + break; + case 'cross': + doc.rect(cx - r, cy - r / 3, size, (2 * r) / 3, 'F'); + doc.rect(cx - r / 3, cy - r, (2 * r) / 3, size, 'F'); + break; + case 'bars': + doc.rect(cx - r, cy - r, size, size / 4, 'F'); + doc.rect(cx - r, cy - size / 8, size, size / 4, 'F'); + doc.rect(cx - r, cy + r - size / 4, size, size / 4, 'F'); + break; + } +} + +function drawField(doc: jsPDF, symbol: SortSymbol, x: number, y: number, w: number, h: number) { + doc.setFillColor(...symbol.fill); + doc.rect(x, y, w, h, 'F'); + drawSymbol(doc, symbol, x + w / 2, y + h / 2, Math.min(w, h) * 0.6); +} + +/** The large digit (with the letter, if any) and one wide field over two small ones. */ +export function drawSortMark( + doc: jsPDF, + code: number, + x: number, + y: number, + width: number, + height: number +) { + const mark = sortMark(code); + const digitWidth = height * 0.72; + doc.setTextColor(0, 0, 0); + doc.setFont('helvetica', 'bold'); + // 1 pt is 0.353 mm; digits are about 0.72 of the font size high + doc.setFontSize(((mark.letter ? height * 0.72 : height) / 0.353) * 1.05); + const digitY = mark.letter ? y + height * 0.68 : y + height * 0.86; + doc.text(String(mark.digit), x + digitWidth / 2, digitY, { align: 'center' }); + if (mark.letter) { + doc.setFontSize((height * 0.3) / 0.353); + doc.text(mark.letter, x + digitWidth / 2, y + height * 0.98, { align: 'center' }); + } + + const fieldX = x + digitWidth; + const fieldWidth = width - digitWidth; + const gap = height * 0.03; + const rowHeight = (height - gap) / 2; + drawField(doc, mark.fields[0], fieldX, y, fieldWidth, rowHeight); + const smallWidth = (fieldWidth - gap) / 2; + drawField(doc, mark.fields[1], fieldX, y + rowHeight + gap, smallWidth, rowHeight); + drawField( + doc, + mark.fields[2], + fieldX + smallWidth + gap, + y + rowHeight + gap, + smallWidth, + rowHeight + ); +} diff --git a/src/lib/sortSheetsPdf.ts b/src/lib/sortSheetsPdf.ts new file mode 100644 index 00000000..57f9fcb9 --- /dev/null +++ b/src/lib/sortSheetsPdf.ts @@ -0,0 +1,45 @@ +import { jsPDF } from 'jspdf'; +import { compareSortCodes } from '../shared/sortCode'; +import { savePdf } from './saveFile'; +import { drawSortMark } from './sortMarkPdf'; + +const PAGE_WIDTH = 210; +const PAGE_HEIGHT = 297; +const MARGIN = 15; + +export interface SortSheetSeller { + sortCode: number; + name: string; + sellerNumber?: number; +} + +/** A4 pages with two sheets each, in sorting order: one for each seller's basket. */ +export function buildSortSheetsPdf(sellers: SortSheetSeller[]): jsPDF { + const doc = new jsPDF({ orientation: 'portrait', unit: 'mm', format: 'a4' }); + const sheetHeight = PAGE_HEIGHT / 2; + const sorted = [...sellers].sort((a, b) => compareSortCodes(a.sortCode, b.sortCode)); + for (const [i, seller] of sorted.entries()) { + if (i > 0 && i % 2 === 0) doc.addPage(); + const y = (i % 2) * sheetHeight; + drawSortMark(doc, seller.sortCode, MARGIN, y + MARGIN, PAGE_WIDTH - 2 * MARGIN, 90); + doc.setTextColor(0, 0, 0); + doc.setFont('helvetica', 'bold'); + doc.setFontSize(24); + doc.text(seller.name, MARGIN, y + MARGIN + 104, { maxWidth: PAGE_WIDTH - 2 * MARGIN - 30 }); + if (seller.sellerNumber !== undefined) { + doc.text(`Nr. ${seller.sellerNumber}`, PAGE_WIDTH - MARGIN, y + MARGIN + 104, { + align: 'right', + }); + } + if (i % 2 === 0) { + doc.setDrawColor(190); + doc.setLineWidth(0.1); + doc.line(0, sheetHeight, PAGE_WIDTH, sheetHeight); + } + } + return doc; +} + +export async function downloadSortSheets(sellers: SortSheetSeller[]): Promise { + await savePdf(buildSortSheetsPdf(sellers), 'BazarPro-Sortierblaetter.pdf'); +} diff --git a/src/locales/de/company.json b/src/locales/de/company.json index 1329b728..824565f7 100644 --- a/src/locales/de/company.json +++ b/src/locales/de/company.json @@ -13,7 +13,7 @@ }, "qrLabels": { "title": "QR-Etiketten in zwei Größen", - "text": "Verkäufer drucken ihre Etiketten selbst: groß für Fahrräder, klein mit 40 pro Seite für Kleidung, mit Verkäufernummer oder zum Wiederverwenden ohne. Ohne Preis darauf gehen Rabatte ohne Neudruck." + "text": "Verkäufer drucken ihre Etiketten selbst: groß für Fahrräder, klein mit 40 pro Seite für Kleidung, mit Verkäufernummer oder als Universal-Etikett zum Wiederverwenden. Ohne Preis darauf gehen Rabatte ohne Neudruck." }, "phoneCheckout": { "title": "Kasse mit Warenkorb", diff --git a/src/locales/de/organizer.json b/src/locales/de/organizer.json index b1c0aab7..69db4127 100644 --- a/src/locales/de/organizer.json +++ b/src/locales/de/organizer.json @@ -139,8 +139,14 @@ "labelsLarge": "Groß – 12 pro A4-Seite (z. B. Fahrräder)", "labelsSmall": "Klein – 40 pro A4-Seite (z. B. Kleidung)", "labelsHint": "Auf jedem Etikett stehen QR-Code, Titel und – wenn angegeben – die Größe.", - "sellerNumberOnLabel": "Verkäufernummer aufs Etikett drucken", - "sellerNumberOnLabelText": "Hilft beim Zurücksortieren nach dem Basar. Ausgeschaltet können Verkäufer ihre Etiketten beim nächsten Basar wiederverwenden. Der QR-Code bleibt gültig.", + "labelMark": "Verkäufer auf dem Etikett", + "labelMarkNumber": "Verkäufernummer dieses Basars", + "labelMarkUniversal": "Universal-Etikett: Ziffer und Sortierzeichen (nur kleine Etiketten)", + "labelMarkNone": "Nichts, nur QR-Code", + "labelMarkNumberHint": "Am einfachsten zu lesen. Die Nummer gilt nur für diesen Basar, Verkäufer drucken für den nächsten neu.", + "labelMarkUniversalHint": "Für viele kleine Teile: Helfer sortieren erst nach der großen Ziffer, dann nach Farben und Symbolen, ohne zu lesen. Das Zeichen bleibt beim Verkäufer, die Etiketten passen also auch bei anderen Basaren mit Universal-Etiketten. Es funktioniert auch im Schwarz-Weiß-Druck.", + "labelMarkNoneHint": "Die Etiketten lassen sich wiederverwenden. Zum Zurücksortieren muss das Team aber jeden Artikel scannen.", + "labelMarkNeedsSmall": "Universal-Etiketten gibt es nur im kleinen Format. Im großen Format wird die Verkäufernummer gedruckt.", "priceOnLabel": "Preis aufs Etikett drucken", "priceOnLabelText": "Hilft an der Kasse ohne Scanner. Der Preis auf dem Etikett ist fest – bei Rabatten wird er deshalb nicht gedruckt.", "priceOnLabelDiscounts": "Rabatte sind eingeschaltet, deshalb erscheint kein Preis auf den Etiketten.", @@ -261,13 +267,16 @@ "labelsSmall": "Kleine Etiketten (40 pro Seite)", "labelsLarge": "Große Etiketten (12 pro Seite)", "priceOnLabel": "Preis auf dem Etikett", - "sellerNumberOnLabel": "Verkäufernummer auf dem Etikett", + "labelMarkNumber": "Verkäufernummer auf dem Etikett", + "labelMarkUniversal": "Universal-Etikett mit Sortierzeichen", "questionsDuringEvent": "erst während des Basars", "requiredFields": "Pflichtangaben: {{fields}}", "privateSellers": "Nur Privatverkäufer", "fixedData": "Feste Daten für den Nachweis" }, "sellers": { + "sortSheets": "Sortierblätter", + "sortSheetsHint": "Ein Blatt pro Verkäufer für die Kiste, in Sortierreihenfolge", "helperRemoved": "{{name}} ist kein Helfer mehr", "helperAdded": "{{name}} wurde als Helfer hinzugefügt", "actionFailed": "Aktion fehlgeschlagen", @@ -818,6 +827,7 @@ "labelPriceHidden": "Ohne Preis: Rabatte ändern ihn ja noch.", "labelNumber": "Nr. {{seller}}", "labelReusable": "Ohne Verkäufernummer: Das Etikett passt auch beim nächsten Basar.", + "labelUniversal": "Universal-Etikett: Ziffer, Farben und Symbole bleiben beim Verkäufer. Das Team sortiert danach und braucht nichts zu lesen.", "photoRequired": "Foto Pflicht", "photoOptional": "Ohne Foto", "maxItems": "Bis zu {{count}} Artikel pro Verkäufer", diff --git a/src/locales/de/seller.json b/src/locales/de/seller.json index 91223956..53e7776f 100644 --- a/src/locales/de/seller.json +++ b/src/locales/de/seller.json @@ -199,6 +199,9 @@ "formatSmall": "Format Klein: {{perPage}} kleine Etiketten pro Seite", "formatPerItem": "Format und Verkäufernummer nach dem jeweils nächsten Basar des Artikels, sonst Standard", "reusable": "Ohne Verkäufernummer: Du kannst diese Etiketten beim nächsten Basar wiederverwenden.", + "reusableUniversal": "Mit Sortierzeichen statt Nummer: Diese Etiketten kannst du bei anderen Basaren mit Universal-Etiketten wiederverwenden.", + "startAt": "Erstes freies Feld auf dem Bogen", + "startAtHint": "Für angebrochene Bögen: Zeile für Zeile gezählt, 1 bis {{perPage}}.", "download": "PDF herunterladen", "created_one": "{{count}} Etikett erstellt", "created_other": "{{count}} Etiketten erstellt", diff --git a/src/locales/en/company.json b/src/locales/en/company.json index 72786b72..dd7c0d6d 100644 --- a/src/locales/en/company.json +++ b/src/locales/en/company.json @@ -13,7 +13,7 @@ }, "qrLabels": { "title": "QR labels in two sizes", - "text": "Sellers print their own labels: large for bikes, small with 40 per page for clothes, with the seller number or without it for reuse. Without a price on them, discounts work without reprinting." + "text": "Sellers print their own labels: large for bikes, small with 40 per page for clothes, with the seller number or as a reusable universal label. Without a price on them, discounts work without reprinting." }, "phoneCheckout": { "title": "Checkout with a cart", diff --git a/src/locales/en/organizer.json b/src/locales/en/organizer.json index 02724ddf..321a9453 100644 --- a/src/locales/en/organizer.json +++ b/src/locales/en/organizer.json @@ -139,8 +139,14 @@ "labelsLarge": "Large – 12 per A4 page (e.g. bikes)", "labelsSmall": "Small – 40 per A4 page (e.g. clothes)", "labelsHint": "Every label shows QR code, title and – if given – the size.", - "sellerNumberOnLabel": "Print the seller number on the label", - "sellerNumberOnLabelText": "Helps sorting items back after the bazaar. Switched off, sellers can reuse their labels at the next bazaar. The QR code stays valid.", + "labelMark": "Seller on the label", + "labelMarkNumber": "Seller number of this bazaar", + "labelMarkUniversal": "Universal label: digit and sorting mark (small labels only)", + "labelMarkNone": "Nothing, QR code only", + "labelMarkNumberHint": "Easiest to read. The number is only valid for this bazaar, sellers print again for the next.", + "labelMarkUniversalHint": "For many small items: helpers sort by the large digit first, then by colors and symbols, without reading. The mark stays with the seller, so labels also work at other bazaars with universal labels. It also works in black and white.", + "labelMarkNoneHint": "Labels can be reused. To sort items back, the team has to scan every one.", + "labelMarkNeedsSmall": "Universal labels only exist in the small format. The large format prints the seller number.", "priceOnLabel": "Print the price on the label", "priceOnLabelText": "Helps at a cash desk without scanner. The printed price is fixed – so it is not printed when discounts are on.", "priceOnLabelDiscounts": "Discounts are switched on, so no price appears on the labels.", @@ -261,13 +267,16 @@ "labelsSmall": "Small labels (40 per page)", "labelsLarge": "Large labels (12 per page)", "priceOnLabel": "Price on the label", - "sellerNumberOnLabel": "Seller number on the label", + "labelMarkNumber": "Seller number on the label", + "labelMarkUniversal": "Universal label with sorting mark", "questionsDuringEvent": "only during the bazaar", "requiredFields": "Required details: {{fields}}", "privateSellers": "Private sellers only", "fixedData": "Fixed data for the record" }, "sellers": { + "sortSheets": "Sorting sheets", + "sortSheetsHint": "One sheet per seller for the basket, in sorting order", "helperRemoved": "{{name}} is no longer a helper", "helperAdded": "{{name}} was added as a helper", "actionFailed": "Action failed", @@ -818,6 +827,7 @@ "labelPriceHidden": "No price: discounts may still change it.", "labelNumber": "No. {{seller}}", "labelReusable": "No seller number: the label also works at the next bazaar.", + "labelUniversal": "Universal label: digit, colors and symbols stay with the seller. The team sorts by them without reading.", "photoRequired": "Photo required", "photoOptional": "No photo", "maxItems": "Up to {{count}} items per seller", diff --git a/src/locales/en/seller.json b/src/locales/en/seller.json index 458d6969..a6be5552 100644 --- a/src/locales/en/seller.json +++ b/src/locales/en/seller.json @@ -199,6 +199,9 @@ "formatSmall": "Small format: {{perPage}} small labels per page", "formatPerItem": "Format and seller number from each item's next bazaar, otherwise standard", "reusable": "No seller number: you can reuse these labels at the next bazaar.", + "reusableUniversal": "With a sorting mark instead of a number: you can reuse these labels at other bazaars with universal labels.", + "startAt": "First free place on the sheet", + "startAtHint": "For partly used sheets: counted row by row, 1 to {{perPage}}.", "download": "Download PDF", "created_one": "{{count}} label created", "created_other": "{{count}} labels created", diff --git a/src/pages/organizer/events/EditEventForm.tsx b/src/pages/organizer/events/EditEventForm.tsx index 842ddb4c..edb3fae9 100644 --- a/src/pages/organizer/events/EditEventForm.tsx +++ b/src/pages/organizer/events/EditEventForm.tsx @@ -8,7 +8,7 @@ import { Button } from '../../../components/ui/button'; import { useApiClient, useAuthState, useMutation, useQuery } from '../../../lib/api/react'; import { api } from '../../../lib/api/functions'; import type { Doc, Id } from '../../../lib/api/types'; -import { LABEL_FORMATS } from '../../../shared/constants'; +import { LABEL_FORMATS, LABEL_MARKS } from '../../../shared/constants'; import { EditEventBasicInfo } from './components/EditEventBasicInfo'; import { EditEventCategories } from './components/EditEventCategories'; import { EditEventContact } from './components/EditEventContact'; @@ -163,7 +163,7 @@ const buildEventSchema = ( .or(z.nan()), labelFormat: z.enum(LABEL_FORMATS), priceOnLabel: z.boolean(), - sellerNumberOnLabel: z.boolean(), + labelMark: z.enum(LABEL_MARKS), privateSellersOnly: z.boolean(), fixedSellerData: z.boolean(), intakeFee: z @@ -276,7 +276,7 @@ function featuresToForm(stored: StoredEventFeatures | undefined): FeatureFormDat maxItemsPerSeller: features.maxItemsPerSeller, labelFormat: features.labelFormat, priceOnLabel: features.priceOnLabel, - sellerNumberOnLabel: features.sellerNumberOnLabel, + labelMark: features.labelMark, intakeFee: features.intakeFee, privateSellersOnly: features.privateSellersOnly, fixedSellerData: features.fixedSellerData, @@ -303,7 +303,7 @@ function featuresFromForm(features: FeatureFormData): StoredEventFeatures { : undefined, labelFormat: features.labelFormat, priceOnLabel: features.priceOnLabel, - sellerNumberOnLabel: features.sellerNumberOnLabel, + labelMark: features.labelMark, intakeFee: typeof features.intakeFee === 'number' && !isNaN(features.intakeFee) && features.intakeFee > 0 ? features.intakeFee diff --git a/src/pages/organizer/events/components/EditEventFeatures.tsx b/src/pages/organizer/events/components/EditEventFeatures.tsx index daa59b24..0be5213c 100644 --- a/src/pages/organizer/events/components/EditEventFeatures.tsx +++ b/src/pages/organizer/events/components/EditEventFeatures.tsx @@ -18,7 +18,6 @@ type FeatureKey = | 'questions' | 'photosOptional' | 'priceOnLabel' - | 'sellerNumberOnLabel' | 'privateSellersOnly' | 'fixedSellerData'; @@ -223,6 +222,8 @@ export function EditEventFeatures({ } = useFormContext(); const discounts = watch('features.discounts') as boolean; const priceOnLabel = watch('features.priceOnLabel') as boolean; + const labelFormat = watch('features.labelFormat') as string; + const labelMark = watch('features.labelMark') as string; const featureErrors = errors.features as | Partial< Record<'maxDiscountPercent' | 'intakeFee' | 'maxItemsPerSeller', { message?: string }> @@ -339,11 +340,34 @@ export function EditEventFeatures({

{t('features.labelsHint')}

- +
+ + +

+ {t( + labelMark === 'universal' + ? 'features.labelMarkUniversalHint' + : labelMark === 'none' + ? 'features.labelMarkNoneHint' + : 'features.labelMarkNumberHint' + )} +

+ {labelMark === 'universal' && labelFormat !== 'small' && ( +

+ {t('features.labelMarkNeedsSmall')} +

+ )} +
- {small && withNumber &&

Nr. 17

} + {small && mark === 'number' &&

Nr. 17

} + {small && mark === 'universal' && ( + + )}

- {[!small && withNumber && number, price !== undefined && `${formatPriceDE(price)} €`] + {[ + !small && mark === 'number' && number, + price !== undefined && `${formatPriceDE(price)} €`, + ] .filter(Boolean) .join(' · ')}

@@ -407,7 +418,7 @@ export function ItemsPreview({ type }: { type?: EventType }) { const limit = given(features.maxItemsPerSeller); const small = features.labelFormat === 'small'; const showPrice = !!features.priceOnLabel && !features.discounts; - const withNumber = features.sellerNumberOnLabel !== false; + const mark = effectiveLabelMark({ features: features as StoredEventFeatures }); return ( · {t('wizard.preview.labelPriceHidden')}} - {!withNumber && ( + {mark === 'universal' && ( + }>{t('wizard.preview.labelUniversal')} + )} + {mark === 'none' && ( }>{t('wizard.preview.labelReusable')} )} }> @@ -470,7 +484,7 @@ export function ItemsPreview({ type }: { type?: EventType }) { small={small} title={items[0].title} price={showPrice ? items[0].price : undefined} - withNumber={withNumber} + mark={mark} />
diff --git a/src/pages/organizer/events/dashboard/SellerManagementPage.tsx b/src/pages/organizer/events/dashboard/SellerManagementPage.tsx index e18d6f31..e0693721 100644 --- a/src/pages/organizer/events/dashboard/SellerManagementPage.tsx +++ b/src/pages/organizer/events/dashboard/SellerManagementPage.tsx @@ -1,3 +1,5 @@ +import { SortMarkBadge } from '../../../../components/sellers/SortMarkBadge'; +import { downloadSortSheets } from '../../../../lib/sortSheetsPdf'; import { useMemo, useState } from 'react'; import { WalkInBadge } from '../../../../components/walkIn/WalkInBadge'; import { SellerNumberBadge } from '../../../../components/sellers/SellerNumberBadge'; @@ -32,12 +34,14 @@ import { AlertTriangle, Info, Megaphone, + Printer, } from 'lucide-react'; import { formatPriceDE } from '../../../../lib/utils'; import type { VendorWithCalculations } from '../../../../lib/api/types'; import { Tabs, TabsList, TabsTrigger } from '../../../../components/ui/tabs'; import { Button } from '../../../../components/ui/button'; import { toast } from 'sonner'; +import { getUserFacingErrorMessage } from '../../../../lib/errors'; import { AlertDialog, AlertDialogAction, @@ -86,6 +90,12 @@ export function SellerManagementPage() { const vendors = useQuery(api.eventRoles.getVendorsForEvent, { eventId: eventId as Id<'events'>, }) as VendorWithCalculations[] | undefined; + // Only universal labels bring a sorting code along: one sheet for each seller's basket + const sortSheetSellers = (vendors ?? []).flatMap((v) => + v.sortCode === undefined + ? [] + : [{ sortCode: v.sortCode, name: v.name ?? '-', sellerNumber: v.sellerNumber }] + ); const addHelper = useMutation(api.eventRoles.addCoOrganizerForEvent); useAssignMissingSellerNumbers(eventId as Id<'events'>, vendors, canManage); @@ -169,6 +179,20 @@ export function SellerManagementPage() { > {t('sellers.walkIn')} + {sortSheetSellers.length > 0 && ( + + )}
{v.name} + {v.sortCode !== undefined && ( + + )} {v.managedByEventId && } {v.isHelper && !isOwner && ( diff --git a/src/pages/organizer/events/dashboard/components/EventSettingsSummary.tsx b/src/pages/organizer/events/dashboard/components/EventSettingsSummary.tsx index c2b0c9ba..363d2ee0 100644 --- a/src/pages/organizer/events/dashboard/components/EventSettingsSummary.tsx +++ b/src/pages/organizer/events/dashboard/components/EventSettingsSummary.tsx @@ -1,7 +1,7 @@ import type { ReactNode } from 'react'; import { Check, Minus } from 'lucide-react'; import type { Doc } from '../../../../../lib/api/types'; -import { resolveEventFeatures } from '../../../../../shared/eventFeatures'; +import { effectiveLabelMark, resolveEventFeatures } from '../../../../../shared/eventFeatures'; import { VISIBILITY_OPTIONS } from '../../../../../constants/records'; import { formatDateRangeDE, formatPriceDE } from '../../../../../lib/utils'; import { Badge } from '../../../../../components/ui/badge'; @@ -64,6 +64,7 @@ export function EventSettingsSummary({ event }: { event: EventWithLabels }) { minute: '2-digit', }); const features = resolveEventFeatures(event); + const labelMark = effectiveLabelMark(event); const logistics = event.sellerLogistics; const discountDetail = [ features.discountStartsAt @@ -155,7 +156,12 @@ export function EventSettingsSummary({ event }: { event: EventWithLabels }) { features.labelFormat === 'small' ? t('summary.labelsSmall') : t('summary.labelsLarge') } /> - + { it('tells the seller when the labels of a bazaar can be reused', async () => { const reusable = { ...events[0], - features: { sellerNumberOnLabel: false }, + features: { labelFormat: 'small', labelMark: 'universal' }, } as unknown as Doc<'events'>; render( { eventId="later" /> ); - expect(await screen.findByText(/beim nächsten Basar wiederverwenden/)).toBeInTheDocument(); + expect( + await screen.findByText(/anderen Basaren mit Universal-Etiketten wiederverwenden/) + ).toBeInTheDocument(); + }); + + it('starts on a free place of a partly used sheet (#238)', async () => { + renderDialog('next'); + expect(await screen.findByText('42 Etiketten auf 2 A4-Seiten')).toBeInTheDocument(); + fireEvent.change(screen.getByLabelText('Erstes freies Feld auf dem Bogen'), { + target: { value: '40' }, + }); + // One label left on the first sheet, 41 need two more + expect(await screen.findByText('42 Etiketten auf 3 A4-Seiten')).toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: 'PDF herunterladen' })); + await waitFor(() => + expect(downloadLabelsPdf).toHaveBeenCalledWith(client, expect.any(Array), 'next', 40) + ); }); it('prints the unsold items of the chosen bazaar for that bazaar', async () => { @@ -87,7 +103,9 @@ describe('LabelPrintDialog', () => { expect(await screen.findByText('1 Etikett auf 1 A4-Seite')).toBeInTheDocument(); expect(screen.getByText('Format Standard: 12 große Etiketten pro Seite')).toBeInTheDocument(); fireEvent.click(screen.getByRole('button', { name: 'PDF herunterladen' })); - await waitFor(() => expect(downloadLabelsPdf).toHaveBeenCalledWith(client, ['p101'], 'later')); + await waitFor(() => + expect(downloadLabelsPdf).toHaveBeenCalledWith(client, ['p101'], 'later', 1) + ); }); it('falls back to all available items without a bazaar', async () => { @@ -98,7 +116,7 @@ describe('LabelPrintDialog', () => { expect(screen.getByText(/nach dem jeweils nächsten Basar/)).toBeInTheDocument(); fireEvent.click(screen.getByRole('button', { name: 'PDF herunterladen' })); await waitFor(() => - expect(downloadLabelsPdf).toHaveBeenCalledWith(client, expect.any(Array), undefined) + expect(downloadLabelsPdf).toHaveBeenCalledWith(client, expect.any(Array), undefined, 1) ); expect(vi.mocked(downloadLabelsPdf).mock.calls[0][1]).toHaveLength(43); }); diff --git a/src/pages/seller/products/components/LabelPrintDialog.tsx b/src/pages/seller/products/components/LabelPrintDialog.tsx index 657149ec..1a312658 100644 --- a/src/pages/seller/products/components/LabelPrintDialog.tsx +++ b/src/pages/seller/products/components/LabelPrintDialog.tsx @@ -11,6 +11,8 @@ import { DialogTitle, } from '../../../../components/ui/dialog'; import { Button } from '../../../../components/ui/button'; +import { Input } from '../../../../components/ui/input'; +import { Label } from '../../../../components/ui/label'; import { Select, SelectContent, @@ -23,6 +25,7 @@ import type { Doc, Id } from '../../../../lib/api/types'; import { getUserFacingErrorMessage } from '../../../../lib/errors'; import { LABEL_LAYOUTS, downloadLabelsPdf } from '../../../../lib/productQRCodePdf'; import { formatDateDE } from '../../../../lib/utils'; +import { effectiveLabelMark } from '../../../../shared/eventFeatures'; /** Without a bazaar: all available items, each on the sheet of its next bazaar */ const ALL = 'all'; @@ -51,6 +54,7 @@ export function LabelPrintDialog({ const client = useApiClient(); const [choice, setChoice] = useState(ALL); const [isCreating, setIsCreating] = useState(false); + const [startInput, setStartInput] = useState('1'); const available = useMemo(() => products.filter((p) => !p.sold), [products]); @@ -71,18 +75,23 @@ export function LabelPrintDialog({ if (!open) return; const preselected = bazaars.find((bazaar) => bazaar.event._id === eventId); setChoice(preselected?.event._id ?? bazaars[0]?.event._id ?? ALL); + setStartInput('1'); }, [open, eventId, bazaars]); const bazaar = bazaars.find((entry) => entry.event._id === choice); const ids = bazaar ? bazaar.ids : available.map((p) => p._id); const format = bazaar?.event.features?.labelFormat ?? 'standard'; const { cols, rows } = LABEL_LAYOUTS[format]; - const pages = Math.ceil(ids.length / (cols * rows)); + const perPage = cols * rows; + // Only for one bazaar: only then the sheet is known before the PDF is made + const startAt = bazaar ? Math.min(Math.max(Math.trunc(Number(startInput)) || 1, 1), perPage) : 1; + const pages = Math.ceil((ids.length + startAt - 1) / perPage); + const mark = bazaar && effectiveLabelMark(bazaar.event); const create = async () => { setIsCreating(true); try { - const count = await downloadLabelsPdf(client, ids, bazaar?.event._id); + const count = await downloadLabelsPdf(client, ids, bazaar?.event._id, startAt); toast.success(t('labels.created', { count })); onOpenChange(false); } catch (e) { @@ -128,10 +137,30 @@ export function LabelPrintDialog({ }) : t('labels.formatPerItem')}

- {bazaar?.event.features?.sellerNumberOnLabel === false && ( -

{t('labels.reusable')}

+ {mark === 'universal' && ( +

{t('labels.reusableUniversal')}

)} + {mark === 'none' &&

{t('labels.reusable')}

}
+ + {bazaar && ( +
+ + setStartInput(e.target.value)} + /> +

+ {t('labels.startAtHint', { perPage })} +

+
+ )} diff --git a/src/shared/constants.ts b/src/shared/constants.ts index d7d6aff6..6404ebfb 100644 --- a/src/shared/constants.ts +++ b/src/shared/constants.ts @@ -25,6 +25,10 @@ export const PLACEHOLDER_PATTERN = /\[\[[^\]]+\]\]/; export const LABEL_FORMATS = ['standard', 'small'] as const; export type LabelFormat = (typeof LABEL_FORMATS)[number]; +/** What tells sellers' items apart on labels: see EventFeatures.labelMark */ +export const LABEL_MARKS = ['number', 'universal', 'none'] as const; +export type LabelMark = (typeof LABEL_MARKS)[number]; + export const SYSTEM_ROLES = ['admin', 'user'] as const; // leave admin always on position SYSTEM_ROLES[0]!! export type SystemRole = (typeof SYSTEM_ROLES)[number]; diff --git a/src/shared/eventFeatures.ts b/src/shared/eventFeatures.ts index 1a44c4b6..ae602e1e 100644 --- a/src/shared/eventFeatures.ts +++ b/src/shared/eventFeatures.ts @@ -1,4 +1,4 @@ -import type { LabelFormat } from './constants'; +import type { LabelFormat, LabelMark } from './constants'; import type { ErrorCode } from './errorCodes'; import type { CategoryField } from './categoryFields'; /** @@ -38,10 +38,11 @@ export interface EventFeatures { /** Print the price on labels; only takes effect while discounts are off. */ priceOnLabel: boolean; /** - * Print the seller number on labels. Off, a label holds nothing specific to this bazaar - * (the QR code only links to the item), so sellers can reuse it at their next one. + * The seller's mark on labels. `number`: the number at this bazaar. `universal`: a code + * that stays with the seller, read by sight (small labels only). `none`: only the QR code, + * which just links to the item. The last two can be reused at the next bazaar. */ - sellerNumberOnLabel: boolean; + labelMark: LabelMark; /** Fixed fee in € per accepted item (sold or not), kept from the payout; unset means none. */ intakeFee?: number; /** Sellers confirm when joining that they sell as private persons, not as traders. */ @@ -70,7 +71,7 @@ export const DEFAULT_EVENT_FEATURES: EventFeatures = { photosOptional: false, labelFormat: 'standard', priceOnLabel: false, - sellerNumberOnLabel: true, + labelMark: 'number', privateSellersOnly: false, fixedSellerData: false, }; @@ -185,6 +186,14 @@ export function areOffersOpen( return listing.status === 'available' && listing.startDate <= now && now <= listing.endDate; } +/** The mark labels of this event really carry: universal ones need the small sheet. */ +export function effectiveLabelMark(event: { features?: StoredEventFeatures }): LabelMark { + const features = resolveEventFeatures(event); + return features.labelMark === 'universal' && features.labelFormat !== 'small' + ? 'number' + : features.labelMark; +} + /** Whether labels of this event show the price: a discount would make a printed price wrong. */ export function showsPriceOnLabel(event: { features?: StoredEventFeatures }): boolean { const features = resolveEventFeatures(event); diff --git a/src/shared/sortCode.test.ts b/src/shared/sortCode.test.ts new file mode 100644 index 00000000..e7091533 --- /dev/null +++ b/src/shared/sortCode.test.ts @@ -0,0 +1,37 @@ +import { describe, expect, it } from 'vitest'; +import { compareSortCodes, sortMark } from './sortCode'; + +const signature = (code: number) => { + const mark = sortMark(code); + return `${mark.digit}|${mark.fields.map((field) => field.id).join()}|${mark.letter}`; +}; + +describe('sortMark', () => { + it('gives every seller an own mark', () => { + const marks = new Set(Array.from({ length: 30_000 }, (_, code) => signature(code + 1))); + expect(marks.size).toBe(30_000); + }); + + it('needs no letter for the first 2160 sellers', () => { + expect(sortMark(1).letter).toBe(''); + expect(sortMark(2159).letter).toBe(''); + expect(sortMark(2160).letter).toBe('A'); + expect(sortMark(2160 * 26).letter).toBe('Z'); + expect(sortMark(2160 * 27).letter).toBe('AA'); + }); + + it('makes codes of one pile differ in all fields, also one after the other', () => { + const [a, b] = [sortMark(15), sortMark(25)]; + expect(a.digit).toBe(b.digit); + a.fields.forEach((field, i) => expect(field.id).not.toBe(b.fields[i].id)); + }); + + it('stays the same: printed labels depend on it', () => { + expect(signature(175)).toBe('5|diamond,circle,bars|'); + }); + + it('sorts by digit first', () => { + const sorted = [13, 22, 31, 40].sort(compareSortCodes); + expect(sorted.map((code) => code % 10)).toEqual([0, 1, 2, 3]); + }); +}); diff --git a/src/shared/sortCode.ts b/src/shared/sortCode.ts new file mode 100644 index 00000000..69d9ad09 --- /dev/null +++ b/src/shared/sortCode.ts @@ -0,0 +1,83 @@ +/** + * Sorting code of universal labels. Unsold items are sorted back without reading: first + * into piles by the large digit, then by the three fields. A seller keeps the code at + * every bazaar, so printed labels stay valid. + * + * Every field has a color and its own symbol: most sellers print in black and white, and + * not every helper tells all colors apart. A letter only appears after the first 2160 + * sellers, to tell two sellers with the same digit and fields apart. + */ + +export interface SortSymbol { + id: 'circle' | 'triangle' | 'square' | 'diamond' | 'cross' | 'bars'; + /** Field color, also distinct for color-blind helpers (Okabe-Ito) */ + fill: [number, number, number]; + /** Color of the symbol on the field, the stronger contrast also in black and white */ + ink: [number, number, number]; +} + +const WHITE: [number, number, number] = [255, 255, 255]; +const BLACK: [number, number, number] = [0, 0, 0]; + +export const SORT_SYMBOLS: readonly SortSymbol[] = [ + { id: 'circle', fill: [0, 114, 178], ink: WHITE }, + { id: 'triangle', fill: [230, 159, 0], ink: BLACK }, + { id: 'square', fill: [0, 120, 90], ink: WHITE }, + { id: 'diamond', fill: [240, 228, 66], ink: BLACK }, + { id: 'cross', fill: [204, 121, 167], ink: BLACK }, + { id: 'bars', fill: [30, 30, 30], ink: WHITE }, +]; + +const PATTERNS = SORT_SYMBOLS.length ** 3; +/** + * Walks through all patterns so that neighboring codes differ in all three fields: + * sellers who sign up one after the other are easy to tell apart. Coprime to PATTERNS. + */ +const PATTERN_STEP = 121; + +export interface SortMark { + digit: number; + fields: [SortSymbol, SortSymbol, SortSymbol]; + /** Empty for most sellers */ + letter: string; +} + +function letterOf(index: number): string { + let letter = ''; + for (let rest = index; rest > 0; rest = Math.floor((rest - 1) / 26)) { + letter = String.fromCharCode(65 + ((rest - 1) % 26)) + letter; + } + return letter; +} + +export function sortMark(code: number): SortMark { + const group = Math.floor(code / 10); + const pattern = (group * PATTERN_STEP) % PATTERNS; + const count = SORT_SYMBOLS.length; + return { + digit: code % 10, + fields: [ + SORT_SYMBOLS[Math.floor(pattern / count ** 2)], + SORT_SYMBOLS[Math.floor(pattern / count) % count], + SORT_SYMBOLS[pattern % count], + ], + letter: letterOf(Math.floor(group / PATTERNS)), + }; +} + +/** For putting the baskets in a row in sorting order: by digit, then by the fields. */ +export function compareSortCodes(a: number, b: number): number { + const key = (code: number) => { + const mark = sortMark(code); + return [ + mark.digit, + ...mark.fields.map((field) => SORT_SYMBOLS.indexOf(field)), + mark.letter.length, + ]; + }; + const [left, right] = [key(a), key(b)]; + for (const [i, value] of left.entries()) { + if (value !== right[i]) return value - right[i]; + } + return sortMark(a).letter.localeCompare(sortMark(b).letter); +} From c1d3f0113238f2eab43e772d89d2b572ccd9618d Mon Sep 17 00:00:00 2001 From: Ivo Zeitz Date: Mon, 2 Nov 2026 10:59:05 +0100 Subject: [PATCH 04/14] feat(events): universal labels by default for kids and clothing bazaars Co-Authored-By: Claude Opus 5.5 --- src/lib/eventTypes.test.ts | 14 +++++++++++++- src/lib/eventTypes.ts | 4 ++++ src/locales/de/organizer.json | 2 +- src/locales/en/organizer.json | 2 +- 4 files changed, 19 insertions(+), 3 deletions(-) diff --git a/src/lib/eventTypes.test.ts b/src/lib/eventTypes.test.ts index 278d7990..21370d55 100644 --- a/src/lib/eventTypes.test.ts +++ b/src/lib/eventTypes.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest'; import { EVENT_TYPES, findEventType } from './eventTypes'; -import { showsPriceOnLabel } from '../shared/eventFeatures'; +import { effectiveLabelMark, showsPriceOnLabel } from '../shared/eventFeatures'; import { REQUIRABLE_FIELD_KEYS } from '../shared/categoryFields'; import i18n from '../i18n'; @@ -21,6 +21,18 @@ describe('event types', () => { } }); + it('uses universal labels where many small items are sorted back', () => { + const marks = Object.fromEntries( + EVENT_TYPES.map((type) => [type.id, effectiveLabelMark(type)]) + ); + expect(marks).toEqual({ + kidsBazaar: 'universal', + clothingBazaar: 'universal', + skiBazaar: 'number', + bikeExchange: 'number', + }); + }); + it('the most asked for kinds come first, each with examples for the previews', () => { expect(EVENT_TYPES.map((type) => type.id)).toEqual([ 'kidsBazaar', diff --git a/src/lib/eventTypes.ts b/src/lib/eventTypes.ts index 0db4bc4b..af51467a 100644 --- a/src/lib/eventTypes.ts +++ b/src/lib/eventTypes.ts @@ -38,6 +38,8 @@ export const EVENT_TYPES: EventType[] = [ photosOptional: true, maxItemsPerSeller: 50, labelFormat: 'small', + // Many small items: sorted back by sight, and the labels work at the next bazaar + labelMark: 'universal', priceOnLabel: false, }, categoryMatch: /kind|baby|spiel|kleid|schuh|buch/i, @@ -57,6 +59,8 @@ export const EVENT_TYPES: EventType[] = [ photosOptional: true, maxItemsPerSeller: 30, labelFormat: 'small', + // Many small items: sorted back by sight, and the labels work at the next bazaar + labelMark: 'universal', priceOnLabel: false, }, categoryMatch: /kleid|schuh|accessoir|haushalt|buch|spiel/i, diff --git a/src/locales/de/organizer.json b/src/locales/de/organizer.json index 69db4127..5ed54778 100644 --- a/src/locales/de/organizer.json +++ b/src/locales/de/organizer.json @@ -902,7 +902,7 @@ "kidsBazaar": { "title": "Kinderbasar", "text": "Kinderkleidung, Spielzeug, Bücher und Ausstattung – viele kleine Teile pro Familie.", - "highlights": ["Kleine Etiketten", "Fotos freiwillig", "Rabatte zum Schluss"], + "highlights": ["Universal-Etiketten", "Fotos freiwillig", "Rabatte zum Schluss"], "exampleTitle": "Kinderbasar", "exampleItems": [ "T-Shirt und Latzhose, Gr. 98", diff --git a/src/locales/en/organizer.json b/src/locales/en/organizer.json index 321a9453..bc006076 100644 --- a/src/locales/en/organizer.json +++ b/src/locales/en/organizer.json @@ -902,7 +902,7 @@ "kidsBazaar": { "title": "Children's bazaar", "text": "Children's clothes, toys, books and gear – many small items per family.", - "highlights": ["Small labels", "Photos optional", "Discounts at the end"], + "highlights": ["Universal labels", "Photos optional", "Discounts at the end"], "exampleTitle": "Children's bazaar", "exampleItems": ["T-shirt and dungarees, size 98", "Lego box, mixed", "Rubber boots, size 27"] }, From d00c820d945d4b6f5546c67c2029b167c341274e Mon Sep 17 00:00:00 2001 From: Ivo Zeitz Date: Mon, 2 Nov 2026 13:43:57 +0100 Subject: [PATCH 05/14] feat(demo): seed universal labels, QR-only labels and venue addresses The kids and clothing bazaars print universal labels, the flea market QR-only labels. Venues get a structured address, including one in Austria. Co-Authored-By: Claude Opus 5.5 --- backend/src/demo/extended.rs | 54 ++++++++++++++++++++++++++++++++--- backend/tests/api/demo.rs | 55 ++++++++++++++++++++++++++++++++++++ 2 files changed, 105 insertions(+), 4 deletions(-) diff --git a/backend/src/demo/extended.rs b/backend/src/demo/extended.rs index 57c5cddf..bfd47e87 100644 --- a/backend/src/demo/extended.rs +++ b/backend/src/demo/extended.rs @@ -108,11 +108,21 @@ struct Demo<'a> { single: bool, } +/// Address of the venue. Empty parts in English: the address form knows no British towns, +/// those demos keep it all in the location, as older events do. +struct Venue { + street: Text, + postal_code: Text, + city: Text, + country: &'static str, +} + struct EventPlan { organizer: Uuid, title: Text, description: Text, location: Text, + address: Option, contact: &'static str, services: &'static [&'static str], visibility: &'static str, @@ -239,6 +249,14 @@ impl Demo<'_> { "commission": plan.commission, "features": plan.features, }); + if let Some(venue) = &plan.address { + args["address"] = json!({ + "street": self.text(venue.street), + "postalCode": self.text(venue.postal_code), + "city": self.text(venue.city), + "country": venue.country, + }); + } if let Some(cover) = self.seeder.image(plan.cover) { args["coverImage"] = json!(cover); } @@ -659,9 +677,15 @@ async fn kids_bazaar(demo: &mut Demo<'_>, people: &People) -> anyhow::Result<()> "Second-hand bazaar for children's clothes, toys, books and prams. Run by the parents' council, 15 % go to the nursery. With a cake buffet!\n\nDrop-off the day before, unsold items can be picked up from 3 pm.", ), location: t( - "Kita Sonnenschein, Turnraum, Lindenstraße 4, Ulm", + "Kita Sonnenschein, Turnraum", "Sunshine Nursery, gym, 4 Linden Street, Oxford", ), + address: Some(Venue { + street: t("Lindenstraße 4", ""), + postal_code: t("89073", ""), + city: t("Ulm", ""), + country: "DE", + }), contact: "elternbeirat@example.org", services: &["Imbiss", "Getränke"], visibility: "public", @@ -678,6 +702,7 @@ async fn kids_bazaar(demo: &mut Demo<'_>, people: &People) -> anyhow::Result<()> "minimumPrice": true, "questions": true, "labelFormat": "small", + "labelMark": "universal", "intakeFee": 0.5, "privateSellersOnly": true, "fixedSellerData": true, @@ -948,9 +973,15 @@ async fn ski_bazaar(demo: &mut Demo<'_>, people: &People) -> anyhow::Result<()> "Used skis, snowboards, boots, helmets and winter clothing. Our instructors help you choose, and the waxing service is on site.\n\nSellers register with the access code from the club newsletter.", ), location: t( - "Mehrzweckhalle Blaustein, Am Sportplatz 2", + "Mehrzweckhalle Blaustein", "Blue Valley sports hall, 2 Sports Ground Road", ), + address: Some(Venue { + street: t("Am Sportplatz 2", ""), + postal_code: t("89134", ""), + city: t("Blaustein", ""), + country: "DE", + }), contact: "skibasar@example.org", services: &["Parkplatz", "Skiservice", "Getränke"], visibility: "public", @@ -1096,9 +1127,15 @@ async fn flea_market(demo: &mut Demo<'_>, people: &People) -> anyhow::Result<()> "Flea market in the courtyard of the community centre: household goods, furniture, electronics, bikes and clothes. Coffee and waffles from the neighbourhood café.", ), location: t( - "Stadtteiltreff Südstadt, Gartenweg 12", + "Stadtteiltreff Südstadt", "Southside community centre, 12 Garden Lane", ), + address: Some(Venue { + street: t("Gartenweg 12", ""), + postal_code: t("89077", ""), + city: t("Ulm", ""), + country: "DE", + }), contact: "suedstadt@example.org", services: &["Gastronomie"], visibility: "public", @@ -1114,6 +1151,8 @@ async fn flea_market(demo: &mut Demo<'_>, people: &People) -> anyhow::Result<()> "priceOffers": true, "minimumPrice": true, "questions": true, + // Only the QR code: sellers bring the labels of their last flea market + "labelMark": "none", }), }, true, @@ -1290,6 +1329,12 @@ async fn book_market(demo: &mut Demo<'_>, people: &People) -> anyhow::Result<()> "Second-hand books for a good cause: novels, non-fiction and children's books. Proceeds go to reading programmes.", ), location: t("Stadtbibliothek, Foyer", "City library, foyer"), + address: Some(Venue { + street: t("Kirchstraße 12", "Kirchstraße 12"), + postal_code: t("6900", "6900"), + city: t("Bregenz", "Bregenz"), + country: "AT", + }), contact: "bibliothek@example.org", services: &["Getränke"], visibility: "public", @@ -1354,6 +1399,7 @@ async fn other_events(demo: &mut Demo<'_>, people: &People) -> anyhow::Result<() title, description, location, + address: None, contact: "kontakt@example.org", services: &[], visibility: "public", @@ -1431,7 +1477,7 @@ async fn other_events(demo: &mut Demo<'_>, people: &People) -> anyhow::Result<() vendor_limit: Some(3), visibility: "logged-in", categories: &[Cat::Clothing, Cat::Shoes], - features: json!({ "discounts": false, "labelFormat": "small" }), + features: json!({ "discounts": false, "labelFormat": "small", "labelMark": "universal" }), ..plan( sabine, t("Kleiderbasar Gemeindehaus", "Parish Hall Clothes Sale"), diff --git a/backend/tests/api/demo.rs b/backend/tests/api/demo.rs index 2db9d361..73321117 100644 --- a/backend/tests/api/demo.rs +++ b/backend/tests/api/demo.rs @@ -157,6 +157,61 @@ async fn bazaars_in_every_state(db: PgPool) { // The views of organizers, sellers and admins work on the data let kids = event_id(&db, "Kinderbasar Kita Sonnenschein").await; + // Universal labels: the seller's lasting code instead of the number of this bazaar + let item: String = sqlx::query_scalar( + "SELECT p.id::text FROM products p + JOIN event_products ep ON ep.product_id = p.id + JOIN events e ON e.id = ep.event_id + JOIN users u ON u.id = p.vendor_id + WHERE e.title = 'Kinderbasar Kita Sonnenschein' AND u.email = 'anna.schmidt@example.org' + LIMIT 1", + ) + .fetch_one(&db) + .await + .unwrap(); + let labels = ok( + &app, + "labels.getLabelData", + json!({ "productIds": [item], "eventId": kids }), + Some(&seller), + ) + .await; + assert_eq!(labels["format"], "small"); + assert!(labels["labels"][0]["sortCode"].is_number()); + assert!(labels["labels"][0].get("sellerNumber").is_none()); + let vendors = ok( + &app, + "eventRoles.getVendorsForEvent", + json!({ "eventId": kids }), + Some(&organizer), + ) + .await; + assert!( + vendors + .as_array() + .unwrap() + .iter() + .any(|vendor| vendor["sortCode"].is_number()) + ); + // The address form: venue name and address apart, also outside of Germany + assert_eq!( + count( + &db, + "SELECT count(*) FROM events WHERE title = 'Kinderbasar Kita Sonnenschein' + AND location = 'Kita Sonnenschein, Turnraum' AND street = 'Lindenstraße 4' + AND postal_code = '89073' AND city = 'Ulm'" + ) + .await, + 1 + ); + assert_eq!( + count( + &db, + "SELECT count(*) FROM events WHERE country = 'AT' AND city = 'Bregenz'" + ) + .await, + 1 + ); let event = json!({ "eventId": kids }); let summary = ok( &app, From 66fc7943439b148bc4745c4e3aecc76fc0a724c5 Mon Sep 17 00:00:00 2001 From: Ivo Zeitz Date: Mon, 2 Nov 2026 21:36:49 +0100 Subject: [PATCH 06/14] feat(marketing): explain universal labels on the public pages The features page shows example labels and links to the guide, the pricing FAQ answers what a universal label is, and the short texts name the option. Co-Authored-By: Claude Opus 5.5 --- src/locales/de/company.json | 31 ++++++- src/locales/de/landing.json | 2 +- src/locales/de/organizer.json | 2 +- src/locales/en/company.json | 31 ++++++- src/locales/en/landing.json | 2 +- src/locales/en/organizer.json | 2 +- src/pages/public/company/FeaturesPage.tsx | 3 + src/pages/public/company/PricingPage.tsx | 2 +- .../components/UniversalLabelSection.tsx | 91 +++++++++++++++++++ 9 files changed, 157 insertions(+), 9 deletions(-) create mode 100644 src/pages/public/company/components/UniversalLabelSection.tsx diff --git a/src/locales/de/company.json b/src/locales/de/company.json index 824565f7..7263f1eb 100644 --- a/src/locales/de/company.json +++ b/src/locales/de/company.json @@ -44,6 +44,29 @@ "text": "App und E-Mails gibt es auf Deutsch und Englisch. Jeder bekommt Mails in seiner Sprache." } }, + "universalLabel": { + "eyebrow": "Universal-Etikett", + "title": "Zurücksortieren, ohne zu lesen", + "text": "Bei Kinder- und Kleiderbasaren müssen am Ende Hunderte kleine Teile zurück zu ihren Verkäufern. Dabei hilft ein Zeichen aus Ziffer, Farben und Symbolen, das jeder Verkäufer behält.", + "example": "Beispiel für drei Etiketten eines Verkäufers mit demselben Sortierzeichen", + "exampleItems": ["Body mit Bären", "Regenjacke", "Gummistiefel"], + "steps": { + "sort": { + "title": "Auf einen Blick sortieren", + "text": "Helfer legen die Ware erst nach der großen Ziffer auf Stapel und dann nach Farben und Symbolen in die Kiste des Verkäufers. Die Sortierblätter für die Kisten druckt BazarPro." + }, + "reuse": { + "title": "Beim nächsten Basar wiederverwenden", + "text": "Das Zeichen bleibt beim Verkäufer. Unverkaufte Teile behalten ihr Etikett, wenn auch der nächste Basar Universal-Etiketten nutzt." + }, + "print": { + "title": "Auf jedem Drucker", + "text": "Jede Farbe hat ihr eigenes Symbol, deshalb klappt es auch im Schwarz-Weiß-Druck und für farbenblinde Helfer." + } + }, + "default": "Bei den Vorlagen für Kinder- und Kleiderbasare schon eingestellt. Für wenige große Artikel wie Fahrräder bleibt die Verkäufernummer die bessere Wahl.", + "guide": "So funktioniert das Universal-Etikett" + }, "useCases": { "eyebrow": "Einsatzbereiche", "title": "Für jeden Second-Hand-Basar", @@ -53,7 +76,7 @@ "bazaarTypes": { "kids": { "title": "Kinderkleiderbasar", - "text": "Kleiderbasar, Kinderbasar oder Nummernbasar: viele kleine Teile, kleine Etiketten, Fotos freiwillig." + "text": "Kleiderbasar, Kinderbasar oder Nummernbasar: viele kleine Teile, Universal-Etiketten zum Wiederverwenden, Fotos freiwillig." }, "bikes": { "title": "Fahrradbörse", @@ -80,7 +103,7 @@ "wizard": "Assistent zum Anlegen mit Vorlagen für Fahrradbörse, Kinderbasar und Flohmarkt", "registration": "Online-Anmeldung von Verkäufern mit Zugangscode und Teilnehmerlimit", "listing": "Artikel mit Foto und Preis online erfassen", - "labels": "QR-Code-Etiketten als PDF, groß oder klein, mit Verkäufernummer", + "labels": "QR-Code-Etiketten als PDF, groß oder klein, mit Verkäufernummer oder als wiederverwendbares Universal-Etikett", "scan": "Warenannahme und Kasse per Smartphone-Scan", "cart": "Kasse mit Warenkorb, per Handykamera oder Hand-Scanner", "offline": "Offline-Kasse in der App: verkauft ohne Internet und bucht später nach", @@ -216,6 +239,10 @@ "question": "Brauche ich eine Kasse oder einen Scanner?", "answer": "Nein. Warenannahme und Verkauf laufen im Browser über die Kamera eines Smartphones oder Tablets. Einen Hand-Scanner kannst du an der Kasse zusätzlich nutzen. Etiketten druckst du auf normalem Papier." }, + "universalLabels": { + "question": "Was ist ein Universal-Etikett?", + "answer": "Ein kleines Etikett, das statt der Verkäufernummer ein festes Zeichen des Verkäufers aus Ziffer, Farben und Symbolen trägt. Helfer sortieren unverkaufte Ware danach zurück, ohne zu lesen. Unverkaufte Teile behalten ihr Etikett beim nächsten Basar mit Universal-Etiketten, und es funktioniert auch im Schwarz-Weiß-Druck." + }, "selfHost": { "question": "Kann ich BazarPro auf meinem eigenen Server betreiben?", "answer": "Ja. BazarPro ist Open Source unter MIT-Lizenz. Mit Docker Compose läuft es auf einem eigenen Server – die Anleitung steht in der Dokumentation unter docs.bazarpro.de." diff --git a/src/locales/de/landing.json b/src/locales/de/landing.json index 17d4629b..b7e4a7b8 100644 --- a/src/locales/de/landing.json +++ b/src/locales/de/landing.json @@ -18,7 +18,7 @@ }, "printer": { "title": "Etiketten als PDF", - "text": "Groß oder klein, mit Verkäufernummer – einzeln oder alle auf einmal." + "text": "Groß oder klein, mit Verkäufernummer oder als Universal-Etikett zum Wiederverwenden – einzeln oder alle auf einmal." }, "badgePercent": { "title": "Rabatte", diff --git a/src/locales/de/organizer.json b/src/locales/de/organizer.json index 5ed54778..04cfa5f8 100644 --- a/src/locales/de/organizer.json +++ b/src/locales/de/organizer.json @@ -913,7 +913,7 @@ "clothingBazaar": { "title": "Kleider- & Second-Hand-Basar", "text": "Damen-, Herren- oder Familienkleidung, Schuhe und Haushalt – oder ein klassischer Flohmarkt.", - "highlights": ["Preisvorschläge", "Fragen an Verkäufer", "Rabatte"], + "highlights": ["Universal-Etiketten", "Preisvorschläge", "Fragen an Verkäufer"], "exampleTitle": "Second-Hand-Basar", "exampleItems": ["Jacke, Gr. 38", "Lederstiefel, Gr. 39", "Handtasche, Leder"] }, diff --git a/src/locales/en/company.json b/src/locales/en/company.json index dd7c0d6d..4afc655e 100644 --- a/src/locales/en/company.json +++ b/src/locales/en/company.json @@ -44,6 +44,29 @@ "text": "The app and its emails are available in German and English. Everyone gets emails in their own language." } }, + "universalLabel": { + "eyebrow": "Universal label", + "title": "Sort items back without reading", + "text": "At kids' and clothing bazaars, hundreds of small items have to go back to their sellers at the end. A mark made of a digit, colors and symbols, which each seller keeps, makes this easier.", + "example": "Example of three labels from one seller with the same sorting mark", + "exampleItems": ["Bodysuit with bears", "Rain jacket", "Rubber boots"], + "steps": { + "sort": { + "title": "Sort at a glance", + "text": "Helpers pile the items by the large digit first, then put them into the seller's basket by colors and symbols. BazarPro prints the sorting sheets for the baskets." + }, + "reuse": { + "title": "Reuse at the next bazaar", + "text": "The mark stays with the seller. Unsold items keep their label if the next bazaar uses universal labels too." + }, + "print": { + "title": "On any printer", + "text": "Every color has its own symbol, so it also works in black and white and for color-blind helpers." + } + }, + "default": "Already set in the templates for kids' and clothing bazaars. For a few large items such as bikes, the seller number remains the better choice.", + "guide": "How the universal label works" + }, "useCases": { "eyebrow": "Use cases", "title": "For every second-hand bazaar", @@ -53,7 +76,7 @@ "bazaarTypes": { "kids": { "title": "Children's clothing bazaar", - "text": "Clothing, kids' or numbered bazaar: many small items, small labels, photos optional." + "text": "Clothing, kids' or numbered bazaar: many small items, reusable universal labels, photos optional." }, "bikes": { "title": "Bike sale", @@ -80,7 +103,7 @@ "wizard": "Creation wizard with presets for bike sales, kids' bazaars and flea markets", "registration": "Online seller registration with access code and participant limit", "listing": "Enter items online with photo and price", - "labels": "QR code labels as PDF, large or small, with seller number", + "labels": "QR code labels as PDF, large or small, with seller number or as a reusable universal label", "scan": "Drop-off and checkout by smartphone scan", "cart": "Checkout with a cart, by phone camera or hand scanner", "offline": "Offline checkout in the app: sells without internet and books the sales later", @@ -216,6 +239,10 @@ "question": "Do I need a till or a scanner?", "answer": "No. Drop-off and sales run in the browser using the camera of a smartphone or tablet. You can also use a hand scanner at the checkout. You print labels on regular paper." }, + "universalLabels": { + "question": "What is a universal label?", + "answer": "A small label that carries a seller's lasting mark made of a digit, colors and symbols instead of the seller number. Helpers sort unsold items back by it without reading. Unsold items keep their label at the next bazaar with universal labels, and it also works in black and white." + }, "selfHost": { "question": "Can I run BazarPro on my own server?", "answer": "Yes. BazarPro is open source under the MIT license. With Docker Compose it runs on your own server – the guide is in the documentation at docs.bazarpro.de." diff --git a/src/locales/en/landing.json b/src/locales/en/landing.json index 286e8ef8..97adf42b 100644 --- a/src/locales/en/landing.json +++ b/src/locales/en/landing.json @@ -18,7 +18,7 @@ }, "printer": { "title": "Labels as PDF", - "text": "Large or small, with your seller number – one by one or all at once." + "text": "Large or small, with your seller number or as a reusable universal label – one by one or all at once." }, "badgePercent": { "title": "Discounts", diff --git a/src/locales/en/organizer.json b/src/locales/en/organizer.json index bc006076..bd0dbc0b 100644 --- a/src/locales/en/organizer.json +++ b/src/locales/en/organizer.json @@ -909,7 +909,7 @@ "clothingBazaar": { "title": "Clothing & second-hand bazaar", "text": "Women's, men's or family clothing, shoes and household goods – or a classic flea market.", - "highlights": ["Price offers", "Questions to sellers", "Discounts"], + "highlights": ["Universal labels", "Price offers", "Questions to sellers"], "exampleTitle": "Second-hand bazaar", "exampleItems": ["Jacket, size 38", "Leather boots, size 39", "Leather handbag"] }, diff --git a/src/pages/public/company/FeaturesPage.tsx b/src/pages/public/company/FeaturesPage.tsx index e7cddb4f..f3fa1523 100644 --- a/src/pages/public/company/FeaturesPage.tsx +++ b/src/pages/public/company/FeaturesPage.tsx @@ -27,6 +27,7 @@ import { LandingCTA } from '../landing/components/LandingCTA'; import { LandingFeatures } from '../landing/components/LandingFeatures'; import { MarketingHero, SectionHeading } from './components/MarketingHero'; import { OpenSourceSection } from './components/OpenSourceSection'; +import { UniversalLabelSection } from './components/UniversalLabelSection'; import { useStartActions } from './components/useStartActions'; import { Trans, useTranslation } from 'react-i18next'; @@ -186,6 +187,8 @@ export function FeaturesPage() { + + {/* Use cases */}
diff --git a/src/pages/public/company/PricingPage.tsx b/src/pages/public/company/PricingPage.tsx index 011d7d66..4ea30193 100644 --- a/src/pages/public/company/PricingPage.tsx +++ b/src/pages/public/company/PricingPage.tsx @@ -15,7 +15,7 @@ const HOSTED_FEATURES = ['unlimited', 'labels', 'settlement', 'instant'] as cons const SELFHOSTED_FEATURES = ['allFeatures', 'ownData', 'ownDomain', 'docker'] as const; -const FAQ = ['free', 'useCases', 'commission', 'hardware', 'selfHost'] as const; +const FAQ = ['free', 'useCases', 'commission', 'hardware', 'universalLabels', 'selfHost'] as const; export function PricingPage() { const { isAuthenticated, goToOrganizer, goToSeller } = useStartActions(); diff --git a/src/pages/public/company/components/UniversalLabelSection.tsx b/src/pages/public/company/components/UniversalLabelSection.tsx new file mode 100644 index 00000000..2a05c159 --- /dev/null +++ b/src/pages/public/company/components/UniversalLabelSection.tsx @@ -0,0 +1,91 @@ +import { ArrowRight, Printer, Recycle, ScanEye, type LucideIcon } from 'lucide-react'; +import { QRCodeSVG } from 'qrcode.react'; +import { useTranslation } from 'react-i18next'; +import { SortMarkBadge } from '../../../../components/sellers/SortMarkBadge'; +import { docsUrl } from '../../../../lib/links'; +import { SectionHeading } from './MarketingHero'; + +/** Any code gives a realistic mark; this one has three clearly different fields. */ +const EXAMPLE_SORT_CODE = 175; + +const STEPS: { icon: LucideIcon; id: 'sort' | 'reuse' | 'print' }[] = [ + { icon: ScanEye, id: 'sort' }, + { icon: Recycle, id: 'reuse' }, + { icon: Printer, id: 'print' }, +]; + +/** Explains universal labels with labels as they are printed, in every theme on white. */ +export function UniversalLabelSection() { + const { t, i18n } = useTranslation('company'); + const items = t('featuresPage.universalLabel.exampleItems', { + returnObjects: true, + }) as string[]; + + return ( +
+
+ + {t('featuresPage.universalLabel.text')} + +
+
+ {items.map((title) => ( +
+ +
+ +

{title}

+
+
+ ))} +
+
+ {STEPS.map(({ icon: Icon, id }) => ( +
+ + + +
+

+ {t(`featuresPage.universalLabel.steps.${id}.title`)} +

+

+ {t(`featuresPage.universalLabel.steps.${id}.text`)} +

+
+
+ ))} +

+ {t('featuresPage.universalLabel.default')} +

+ + {t('featuresPage.universalLabel.guide')} + + +
+
+
+
+ ); +} From 89d84a45978d22005d13ea6e1d6cc1c5db34036c Mon Sep 17 00:00:00 2001 From: Ivo Zeitz Date: Tue, 3 Nov 2026 04:51:32 +0100 Subject: [PATCH 07/14] feat(account): country selector in the profile and the join wizard Profiles now store country codes like events do, and the postal code is checked by the chosen country. A migration converts common spellings; other text stays selectable and is shown as typed. Co-Authored-By: Claude Opus 5.5 --- backend/migrations/0018_user_country_code.sql | 13 +++++ backend/src/demo/catalog.rs | 6 +-- backend/src/demo/core.rs | 2 +- backend/src/modules/users.rs | 2 +- backend/tests/api/users.rs | 34 +++++++++++++ .../ValidateProfileInformation.test.tsx | 50 +++++++++++++++++++ .../events/ValidateProfileInformation.tsx | 32 ++++++------ src/components/sellers/SellerIdCheck.tsx | 3 +- src/components/ui/country-select.tsx | 34 +++++++++++++ src/i18n/countries.test.ts | 20 ++++++++ src/i18n/countries.ts | 11 ++++ src/lib/proofOfOffersPdf.ts | 4 +- src/locales/de/account.json | 4 +- src/locales/de/common.json | 7 +++ src/locales/de/organizer.json | 7 --- src/locales/en/account.json | 4 +- src/locales/en/common.json | 7 +++ src/locales/en/organizer.json | 7 --- src/pages/account/components/ProfileCard.tsx | 22 ++++---- src/pages/organizer/events/EditEventForm.tsx | 6 +-- .../events/components/EditEventBasicInfo.tsx | 15 +----- .../dashboard/ProductManagementPage.tsx | 5 +- src/shared/constants.ts | 15 ++++-- src/tests/auth/profile.spec.ts | 4 +- 24 files changed, 240 insertions(+), 74 deletions(-) create mode 100644 backend/migrations/0018_user_country_code.sql create mode 100644 src/components/events/ValidateProfileInformation.test.tsx create mode 100644 src/components/ui/country-select.tsx create mode 100644 src/i18n/countries.test.ts create mode 100644 src/i18n/countries.ts diff --git a/backend/migrations/0018_user_country_code.sql b/backend/migrations/0018_user_country_code.sql new file mode 100644 index 00000000..5e138199 --- /dev/null +++ b/backend/migrations/0018_user_country_code.sql @@ -0,0 +1,13 @@ +-- Profile countries were free text; now they are ISO 3166-1 alpha-2 codes like those of events. +-- Other values stay as they are and keep being shown as typed. Snapshots of sellers keep what +-- was true when they were taken. +UPDATE users SET country = CASE + WHEN lower(trim(country)) IN ('de', 'd', 'deu', 'ger', 'brd', 'deutschland', 'germany') THEN 'DE' + -- translate: lower() leaves Ö alone in databases with the C locale + WHEN translate(lower(trim(country)), 'Ö', 'ö') IN ('at', 'a', 'aut', 'österreich', 'oesterreich', 'austria') THEN 'AT' + WHEN lower(trim(country)) IN ('ch', 'che', 'schweiz', 'switzerland', 'suisse', 'svizzera') THEN 'CH' + WHEN lower(trim(country)) IN ('li', 'lie', 'liechtenstein') THEN 'LI' + WHEN lower(trim(country)) IN ('lu', 'lux', 'luxemburg', 'luxembourg') THEN 'LU' + ELSE country + END +WHERE country IS NOT NULL; diff --git a/backend/src/demo/catalog.rs b/backend/src/demo/catalog.rs index 670a1bee..7e379f81 100644 --- a/backend/src/demo/catalog.rs +++ b/backend/src/demo/catalog.rs @@ -211,17 +211,17 @@ pub fn city(locale: Locale, index: usize) -> City { City { zip: "89073", name: "Ulm", - country: "Deutschland", + country: "DE", }, City { zip: "89231", name: "Neu-Ulm", - country: "Deutschland", + country: "DE", }, City { zip: "89077", name: "Ulm", - country: "Deutschland", + country: "DE", }, ]; const EN: [City; 3] = [ diff --git a/backend/src/demo/core.rs b/backend/src/demo/core.rs index d96fefcd..1f66e96b 100644 --- a/backend/src/demo/core.rs +++ b/backend/src/demo/core.rs @@ -653,7 +653,7 @@ pub async fn insert_users(seeder: &Seeder, ctx: &mut Ctx) -> AppResult AppResult String { + sqlx::query("UPDATE users SET country = $2 WHERE id = $1") + .bind(user) + .bind(stored) + .execute(&db) + .await + .unwrap(); + sqlx::raw_sql(include_str!("../../migrations/0018_user_country_code.sql")) + .execute(&db) + .await + .unwrap(); + sqlx::query_scalar("SELECT country FROM users WHERE id = $1") + .bind(user) + .fetch_one(&db) + .await + .unwrap() + }; + for (stored, code) in [ + ("Deutschland", "DE"), + (" germany ", "DE"), + ("de", "DE"), + ("Österreich", "AT"), + ("ÖSTERREICH", "AT"), + ("Schweiz", "CH"), + ("Luxembourg", "LU"), + ("United Kingdom", "United Kingdom"), + ] { + assert_eq!(country(stored).await, code); + } +} diff --git a/src/components/events/ValidateProfileInformation.test.tsx b/src/components/events/ValidateProfileInformation.test.tsx new file mode 100644 index 00000000..d21bcd07 --- /dev/null +++ b/src/components/events/ValidateProfileInformation.test.tsx @@ -0,0 +1,50 @@ +import { fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import type { Doc } from '../../lib/api/types'; +import { ValidateProfileInformation } from './ValidateProfileInformation'; + +const update = vi.hoisted(() => vi.fn(async () => undefined)); +vi.mock('../../lib/api/react', () => ({ useMutation: () => update })); + +const fill = (label: string, value: string) => + fireEvent.change(screen.getByLabelText(label), { target: { value } }); + +function renderAddressStep(country?: string) { + render( + } + /> + ); + fill('Straße und Hausnummer', 'Kirchstraße 12'); + fill('Ort', 'Bregenz'); +} + +describe('ValidateProfileInformation', () => { + beforeEach(() => update.mockClear()); + + it('preselects Germany and checks the postal code by the chosen country', async () => { + renderAddressStep(); + expect(screen.getByLabelText('Land')).toHaveValue('DE'); + fill('Postleitzahl', '6900'); + fireEvent.click(screen.getByRole('button', { name: 'Adresse speichern' })); + expect(await screen.findByText('Ungültige Postleitzahl für dieses Land')).toBeVisible(); + expect(update).not.toHaveBeenCalled(); + + fill('Land', 'AT'); + fireEvent.click(screen.getByRole('button', { name: 'Adresse speichern' })); + await waitFor(() => + expect(update).toHaveBeenCalledWith({ + street: 'Kirchstraße 12', + city: 'Bregenz', + zipCode: '6900', + country: 'AT', + }) + ); + }); + + it('keeps a country typed into an older profile', () => { + renderAddressStep('United Kingdom'); + expect(screen.getByLabelText('Land')).toHaveValue('United Kingdom'); + }); +}); diff --git a/src/components/events/ValidateProfileInformation.tsx b/src/components/events/ValidateProfileInformation.tsx index 094ffc14..1d1dc5a3 100644 --- a/src/components/events/ValidateProfileInformation.tsx +++ b/src/components/events/ValidateProfileInformation.tsx @@ -2,6 +2,7 @@ import { useEffect } from 'react'; import { Label } from '../ui/label'; import { Input } from '../ui/input'; import { Button } from '../ui/button'; +import { CountrySelect } from '../ui/country-select'; import { useMutation } from '../../lib/api/react'; import { api } from '../../lib/api/functions'; import type { Doc } from '../../lib/api/types'; @@ -11,6 +12,7 @@ import { useForm } from 'react-hook-form'; import { getUserFacingErrorMessage } from '../../lib/errors'; import { useTranslation } from 'react-i18next'; import i18n from '../../i18n'; +import { isPostalCodeValid } from '../../shared/constants'; /** Error text in the current language, read when validating */ const msg = (key: string, ns = 'events') => ({ @@ -27,10 +29,7 @@ const profileSchema = z.object({ .regex(/^\+?[0-9\s\-()]{7,20}$/, msg('profile.invalidPhone', 'account')), street: z.string().trim().min(1, msg('profile.streetRequired')), city: z.string().trim().min(1, msg('profile.cityRequired')), - zipCode: z - .string() - .trim() - .regex(/^\d{5}$/, msg('profile.invalidZip', 'account')), + zipCode: z.string().trim().min(1, msg('profile.invalidZip', 'account')), country: z.string().trim().min(1, msg('profile.countryRequired')), }); @@ -40,12 +39,17 @@ const basicProfileSchema = profileSchema.pick({ phone: true, }); -const addressProfileSchema = profileSchema.pick({ - street: true, - city: true, - zipCode: true, - country: true, -}); +const addressProfileSchema = profileSchema + .pick({ + street: true, + city: true, + zipCode: true, + country: true, + }) + .refine((address) => isPostalCodeValid(address.zipCode, address.country), { + path: ['zipCode'], + ...msg('profile.invalidZip', 'account'), + }); type ProfileFormData = z.infer; type BasicProfileFormData = z.infer; @@ -93,7 +97,7 @@ export function ValidateProfileInformation({ street: user.street ?? '', city: user.city ?? '', zipCode: user.zipCode ?? '', - country: user.country ?? '', + country: user.country || 'DE', }); }, [user, isDirty, reset]); @@ -259,11 +263,7 @@ export function ValidateProfileInformation({
- + {errors.country && (

{errors.country.message}

)} diff --git a/src/components/sellers/SellerIdCheck.tsx b/src/components/sellers/SellerIdCheck.tsx index 67cb5afb..fe4cba74 100644 --- a/src/components/sellers/SellerIdCheck.tsx +++ b/src/components/sellers/SellerIdCheck.tsx @@ -2,6 +2,7 @@ import { IdCard } from 'lucide-react'; import { useTranslation } from 'react-i18next'; import { Alert, AlertDescription, AlertTitle } from '../ui/alert'; import type { VendorWithCalculations } from '../../lib/api/types'; +import { countryName } from '../../i18n/countries'; /** * Bazaars with fixedSellerData: name and address as they will be recorded with the first @@ -20,7 +21,7 @@ export function SellerIdCheck({ seller }: { seller: VendorWithCalculations }) { {name &&
{name}
} {seller.street &&
{seller.street}
} {place &&
{place}
} - {seller.country &&
{seller.country}
} + {seller.country &&
{countryName(seller.country)}
}

{t('products.idCheckText')}

diff --git a/src/components/ui/country-select.tsx b/src/components/ui/country-select.tsx new file mode 100644 index 00000000..3790e594 --- /dev/null +++ b/src/components/ui/country-select.tsx @@ -0,0 +1,34 @@ +import type { ComponentProps } from 'react'; +import { useTranslation } from 'react-i18next'; +import { isCountry } from '../../i18n/countries'; +import { COUNTRIES } from '../../shared/constants'; +import { cn } from '../utils'; + +interface CountrySelectProps extends ComponentProps<'select'> { + /** Value already saved: free text of an older profile stays selectable, not overwritten */ + saved?: string; + /** Adds a choice for no country, with this label */ + emptyLabel?: string; +} + +export function CountrySelect({ saved, emptyLabel, className, ...props }: CountrySelectProps) { + const { t } = useTranslation('common'); + return ( + + ); +} diff --git a/src/i18n/countries.test.ts b/src/i18n/countries.test.ts new file mode 100644 index 00000000..693cf9fc --- /dev/null +++ b/src/i18n/countries.test.ts @@ -0,0 +1,20 @@ +import { describe, expect, it } from 'vitest'; +import { isPostalCodeValid } from '../shared/constants'; +import { countryName } from './countries'; + +describe('countries', () => { + it('names known codes and leaves the free text of older profiles', () => { + expect(countryName('AT')).toBe('Österreich'); + expect(countryName('United Kingdom')).toBe('United Kingdom'); + }); + + it('checks postal codes by country', () => { + expect(isPostalCodeValid('89073', 'DE')).toBe(true); + expect(isPostalCodeValid('6900', 'DE')).toBe(false); + expect(isPostalCodeValid('6900', 'AT')).toBe(true); + expect(isPostalCodeValid('89073', 'AT')).toBe(false); + // No country counts as Germany, free text has no known format + expect(isPostalCodeValid('6900', '')).toBe(false); + expect(isPostalCodeValid('OX1 2JD', 'United Kingdom')).toBe(true); + }); +}); diff --git a/src/i18n/countries.ts b/src/i18n/countries.ts new file mode 100644 index 00000000..4c9a9ed1 --- /dev/null +++ b/src/i18n/countries.ts @@ -0,0 +1,11 @@ +import i18n from '.'; +import { COUNTRIES, type Country } from '../shared/constants'; + +export function isCountry(value: string | null | undefined): value is Country { + return COUNTRIES.some((code) => code === value); +} + +/** Name in the current language; older profiles and records may hold free text, shown as is. */ +export function countryName(value: string): string { + return isCountry(value) ? (i18n.t(`countries.${value}`, { ns: 'common' }) as string) : value; +} diff --git a/src/lib/proofOfOffersPdf.ts b/src/lib/proofOfOffersPdf.ts index 91165cb9..e3407ee9 100644 --- a/src/lib/proofOfOffersPdf.ts +++ b/src/lib/proofOfOffersPdf.ts @@ -2,6 +2,7 @@ import { jsPDF } from 'jspdf'; import type { ProofItem, ProofSeller } from './api/types'; import { formatPriceDE } from './utils'; import { categoryFieldText } from '../i18n/categoryFields'; +import { countryName } from '../i18n/countries'; import i18n from '../i18n'; import { dateLocale } from '../i18n/format'; import { saveFile, savePdf } from './saveFile'; @@ -36,7 +37,8 @@ export function sellerAddress( seller: Pick ): string { const city = [seller.zipCode, seller.city].filter(Boolean).join(' '); - return [seller.street, city, seller.country].filter(Boolean).join(', ') || '–'; + const country = seller.country && countryName(seller.country); + return [seller.street, city, country].filter(Boolean).join(', ') || '–'; } function contact(seller: ProofSeller): string { diff --git a/src/locales/de/account.json b/src/locales/de/account.json index c149a144..9fb7e84e 100644 --- a/src/locales/de/account.json +++ b/src/locales/de/account.json @@ -16,9 +16,9 @@ "city": "Ort", "cityPlaceholder": "Musterstadt", "country": "Land", - "countryPlaceholder": "Deutschland", + "countryNone": "Bitte wählen", "invalidPhone": "Ungültiges Telefonnummer-Format (z. B. +49 123 456789)", - "invalidZip": "Ungültige Postleitzahl (5 Ziffern erforderlich)", + "invalidZip": "Ungültige Postleitzahl für dieses Land", "save": "Profil aktualisieren", "saved": "Profil erfolgreich aktualisiert!", "saveFailed": "Fehler beim Aktualisieren des Profils.", diff --git a/src/locales/de/common.json b/src/locales/de/common.json index 443d5729..f3ddebec 100644 --- a/src/locales/de/common.json +++ b/src/locales/de/common.json @@ -1,4 +1,11 @@ { + "countries": { + "DE": "Deutschland", + "AT": "Österreich", + "CH": "Schweiz", + "LI": "Liechtenstein", + "LU": "Luxemburg" + }, "header": { "login": "Anmelden", "register": "Registrieren", diff --git a/src/locales/de/organizer.json b/src/locales/de/organizer.json index 04cfa5f8..27b91008 100644 --- a/src/locales/de/organizer.json +++ b/src/locales/de/organizer.json @@ -64,13 +64,6 @@ "postalCode": "PLZ", "city": "Ort", "country": "Land", - "countries": { - "DE": "Deutschland", - "AT": "Österreich", - "CH": "Schweiz", - "LI": "Liechtenstein", - "LU": "Luxemburg" - }, "start": "Startdatum *", "end": "Enddatum *" }, diff --git a/src/locales/en/account.json b/src/locales/en/account.json index 19a06890..f7f245ff 100644 --- a/src/locales/en/account.json +++ b/src/locales/en/account.json @@ -16,9 +16,9 @@ "city": "City", "cityPlaceholder": "Sample City", "country": "Country", - "countryPlaceholder": "Germany", + "countryNone": "Please choose", "invalidPhone": "Invalid phone number format (e.g. +49 123 456789)", - "invalidZip": "Invalid postal code (5 digits required)", + "invalidZip": "Invalid postal code for this country", "save": "Update profile", "saved": "Profile updated!", "saveFailed": "The profile could not be updated.", diff --git a/src/locales/en/common.json b/src/locales/en/common.json index f1b5e964..ec7b5189 100644 --- a/src/locales/en/common.json +++ b/src/locales/en/common.json @@ -1,4 +1,11 @@ { + "countries": { + "DE": "Germany", + "AT": "Austria", + "CH": "Switzerland", + "LI": "Liechtenstein", + "LU": "Luxembourg" + }, "header": { "login": "Log in", "register": "Sign up", diff --git a/src/locales/en/organizer.json b/src/locales/en/organizer.json index bd0dbc0b..4e1aca14 100644 --- a/src/locales/en/organizer.json +++ b/src/locales/en/organizer.json @@ -64,13 +64,6 @@ "postalCode": "Postal code", "city": "Town", "country": "Country", - "countries": { - "DE": "Germany", - "AT": "Austria", - "CH": "Switzerland", - "LI": "Liechtenstein", - "LU": "Luxembourg" - }, "start": "Start date *", "end": "End date *" }, diff --git a/src/pages/account/components/ProfileCard.tsx b/src/pages/account/components/ProfileCard.tsx index eaadc968..fea5b32d 100644 --- a/src/pages/account/components/ProfileCard.tsx +++ b/src/pages/account/components/ProfileCard.tsx @@ -5,6 +5,7 @@ import { z } from 'zod'; import { useMutation, useQuery } from '../../../lib/api/react'; import { api } from '../../../lib/api/functions'; import { Button } from '../../../components/ui/button'; +import { CountrySelect } from '../../../components/ui/country-select'; import { Input } from '../../../components/ui/input'; import { Label } from '../../../components/ui/label'; import { Separator } from '../../../components/ui/separator'; @@ -15,9 +16,10 @@ import { getUserFacingErrorMessage } from '../../../lib/errors'; import { useTranslation } from 'react-i18next'; import type { TFunction } from 'i18next'; import { Alert, AlertDescription } from '../../../components/ui/alert'; +import { isPostalCodeValid } from '../../../shared/constants'; function buildProfileSchema(t: TFunction<'account'>) { - return z.object({ + const schema = z.object({ firstName: z.string().optional(), lastName: z.string().optional(), phone: z @@ -28,14 +30,13 @@ function buildProfileSchema(t: TFunction<'account'>) { }), street: z.string().optional(), city: z.string().optional(), - zipCode: z - .string() - .optional() - .refine((val) => !val || /^\d{5}$/.test(val), { - message: t('profile.invalidZip'), - }), + zipCode: z.string().optional(), country: z.string().optional(), }); + return schema.refine(({ zipCode, country }) => !zipCode || isPostalCodeValid(zipCode, country), { + path: ['zipCode'], + message: t('profile.invalidZip'), + }); } type ProfileFormData = z.infer>; @@ -200,10 +201,11 @@ export function ProfileCard({ user }: ProfileCardProps) {
- {errors.country && ( diff --git a/src/pages/organizer/events/EditEventForm.tsx b/src/pages/organizer/events/EditEventForm.tsx index edb3fae9..a3d484e7 100644 --- a/src/pages/organizer/events/EditEventForm.tsx +++ b/src/pages/organizer/events/EditEventForm.tsx @@ -23,7 +23,7 @@ import { type StoredEventFeatures, } from '../../../shared/eventFeatures'; import { - EVENT_COUNTRIES, + COUNTRIES, EVENT_SERVICES, EVENT_VISIBILITY, POSTAL_CODE_PATTERNS, @@ -93,7 +93,7 @@ const buildEventSchema = ( street: z.string().max(200, zodMessage('form.addressTooLong', 'organizer')), postalCode: z.string().trim(), city: z.string().max(100, zodMessage('form.addressTooLong', 'organizer')), - country: z.enum(EVENT_COUNTRIES), + country: z.enum(COUNTRIES), }) .refine( (address) => @@ -320,7 +320,7 @@ function addressToForm(event: EventPlace | null | undefined): AddressFormData { const empty: AddressFormData = { street: '', postalCode: '', city: '', country: 'DE' }; if (!event) return empty; if (event.street || event.postalCode || event.city) { - const country = EVENT_COUNTRIES.find((code) => code === event.country) ?? 'DE'; + const country = COUNTRIES.find((code) => code === event.country) ?? 'DE'; return { street: event.street ?? '', postalCode: event.postalCode ?? '', diff --git a/src/pages/organizer/events/components/EditEventBasicInfo.tsx b/src/pages/organizer/events/components/EditEventBasicInfo.tsx index f48b4395..b505080f 100644 --- a/src/pages/organizer/events/components/EditEventBasicInfo.tsx +++ b/src/pages/organizer/events/components/EditEventBasicInfo.tsx @@ -8,7 +8,7 @@ import { ImageUpload } from '../../../../components/ui/ImageUpload'; import { SafeMarkdown } from '../../../../components/markdown/SafeMarkdown'; import { IMAGE_UPLOAD_MAX_HEIGHT, IMAGE_UPLOAD_MAX_WIDTH } from '../../../../lib/imageProcessing'; import { Trans, useTranslation } from 'react-i18next'; -import { EVENT_COUNTRIES } from '../../../../shared/constants'; +import { CountrySelect } from '../../../../components/ui/country-select'; interface EditEventBasicInfoProps { initialCoverImageUrl?: string | null; @@ -294,18 +294,7 @@ export function EditEventBasicInfo({ - +
{addressErrors && (

diff --git a/src/pages/organizer/events/dashboard/ProductManagementPage.tsx b/src/pages/organizer/events/dashboard/ProductManagementPage.tsx index 7ab18bb3..2f95247f 100644 --- a/src/pages/organizer/events/dashboard/ProductManagementPage.tsx +++ b/src/pages/organizer/events/dashboard/ProductManagementPage.tsx @@ -1,4 +1,5 @@ import { useDeferredValue, useEffect, useMemo, useState, useRef } from 'react'; +import { countryName } from '../../../../i18n/countries'; import { useApiClient, useMutation, useQuery } from '../../../../lib/api/react'; import { useNavigate, useParams, useLocation, useSearchParams } from 'react-router-dom'; import { api } from '../../../../lib/api/functions'; @@ -716,7 +717,9 @@ export function ProductManagementPage() { )} {selectedVendor.country && ( - {selectedVendor.country} + + {countryName(selectedVendor.country)} + )} diff --git a/src/shared/constants.ts b/src/shared/constants.ts index 6404ebfb..402bac93 100644 --- a/src/shared/constants.ts +++ b/src/shared/constants.ts @@ -192,15 +192,22 @@ export const LOCALE_NAMES: Record = { de: 'Deutsch', en: 'Englis */ export const MIN_PASSWORD_LENGTH = 10; -/** Countries of event addresses (ISO 3166-1 alpha-2); events without one are in Germany. */ -export const EVENT_COUNTRIES = ['DE', 'AT', 'CH', 'LI', 'LU'] as const; -export type EventCountry = (typeof EVENT_COUNTRIES)[number]; +/** Countries of addresses (ISO 3166-1 alpha-2); events without one are in Germany. */ +export const COUNTRIES = ['DE', 'AT', 'CH', 'LI', 'LU'] as const; +export type Country = (typeof COUNTRIES)[number]; /** Postal codes per country: five digits in Germany, four in the others. */ -export const POSTAL_CODE_PATTERNS: Record = { +export const POSTAL_CODE_PATTERNS: Record = { DE: /^\d{5}$/, AT: /^\d{4}$/, CH: /^\d{4}$/, LI: /^\d{4}$/, LU: /^(L-)?\d{4}$/i, }; + +/** No country counts as Germany; free text of older profiles has no known format. */ +export function isPostalCodeValid(postalCode: string, country: string | undefined): boolean { + if (!country) return POSTAL_CODE_PATTERNS.DE.test(postalCode); + const known = COUNTRIES.find((code) => code === country); + return !known || POSTAL_CODE_PATTERNS[known].test(postalCode); +} diff --git a/src/tests/auth/profile.spec.ts b/src/tests/auth/profile.spec.ts index 86331785..8d4cb219 100644 --- a/src/tests/auth/profile.spec.ts +++ b/src/tests/auth/profile.spec.ts @@ -26,7 +26,7 @@ test.describe('profile page', () => { await page.getByRole('button', { name: 'Profil aktualisieren' }).click(); await expect(page.getByText('Ungültiges Telefonnummer-Format')).toBeVisible(); - await expect(page.getByText('Ungültige Postleitzahl (5 Ziffern erforderlich)')).toBeVisible(); + await expect(page.getByText('Ungültige Postleitzahl für dieses Land')).toBeVisible(); await page.locator('#firstName').fill(firstName); await page.locator('#lastName').fill(lastName); @@ -34,7 +34,7 @@ test.describe('profile page', () => { await page.locator('#street').fill('Musterstraße 1'); await page.locator('#zipCode').fill('89073'); await page.locator('#city').fill('Ulm'); - await page.locator('#country').fill('Deutschland'); + await page.locator('#country').selectOption('DE'); await page.getByRole('button', { name: 'Profil aktualisieren' }).click(); await expect(page.getByText('Profil erfolgreich aktualisiert!')).toBeVisible(); From a3c4edcacd5faa9a1ae5e7beb7edba82a1252a9a Mon Sep 17 00:00:00 2001 From: Ivo Zeitz Date: Wed, 4 Nov 2026 16:44:19 +0100 Subject: [PATCH 08/14] feat(labels): one QR component, lasting sort marks without the seller number Labels no longer carry the seller number: a bazaar prints the seller's lasting mark or only the QR code, in both formats. The mark is a pile (color, shape, digit) and two basket marks from 00 to 99, whose tens give the color and ones the shape. That makes 100,000 codes, then a letter is added, so codes never run out or repeat. Only sellers get a code, with their first item or bazaar, and no code is given out again. If two sellers of a bazaar differ by the letter only, the seller sees a warning, and the team sees it in the list and on the sorting sheets. All QR codes come from one module and component, qrcode.react is gone. All label exports go through one dialog, which always asks for the first free place (#238). Co-Authored-By: Claude Opus 5.5 --- .../migrations/0020_sort_code_for_sellers.sql | 32 +++ backend/src/modules/event_roles.rs | 6 +- backend/src/modules/events.rs | 2 +- backend/src/modules/features.rs | 18 +- backend/src/modules/labels.rs | 86 +++++-- backend/tests/api/reminders.rs | 104 ++++++++- package-lock.json | 10 - package.json | 1 - .../products}/LabelPrintDialog.test.tsx | 42 +++- src/components/products/LabelPrintDialog.tsx | 209 ++++++++++++++++++ .../products/ProductQRCodeDialog.test.tsx | 22 +- .../products/ProductQRCodeDialog.tsx | 37 +--- src/components/sellers/SortMarkBadge.tsx | 126 ++++++++--- src/components/ui/QrCode.tsx | 28 +++ src/components/ui/country-select.tsx | 2 +- src/lib/api/types.ts | 25 ++- src/lib/eventTypes.test.ts | 10 +- src/lib/productQRCodePdf.test.ts | 14 +- src/lib/productQRCodePdf.ts | 48 ++-- src/lib/{labelQr.test.ts => qrCode.test.ts} | 2 +- src/lib/{labelQr.ts => qrCode.ts} | 42 ++-- src/lib/sortMarkPdf.ts | 117 +++++----- src/lib/sortSheetsPdf.ts | 17 +- src/locales/de/common.json | 2 +- src/locales/de/company.json | 18 +- src/locales/de/landing.json | 2 +- src/locales/de/organizer.json | 16 +- src/locales/de/seller.json | 9 +- src/locales/en/common.json | 2 +- src/locales/en/company.json | 18 +- src/locales/en/organizer.json | 16 +- src/locales/en/seller.json | 9 +- .../account/components/DigitalIdCard.test.tsx | 4 +- .../account/components/DigitalIdCard.tsx | 8 +- .../events/components/EditEventFeatures.tsx | 19 +- .../components/wizard/WizardPreviews.tsx | 30 +-- .../dashboard/ProductManagementPage.tsx | 24 +- .../events/dashboard/SellerManagementPage.tsx | 19 +- .../components/EventSettingsSummary.tsx | 10 +- .../components/UniversalLabelSection.tsx | 16 +- .../landing/components/demo/Illustrations.tsx | 10 +- .../components/demo/ProcessVisuals.tsx | 4 +- src/pages/seller/products/MyProductsPage.tsx | 63 +++--- .../products/components/LabelPrintDialog.tsx | 182 --------------- src/shared/constants.ts | 4 +- src/shared/eventFeatures.ts | 17 +- src/shared/sortCode.test.ts | 78 +++++-- src/shared/sortCode.ts | 194 +++++++++++----- 48 files changed, 1075 insertions(+), 699 deletions(-) create mode 100644 backend/migrations/0020_sort_code_for_sellers.sql rename src/{pages/seller/products/components => components/products}/LabelPrintDialog.test.tsx (72%) create mode 100644 src/components/products/LabelPrintDialog.tsx create mode 100644 src/components/ui/QrCode.tsx rename src/lib/{labelQr.test.ts => qrCode.test.ts} (98%) rename src/lib/{labelQr.ts => qrCode.ts} (65%) delete mode 100644 src/pages/seller/products/components/LabelPrintDialog.tsx diff --git a/backend/migrations/0020_sort_code_for_sellers.sql b/backend/migrations/0020_sort_code_for_sellers.sql new file mode 100644 index 00000000..bfebe015 --- /dev/null +++ b/backend/migrations/0020_sort_code_for_sellers.sql @@ -0,0 +1,32 @@ +-- Sorting codes are for sellers. A buyer without items must not use up one of the codes +-- that need no extra letter, so a code is given with the first item or bazaar. Codes are +-- never given out again, not even after an account is deleted: printed labels may still +-- carry them. +ALTER TABLE users ALTER COLUMN sort_code DROP IDENTITY; +ALTER TABLE users ALTER COLUMN sort_code DROP NOT NULL; +UPDATE users SET sort_code = NULL; + +CREATE SEQUENCE users_sort_code_seq OWNED BY users.sort_code; + +WITH sellers AS ( + SELECT id FROM users u + WHERE EXISTS (SELECT 1 FROM products p WHERE p.vendor_id = u.id) + OR EXISTS (SELECT 1 FROM event_sellers s WHERE s.user_id = u.id) + ORDER BY created_at, id +), numbered AS ( + SELECT id, nextval('users_sort_code_seq')::integer AS code FROM sellers +) +UPDATE users u SET sort_code = n.code FROM numbered n WHERE n.id = u.id; + +CREATE FUNCTION give_sort_code() RETURNS trigger LANGUAGE plpgsql AS $$ +BEGIN + UPDATE users SET sort_code = nextval('users_sort_code_seq') + WHERE id = (to_jsonb(NEW) ->> TG_ARGV[0])::uuid AND sort_code IS NULL; + RETURN NULL; +END; +$$; + +CREATE TRIGGER products_give_sort_code AFTER INSERT OR UPDATE OF vendor_id ON products + FOR EACH ROW EXECUTE FUNCTION give_sort_code('vendor_id'); +CREATE TRIGGER event_sellers_give_sort_code AFTER INSERT ON event_sellers + FOR EACH ROW EXECUTE FUNCTION give_sort_code('user_id'); diff --git a/backend/src/modules/event_roles.rs b/backend/src/modules/event_roles.rs index 91e24848..52b8ffc7 100644 --- a/backend/src/modules/event_roles.rs +++ b/backend/src/modules/event_roles.rs @@ -11,6 +11,7 @@ use uuid::Uuid; use super::access::is_platform_admin; use super::docs::{self, User}; use super::features::label_mark; +use super::labels::seller_sort_code; use super::sales::{self, IntakeFee}; use super::seller_records::{keeps_seller_record, with_snapshot}; use crate::error::{AppError, AppResult}; @@ -333,10 +334,7 @@ pub async fn load_vendors_with_calculations( accepted.get(&vendor).copied().unwrap_or(0), ); let sort_code = if universal { - sqlx::query_scalar("SELECT sort_code FROM users WHERE id = $1") - .bind(vendor) - .fetch_optional(ctx.conn()) - .await? + seller_sort_code(ctx, vendor).await? } else { None }; diff --git a/backend/src/modules/events.rs b/backend/src/modules/events.rs index e949e23a..3104b5b1 100644 --- a/backend/src/modules/events.rs +++ b/backend/src/modules/events.rs @@ -48,7 +48,7 @@ const SERVICES: [&str; 5] = [ ]; const VISIBILITIES: [&str; 3] = ["public", "logged-in", "approved"]; const LABEL_FORMATS: [&str; 2] = ["standard", "small"]; -const LABEL_MARKS: [&str; 3] = ["number", "universal", "none"]; +const LABEL_MARKS: [&str; 2] = ["universal", "none"]; /// What viewers outside the team see instead of the access code const HIDDEN_ACCESS_CODE: &str = "••••"; diff --git a/backend/src/modules/features.rs b/backend/src/modules/features.rs index fad0cedb..18895b3e 100644 --- a/backend/src/modules/features.rs +++ b/backend/src/modules/features.rs @@ -79,7 +79,11 @@ pub fn resolve(features: Option<&Value>) -> EventFeatures { max_items_per_seller: stored.max_items_per_seller.map(|n| n.max(0.0) as u32), label_format: stored.label_format.unwrap_or_else(|| "standard".to_owned()), price_on_label: stored.price_on_label.unwrap_or(false), - label_mark: stored.label_mark.unwrap_or_else(|| "number".to_owned()), + // Older bazaars may have stored the seller number, which labels no longer show + label_mark: match stored.label_mark.as_deref() { + Some("none") => "none".to_owned(), + _ => "universal".to_owned(), + }, intake_fee: stored .intake_fee .and_then(Decimal::from_f64_retain) @@ -178,14 +182,10 @@ pub fn are_offers_open(status: &str, event: &Event, now: DateTime) -> bool status == "available" && event.start_date <= now && now <= event.end_date } -/// The seller's mark on the labels of this bazaar: `number` of this bazaar, `universal` -/// (the seller's lasting sorting code, for the many items on small labels) or `none`. +/// The seller's mark on the labels of this bazaar: `universal` (the seller's lasting sorting +/// code) or `none`. pub fn label_mark(event: &Event) -> String { - let features = event.resolved_features(); - if features.label_mark == "universal" && features.label_format != "small" { - return "number".to_owned(); - } - features.label_mark + event.resolved_features().label_mark } /// Labels show the price only without discounts: a discount would make it wrong. @@ -206,7 +206,7 @@ mod tests { assert_eq!(features.max_discount_percent, 50); assert!(!features.price_offers && !features.questions && !features.fixed_seller_data); assert_eq!(features.label_format, "standard"); - assert_eq!(features.label_mark, "number"); + assert_eq!(features.label_mark, "universal"); } #[test] diff --git a/backend/src/modules/labels.rs b/backend/src/modules/labels.rs index c5e035be..4f469ab3 100644 --- a/backend/src/modules/labels.rs +++ b/backend/src/modules/labels.rs @@ -18,9 +18,12 @@ use crate::shape::Id; /// More labels at once would be a huge PDF; nobody prints that many in one go. const MAX_LABELS: usize = 500; +/// Sorting codes with the same rest differ by the letter only: src/shared/sortCode.ts +const SORT_PATTERNS: i32 = 100_000; pub fn register(registry: &mut Registry) { register!(registry, Query "labels.getLabelData" => get_label_data); + register!(registry, Query "labels.getSortMarkClashes" => get_sort_mark_clashes); } #[derive(Deserialize)] @@ -36,8 +39,7 @@ struct LabelArgs { struct Label { product_id: Uuid, title: String, - seller_number: Option, - /// The seller's lasting code instead of the number (universal labels) + /// The seller's lasting code for sorting back; none on QR-only labels sort_code: Option, size: Option, price: Option, @@ -49,7 +51,7 @@ struct Labels { labels: Vec

+ + + {t('labels.title')} + {t('labels.text')} + + + {/* min-w-0: long bazaar titles must not widen the dialog beyond the screen */} +
+ {!selection && ( + + )} + +
+

{t('labels.summary', { count: ids.length, pages })}

+

+ {t(format === 'small' ? 'labels.formatSmall' : 'labels.formatStandard', { perPage })} +

+ {mark === 'universal' && ( +

{t('labels.reusableUniversal')}

+ )} + {mark === 'none' &&

{t('labels.reusable')}

} +
+ + {clash && ( +

+ + {t('labels.clash')} +

+ )} + +
+ + setStartInput(e.target.value)} + /> +

{t('labels.startAtHint', { perPage })}

+
+
+ + + + + +
+
+ ); +} diff --git a/src/components/products/ProductQRCodeDialog.test.tsx b/src/components/products/ProductQRCodeDialog.test.tsx index c967a712..94e8d746 100644 --- a/src/components/products/ProductQRCodeDialog.test.tsx +++ b/src/components/products/ProductQRCodeDialog.test.tsx @@ -6,9 +6,15 @@ import { downloadLabelsPdf } from '../../lib/productQRCodePdf'; import { ProductQRCodeDialog } from './ProductQRCodeDialog'; const client = vi.hoisted(() => ({})); -vi.mock('../../lib/api/react', () => ({ useApiClient: () => client })); -vi.mock('../../lib/productQRCodePdf', () => ({ downloadLabelsPdf: vi.fn() })); -vi.mock('sonner', () => ({ toast: { error: vi.fn() } })); +vi.mock('../../lib/api/react', () => ({ + useApiClient: () => client, + useQuery: () => undefined, +})); +vi.mock('../../lib/productQRCodePdf', async (importOriginal) => ({ + ...(await importOriginal()), + downloadLabelsPdf: vi.fn(), +})); +vi.mock('sonner', () => ({ toast: { error: vi.fn(), success: vi.fn() } })); const id = '0199f2a4-7c1e-7b3a-9d2e-5f6a7b8c9d0e' as Id<'products'>; @@ -17,20 +23,24 @@ function renderDialog() { } describe('ProductQRCodeDialog', () => { - it('prints the label of the item for its next bazaar', async () => { + it('prints the label of the item through the print dialog, with a start place', async () => { vi.mocked(downloadLabelsPdf).mockResolvedValue(1); renderDialog(); expect(screen.getByText(new RegExp(`/products/view/${id}$`))).toBeInTheDocument(); fireEvent.click(screen.getByRole('button', { name: 'Etikett als PDF' })); + fireEvent.change(await screen.findByLabelText('Erstes freies Feld auf dem Bogen'), { + target: { value: '3' }, + }); + fireEvent.click(screen.getByRole('button', { name: 'PDF herunterladen' })); // Without a bazaar: the backend takes the item's current or next one - await waitFor(() => expect(downloadLabelsPdf).toHaveBeenCalledWith(client, [id])); + await waitFor(() => expect(downloadLabelsPdf).toHaveBeenCalledWith(client, [id], undefined, 3)); }); it('shows why the label could not be made', async () => { vi.mocked(downloadLabelsPdf).mockRejectedValue(new Error('offline')); renderDialog(); fireEvent.click(screen.getByRole('button', { name: 'Etikett als PDF' })); + fireEvent.click(await screen.findByRole('button', { name: 'PDF herunterladen' })); await waitFor(() => expect(toast.error).toHaveBeenCalled()); - expect(screen.getByRole('button', { name: 'Etikett als PDF' })).toBeEnabled(); }); }); diff --git a/src/components/products/ProductQRCodeDialog.tsx b/src/components/products/ProductQRCodeDialog.tsx index e295a1d4..3e32ed90 100644 --- a/src/components/products/ProductQRCodeDialog.tsx +++ b/src/components/products/ProductQRCodeDialog.tsx @@ -1,14 +1,11 @@ import { useState } from 'react'; -import { QRCodeSVG } from 'qrcode.react'; import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '../ui/dialog'; import { Button } from '../ui/button'; import { Printer } from 'lucide-react'; -import { toast } from 'sonner'; import type { Id } from '../../lib/api/types'; -import { useApiClient } from '../../lib/api/react'; -import { getUserFacingErrorMessage } from '../../lib/errors'; -import { labelUrl } from '../../lib/labelQr'; -import { downloadLabelsPdf } from '../../lib/productQRCodePdf'; +import { labelUrl } from '../../lib/qrCode'; +import { QrCode } from '../ui/QrCode'; +import { LabelPrintDialog } from './LabelPrintDialog'; import { getProductUrl } from '../../lib/utils'; import { useTranslation } from 'react-i18next'; @@ -20,7 +17,7 @@ interface ProductQRCodeDialogProps { } /** - * The item's QR code as on its label, and the label as PDF: with format, seller number + * The item's QR code as on its label, and the label as PDF: with format, sorting code * and price rule of the item's next bazaar (labels.getLabelData). */ export function ProductQRCodeDialog({ @@ -30,21 +27,9 @@ export function ProductQRCodeDialog({ productTitle, }: ProductQRCodeDialogProps) { const { t } = useTranslation(); - const client = useApiClient(); - const [isCreating, setIsCreating] = useState(false); + const [printing, setPrinting] = useState(false); const productUrl = getProductUrl(productId); - const handleDownload = async () => { - setIsCreating(true); - try { - await downloadLabelsPdf(client, [productId]); - } catch (e) { - toast.error(getUserFacingErrorMessage(e)); - } finally { - setIsCreating(false); - } - }; - return ( @@ -53,23 +38,19 @@ export function ProductQRCodeDialog({ {t('qr.text')}
-
- +
+

{t('qr.url')}

{productUrl}

-
+
); diff --git a/src/components/sellers/SortMarkBadge.tsx b/src/components/sellers/SortMarkBadge.tsx index 4b0621ae..b324fd41 100644 --- a/src/components/sellers/SortMarkBadge.tsx +++ b/src/components/sellers/SortMarkBadge.tsx @@ -1,49 +1,103 @@ -import { sortMark, type SortSymbol } from '../../shared/sortCode'; +import { + SORT_COLORS, + SORT_SHAPES, + basketNumber, + sortMark, + sortMarkLayout, + sortMarkText, +} from '../../shared/sortCode'; import { cn } from '../../lib/utils'; const rgb = (color: readonly [number, number, number]) => `rgb(${color.join(' ')})`; -function Symbol({ symbol }: { symbol: SortSymbol }) { - const ink = rgb(symbol.ink); - return ( - - ); -} +const WIDTH = 183; +const HEIGHT = 110; -function Field({ symbol, className }: { symbol: SortSymbol; className?: string }) { +function Shape({ + digit, + x, + y, + size, + fill, + outlined, +}: { + digit: number; + x: number; + y: number; + size: number; + fill: string; + outlined?: boolean; +}) { return ( - - - + point.join()).join(' ')} + transform={`translate(${x} ${y}) scale(${size / 100})`} + fill={fill} + stroke={outlined ? 'black' : undefined} + strokeWidth={outlined ? 3 : undefined} + /> ); } -/** The sorting code as it is printed: large digit, one wide field over two small ones. */ +/** The sorting code as it is printed, on white like the paper. Set the size by its height. */ export function SortMarkBadge({ code, className }: { code: number; className?: string }) { - const { digit, fields, letter } = sortMark(code); + const mark = sortMark(code); + const layout = sortMarkLayout(mark, WIDTH, HEIGHT); + const { fill, ink } = SORT_COLORS[mark.pile]; + const text = { fontFamily: 'Helvetica, Arial, sans-serif', fontWeight: 700 }; return ( - - - {digit} - {letter && {letter}} - - - - - - - + + + + + {mark.pile} + + {layout.baskets.map((basket, i) => ( + + + + {basketNumber(mark.baskets[i])} + + + ))} + {layout.letter && ( + + {mark.letter} + + )} + ); } diff --git a/src/components/ui/QrCode.tsx b/src/components/ui/QrCode.tsx new file mode 100644 index 00000000..a772a0a1 --- /dev/null +++ b/src/components/ui/QrCode.tsx @@ -0,0 +1,28 @@ +import { useMemo } from 'react'; +import { qrRuns, screenQr } from '../../lib/qrCode'; + +/** + * Every QR code in the app. It comes from the same code as the printed labels, so they all + * look alike and keep their light border. On white in every theme, as scanners need it. + */ +export function QrCode({ value, className }: { value: string; className?: string }) { + const { path, box } = useMemo(() => { + const { runs, total } = qrRuns(screenQr(value)); + return { + box: total, + path: runs.map(({ x, y, width }) => `M${x} ${y}h${width}v1h-${width}Z`).join(''), + }; + }, [value]); + return ( + + + + + ); +} diff --git a/src/components/ui/country-select.tsx b/src/components/ui/country-select.tsx index 3790e594..593940c9 100644 --- a/src/components/ui/country-select.tsx +++ b/src/components/ui/country-select.tsx @@ -2,7 +2,7 @@ import type { ComponentProps } from 'react'; import { useTranslation } from 'react-i18next'; import { isCountry } from '../../i18n/countries'; import { COUNTRIES } from '../../shared/constants'; -import { cn } from '../utils'; +import { cn } from '../../lib/utils'; interface CountrySelectProps extends ComponentProps<'select'> { /** Value already saved: free text of an older profile stays selectable, not overwritten */ diff --git a/src/lib/api/types.ts b/src/lib/api/types.ts index 463228d7..76241104 100644 --- a/src/lib/api/types.ts +++ b/src/lib/api/types.ts @@ -107,7 +107,7 @@ export interface Docs { maxItemsPerSeller?: number | undefined; labelFormat?: 'small' | 'standard' | undefined; priceOnLabel?: boolean | undefined; - labelMark?: 'number' | 'universal' | 'none' | undefined; + labelMark?: 'universal' | 'none' | undefined; intakeFee?: number | undefined; privateSellersOnly?: boolean | undefined; fixedSellerData?: boolean | undefined; @@ -373,7 +373,7 @@ export type EventFeatures = { maxItemsPerSeller?: number | undefined; labelFormat: 'small' | 'standard'; priceOnLabel: boolean; - labelMark: 'number' | 'universal' | 'none'; + labelMark: 'universal' | 'none'; intakeFee?: number | undefined; privateSellersOnly: boolean; fixedSellerData: boolean; @@ -1001,7 +1001,7 @@ export interface Api { maxItemsPerSeller?: number | undefined; labelFormat?: 'small' | 'standard' | undefined; priceOnLabel?: boolean | undefined; - labelMark?: 'number' | 'universal' | 'none' | undefined; + labelMark?: 'universal' | 'none' | undefined; intakeFee?: number | undefined; privateSellersOnly?: boolean | undefined; fixedSellerData?: boolean | undefined; @@ -1069,7 +1069,7 @@ export interface Api { maxItemsPerSeller?: number | undefined; labelFormat?: 'small' | 'standard' | undefined; priceOnLabel?: boolean | undefined; - labelMark?: 'number' | 'universal' | 'none' | undefined; + labelMark?: 'universal' | 'none' | undefined; intakeFee?: number | undefined; privateSellersOnly?: boolean | undefined; fixedSellerData?: boolean | undefined; @@ -1139,7 +1139,7 @@ export interface Api { maxItemsPerSeller?: number | undefined; labelFormat?: 'small' | 'standard' | undefined; priceOnLabel?: boolean | undefined; - labelMark?: 'number' | 'universal' | 'none' | undefined; + labelMark?: 'universal' | 'none' | undefined; intakeFee?: number | undefined; privateSellersOnly?: boolean | undefined; fixedSellerData?: boolean | undefined; @@ -1209,7 +1209,7 @@ export interface Api { maxItemsPerSeller?: number | undefined; labelFormat?: 'small' | 'standard' | undefined; priceOnLabel?: boolean | undefined; - labelMark?: 'number' | 'universal' | 'none' | undefined; + labelMark?: 'universal' | 'none' | undefined; intakeFee?: number | undefined; privateSellersOnly?: boolean | undefined; fixedSellerData?: boolean | undefined; @@ -1287,7 +1287,7 @@ export interface Api { maxItemsPerSeller?: number | undefined; labelFormat?: 'small' | 'standard' | undefined; priceOnLabel?: boolean | undefined; - labelMark?: 'number' | 'universal' | 'none' | undefined; + labelMark?: 'universal' | 'none' | undefined; intakeFee?: number | undefined; privateSellersOnly?: boolean | undefined; fixedSellerData?: boolean | undefined; @@ -1358,7 +1358,7 @@ export interface Api { maxItemsPerSeller?: number | undefined; labelFormat?: 'small' | 'standard' | undefined; priceOnLabel?: boolean | undefined; - labelMark?: 'number' | 'universal' | 'none' | undefined; + labelMark?: 'universal' | 'none' | undefined; intakeFee?: number | undefined; privateSellersOnly?: boolean | undefined; fixedSellerData?: boolean | undefined; @@ -1426,7 +1426,7 @@ export interface Api { maxItemsPerSeller?: number | undefined; labelFormat?: 'small' | 'standard' | undefined; priceOnLabel?: boolean | undefined; - labelMark?: 'number' | 'universal' | 'none' | undefined; + labelMark?: 'universal' | 'none' | undefined; intakeFee?: number | undefined; privateSellersOnly?: boolean | undefined; fixedSellerData?: boolean | undefined; @@ -1480,7 +1480,7 @@ export interface Api { maxItemsPerSeller?: number | undefined; labelFormat?: 'small' | 'standard' | undefined; priceOnLabel?: boolean | undefined; - labelMark?: 'number' | 'universal' | 'none' | undefined; + labelMark?: 'universal' | 'none' | undefined; intakeFee?: number | undefined; privateSellersOnly?: boolean | undefined; fixedSellerData?: boolean | undefined; @@ -1532,7 +1532,7 @@ export interface Api { maxItemsPerSeller?: number | undefined; labelFormat?: 'small' | 'standard' | undefined; priceOnLabel?: boolean | undefined; - labelMark?: 'number' | 'universal' | 'none' | undefined; + labelMark?: 'universal' | 'none' | undefined; intakeFee?: number | undefined; privateSellersOnly?: boolean | undefined; fixedSellerData?: boolean | undefined; @@ -1603,7 +1603,7 @@ export interface Api { maxItemsPerSeller?: number | undefined; labelFormat?: 'small' | 'standard' | undefined; priceOnLabel?: boolean | undefined; - labelMark?: 'number' | 'universal' | 'none' | undefined; + labelMark?: 'universal' | 'none' | undefined; intakeFee?: number | undefined; privateSellersOnly?: boolean | undefined; fixedSellerData?: boolean | undefined; @@ -1707,6 +1707,7 @@ export interface Api { >; }; labels: { + getSortMarkClashes: FunctionReference<'query', { eventIds: Id<'events'>[] }, Id<'events'>[]>; getLabelData: FunctionReference< 'query', { eventId?: Id<'events'> | undefined; productIds: Id<'products'>[] }, diff --git a/src/lib/eventTypes.test.ts b/src/lib/eventTypes.test.ts index 21370d55..d4e8e389 100644 --- a/src/lib/eventTypes.test.ts +++ b/src/lib/eventTypes.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest'; import { EVENT_TYPES, findEventType } from './eventTypes'; -import { effectiveLabelMark, showsPriceOnLabel } from '../shared/eventFeatures'; +import { resolveEventFeatures, showsPriceOnLabel } from '../shared/eventFeatures'; import { REQUIRABLE_FIELD_KEYS } from '../shared/categoryFields'; import i18n from '../i18n'; @@ -21,15 +21,15 @@ describe('event types', () => { } }); - it('uses universal labels where many small items are sorted back', () => { + it('uses universal labels at every kind of bazaar', () => { const marks = Object.fromEntries( - EVENT_TYPES.map((type) => [type.id, effectiveLabelMark(type)]) + EVENT_TYPES.map((type) => [type.id, resolveEventFeatures(type).labelMark]) ); expect(marks).toEqual({ kidsBazaar: 'universal', clothingBazaar: 'universal', - skiBazaar: 'number', - bikeExchange: 'number', + skiBazaar: 'universal', + bikeExchange: 'universal', }); }); diff --git a/src/lib/productQRCodePdf.test.ts b/src/lib/productQRCodePdf.test.ts index b1c03a69..8626f5fd 100644 --- a/src/lib/productQRCodePdf.test.ts +++ b/src/lib/productQRCodePdf.test.ts @@ -18,10 +18,9 @@ vi.mock('jspdf', async (importOriginal) => { const id = (n: number) => `product${n}` as Id<'products'>; describe('labels', () => { - it('info line with seller number, size and price', () => { - const label = { productId: id(1), title: 'Body', sellerNumber: 17, size: '104', price: 5 }; - expect(labelInfoLine(label)).toBe('Nr. 17 · Gr. 104 · 5,00 €'); - expect(labelInfoLine(label, false)).toBe('Gr. 104 · 5,00 €'); + it('info line with size and price', () => { + const label = { productId: id(1), title: 'Body', sortCode: 17, size: '104', price: 5 }; + expect(labelInfoLine(label)).toBe('Gr. 104 · 5,00 €'); expect(labelInfoLine({ productId: id(1), title: 'Rad' })).toBe(''); }); @@ -39,7 +38,7 @@ describe('labels', () => { const labels = Array.from({ length: 41 }, (_, i) => ({ productId: id(i), title: `Artikel ${i}`, - sellerNumber: 3, + sortCode: 3, size: '98', })); expect(buildLabelsPdf(labels, 'small').getNumberOfPages()).toBe(2); @@ -49,7 +48,7 @@ describe('labels', () => { it('downloads what the backend returns', async () => { const query = vi.fn().mockResolvedValue({ format: 'small', - labels: [{ productId: id(1), title: 'Body', sellerNumber: 1 }], + labels: [{ productId: id(1), title: 'Body', sortCode: 1 }], }); const client = { query } as never; expect(await downloadLabelsPdf(client, [id(1)], 'event1' as Id<'events'>)).toBe(1); @@ -76,8 +75,9 @@ describe('labels', () => { it('draws the sorting mark in both formats', () => { for (const format of ['small', 'standard'] as const) { const pdf = buildLabelsPdf([label(1)], format).output(); - // The digit of the code 175 + // The pile and a basket mark of the code 175 expect(pdf).toContain('(5) Tj'); + expect(pdf).toContain('(88) Tj'); } }); }); diff --git a/src/lib/productQRCodePdf.ts b/src/lib/productQRCodePdf.ts index 25ca7529..1dd79345 100644 --- a/src/lib/productQRCodePdf.ts +++ b/src/lib/productQRCodePdf.ts @@ -3,7 +3,7 @@ import type { ApiClient } from './api/client'; import { api } from './api/functions'; import type { Id } from './api/types'; import type { LabelFormat } from '../shared/constants'; -import { drawLabelQr, labelUrl } from './labelQr'; +import { drawLabelQr, labelUrl } from './qrCode'; import { drawSortMark } from './sortMarkPdf'; import { formatPriceDE } from './utils'; import { savePdf } from './saveFile'; @@ -22,19 +22,16 @@ export const LABEL_LAYOUTS: Record export interface LabelData { productId: Id<'products'>; title: string; - /** Seller number at the bazaar, for sorting the items back after the sale */ - sellerNumber?: number; - /** Universal labels: the seller's lasting code instead of the number */ + /** The seller's lasting code for sorting the items back; none on QR-only labels */ sortCode?: number; size?: string; /** Only when the bazaar prints prices (and has no discounts) */ price?: number; } -/** "Nr. 17 · Gr. 104 · 5,00 €" – whatever is known about the item. */ -export function labelInfoLine(label: LabelData, withNumber = true): string { +/** "Gr. 104 · 5,00 €" – whatever is known about the item. */ +export function labelInfoLine(label: LabelData): string { return [ - withNumber && label.sellerNumber !== undefined ? `Nr. ${label.sellerNumber}` : null, label.size ? `Gr. ${label.size}` : null, label.price !== undefined ? `${formatPriceDE(label.price)} €` : null, ] @@ -84,7 +81,7 @@ interface Cell { height: number; } -/** QR code on top, title and "Nr. · Gr. · Preis" below. */ +/** QR code on top, title below, then the sorting mark with size and price next to it. */ function drawStandard(doc: jsPDF, label: LabelData, cell: Cell): void { const padding = 2; const qrSize = Math.min(cell.width, cell.height - 20) - 4; @@ -96,23 +93,26 @@ function drawStandard(doc: jsPDF, label: LabelData, cell: Cell): void { doc.setFontSize(8); const titleLines = wrapTitle(doc, label.title, cell.width - 2 * padding, 2); titleLines.forEach((line, i) => { - doc.text(line, centerX, qrY + qrSize + 3 + i * 4, { align: 'center' }); + doc.text(line, centerX, qrY + qrSize + 3 + i * 3.5, { align: 'center' }); }); + const rowY = qrY + qrSize + 3 + titleLines.length * 3.5 - 1.5; + const rowHeight = Math.min(cell.y + cell.height - padding - rowY, 11); + const markWidth = (rowHeight * 18.3) / 11; const info = labelInfoLine(label); - if (info) { - doc.setFont('helvetica', 'bold'); - doc.setFontSize(11); - doc.text(info, centerX, qrY + qrSize + 4.5 + titleLines.length * 4, { align: 'center' }); - } - // Only with items of bazaars with different sheets; the code stays the seller's + doc.setFont('helvetica', 'bold'); + doc.setFontSize(10); if (label.sortCode !== undefined) { - const y = qrY + qrSize + 6 + titleLines.length * 4; - drawSortMark(doc, label.sortCode, centerX - 11, y, 22, 7); + drawSortMark(doc, label.sortCode, cell.x + padding, rowY, markWidth, rowHeight); + doc.setFont('helvetica', 'bold'); + doc.setFontSize(10); + if (info) doc.text(info, cell.x + padding + markWidth + 2, rowY + rowHeight / 2 + 1.2); + } else if (info) { + doc.text(info, centerX, rowY + rowHeight / 2 + 1.2, { align: 'center' }); } } -/** QR code on the left, large seller number, title and size/price on the right. */ +/** QR code on the left, sorting mark, title and size/price on the right. */ function drawSmall(doc: jsPDF, label: LabelData, cell: Cell): void { const padding = 1.5; const qrSize = cell.height - 2 * padding; @@ -124,19 +124,15 @@ function drawSmall(doc: jsPDF, label: LabelData, cell: Cell): void { if (label.sortCode !== undefined) { drawSortMark(doc, label.sortCode, textX, cell.y + padding, textWidth, 11); lineY = cell.y + padding + 14; - } else if (label.sellerNumber !== undefined) { - doc.setFont('helvetica', 'bold'); - doc.setFontSize(13); - doc.text(`Nr. ${label.sellerNumber}`, textX, lineY); - lineY += 4.5; } + doc.setTextColor(0, 0, 0); doc.setFont('helvetica', 'normal'); doc.setFontSize(7); for (const line of wrapTitle(doc, label.title, textWidth, 2)) { doc.text(line, textX, lineY); lineY += 3; } - const info = labelInfoLine(label, false); + const info = labelInfoLine(label); if (info) { doc.setFont('helvetica', 'bold'); let size = 8; @@ -181,8 +177,8 @@ export function buildLabelsPdf(labels: LabelData[], format: LabelFormat, startAt } /** - * Loads what goes on the labels (seller number, size, price and the label sheet - * of the bazaar) and downloads the PDF. With `eventId` the labels are for that bazaar. + * The one way to labels: loads what goes on them (sorting code, size, price and the label + * sheet of the bazaar) and downloads the PDF. With `eventId` the labels are for that bazaar. */ export async function downloadLabelsPdf( client: ApiClient, diff --git a/src/lib/labelQr.test.ts b/src/lib/qrCode.test.ts similarity index 98% rename from src/lib/labelQr.test.ts rename to src/lib/qrCode.test.ts index abb2a532..2936fa5a 100644 --- a/src/lib/labelQr.test.ts +++ b/src/lib/qrCode.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest'; import { jsPDF } from 'jspdf'; -import { MIN_MODULE_MM, drawLabelQr, labelQr, labelUrl, moduleSize } from './labelQr'; +import { MIN_MODULE_MM, drawLabelQr, labelQr, labelUrl, moduleSize } from './qrCode'; import { getSiteUrl } from './seo'; const id = '0199f2a4-7c1e-7b3a-9d2e-5f6a7b8c9d0e'; diff --git a/src/lib/labelQr.ts b/src/lib/qrCode.ts similarity index 65% rename from src/lib/labelQr.ts rename to src/lib/qrCode.ts index a1126042..500dc19c 100644 --- a/src/lib/labelQr.ts +++ b/src/lib/qrCode.ts @@ -3,9 +3,10 @@ import * as QRCode from 'qrcode'; import { getSiteUrl } from './seo'; /** - * QR codes for printed labels. Phones read a code by the size of its modules (the - * black squares), so labels use a short link and pick the error correction by the - * printed size: as much as fits while the modules stay large enough. + * All QR codes: on screen through components/ui/QrCode, in PDFs through drawLabelQr. Phones + * read a code by the size of its modules (the black squares), so labels use a short link and + * pick the error correction by the printed size: as much as fits while the modules stay large + * enough. */ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; @@ -45,26 +46,39 @@ export function moduleSize(code: QRCode.QRCode, sizeMm: number): number { return sizeMm / (code.modules.size + 2 * QUIET_ZONE); } -/** - * Draws the code as vector squares, so it prints sharp at any resolution (a scaled - * bitmap blurs the module edges). Dark runs of a row become one rectangle. - */ -export function drawLabelQr(doc: jsPDF, text: string, x: number, y: number, sizeMm: number) { - const { code } = labelQr(text, sizeMm); +/** Screens are sharp and bright, so one level fits every code in the app. */ +export function screenQr(text: string): QRCode.QRCode { + return QRCode.create(text, { errorCorrectionLevel: 'M' }); +} + +/** The dark runs of each row in modules, with the light border; `total` is the full width. */ +export function qrRuns(code: QRCode.QRCode): { + total: number; + runs: { x: number; y: number; width: number }[]; +} { const { size } = code.modules; - const module = moduleSize(code, sizeMm); - const origin = (index: number) => (QUIET_ZONE + index) * module; - doc.setFillColor(0, 0, 0); + const runs: { x: number; y: number; width: number }[] = []; for (let row = 0; row < size; row++) { let start = -1; for (let col = 0; col <= size; col++) { const dark = col < size && code.modules.get(row, col); if (dark && start < 0) start = col; if (!dark && start >= 0) { - // A hair taller than the module, so PDF viewers show no seams between rows - doc.rect(x + origin(start), y + origin(row), (col - start) * module, module + 0.02, 'F'); + runs.push({ x: QUIET_ZONE + start, y: QUIET_ZONE + row, width: col - start }); start = -1; } } } + return { total: size + 2 * QUIET_ZONE, runs }; +} + +/** Draws the code as vector squares, so it prints sharp at any resolution. */ +export function drawLabelQr(doc: jsPDF, text: string, x: number, y: number, sizeMm: number) { + const { code } = labelQr(text, sizeMm); + const module = moduleSize(code, sizeMm); + doc.setFillColor(0, 0, 0); + for (const run of qrRuns(code).runs) { + // A hair taller than the module, so PDF viewers show no seams between rows + doc.rect(x + run.x * module, y + run.y * module, run.width * module, module + 0.02, 'F'); + } } diff --git a/src/lib/sortMarkPdf.ts b/src/lib/sortMarkPdf.ts index da5fa129..b4228cb2 100644 --- a/src/lib/sortMarkPdf.ts +++ b/src/lib/sortMarkPdf.ts @@ -1,43 +1,32 @@ import type { jsPDF } from 'jspdf'; -import { sortMark, type SortSymbol } from '../shared/sortCode'; +import { + SORT_COLORS, + SORT_SHAPES, + basketNumber, + sortMark, + sortMarkLayout, +} from '../shared/sortCode'; -function drawSymbol(doc: jsPDF, symbol: SortSymbol, cx: number, cy: number, size: number) { - const r = size / 2; - doc.setFillColor(...symbol.ink); - switch (symbol.id) { - case 'circle': - doc.circle(cx, cy, r, 'F'); - break; - case 'triangle': - doc.triangle(cx, cy - r, cx - r, cy + r, cx + r, cy + r, 'F'); - break; - case 'square': - doc.rect(cx - r, cy - r, size, size, 'F'); - break; - case 'diamond': - doc.triangle(cx - r, cy, cx + r, cy, cx, cy - r, 'F'); - // A hair of overlap, so PDF viewers show no seam - doc.triangle(cx - r, cy - 0.02, cx + r, cy - 0.02, cx, cy + r, 'F'); - break; - case 'cross': - doc.rect(cx - r, cy - r / 3, size, (2 * r) / 3, 'F'); - doc.rect(cx - r / 3, cy - r, (2 * r) / 3, size, 'F'); - break; - case 'bars': - doc.rect(cx - r, cy - r, size, size / 4, 'F'); - doc.rect(cx - r, cy - size / 8, size, size / 4, 'F'); - doc.rect(cx - r, cy + r - size / 4, size, size / 4, 'F'); - break; - } -} +/** A font size in the unit of the page (mm), in points */ +const points = (mm: number) => mm / 0.353; -function drawField(doc: jsPDF, symbol: SortSymbol, x: number, y: number, w: number, h: number) { - doc.setFillColor(...symbol.fill); - doc.rect(x, y, w, h, 'F'); - drawSymbol(doc, symbol, x + w / 2, y + h / 2, Math.min(w, h) * 0.6); +function drawShape( + doc: jsPDF, + digit: number, + x: number, + y: number, + size: number, + style: 'F' | 'FD' +) { + const { points: outline } = SORT_SHAPES[digit]; + const scale = size / 100; + const deltas = outline + .slice(1) + .map(([px, py], i) => [(px - outline[i][0]) * scale, (py - outline[i][1]) * scale]); + doc.lines(deltas, x + outline[0][0] * scale, y + outline[0][1] * scale, [1, 1], style, true); } -/** The large digit (with the letter, if any) and one wide field over two small ones. */ +/** The pile on the left, the two basket marks and, if any, the letter next to it. */ export function drawSortMark( doc: jsPDF, code: number, @@ -47,31 +36,39 @@ export function drawSortMark( height: number ) { const mark = sortMark(code); - const digitWidth = height * 0.72; - doc.setTextColor(0, 0, 0); + const layout = sortMarkLayout(mark, width, height); + const { fill, ink } = SORT_COLORS[mark.pile]; + + doc.setFillColor(...fill); + doc.rect(x, y, layout.pile.width, height, 'F'); + doc.setFillColor(...ink); + const { shape, digitEm } = layout.pile; + drawShape(doc, mark.pile, x + shape.x, y + shape.y, shape.size, 'F'); + doc.setTextColor(...ink); doc.setFont('helvetica', 'bold'); - // 1 pt is 0.353 mm; digits are about 0.72 of the font size high - doc.setFontSize(((mark.letter ? height * 0.72 : height) / 0.353) * 1.05); - const digitY = mark.letter ? y + height * 0.68 : y + height * 0.86; - doc.text(String(mark.digit), x + digitWidth / 2, digitY, { align: 'center' }); - if (mark.letter) { - doc.setFontSize((height * 0.3) / 0.353); - doc.text(mark.letter, x + digitWidth / 2, y + height * 0.98, { align: 'center' }); - } + doc.setFontSize(points(digitEm)); + doc.text(String(mark.pile), x + layout.pile.width / 2, y + height * 0.95, { align: 'center' }); - const fieldX = x + digitWidth; - const fieldWidth = width - digitWidth; - const gap = height * 0.03; - const rowHeight = (height - gap) / 2; - drawField(doc, mark.fields[0], fieldX, y, fieldWidth, rowHeight); - const smallWidth = (fieldWidth - gap) / 2; - drawField(doc, mark.fields[1], fieldX, y + rowHeight + gap, smallWidth, rowHeight); - drawField( - doc, - mark.fields[2], - fieldX + smallWidth + gap, - y + rowHeight + gap, - smallWidth, - rowHeight - ); + doc.setTextColor(0, 0, 0); + doc.setDrawColor(0, 0, 0); + for (const [i, basket] of layout.baskets.entries()) { + const value = mark.baskets[i]; + doc.setFillColor(...SORT_COLORS[Math.floor(value / 10)].fill); + doc.setLineWidth(basket.size * 0.03); + drawShape(doc, value % 10, x + basket.shapeX, y + basket.y, basket.size, 'FD'); + doc.setFontSize(points(basket.numberEm)); + // Digits are about 0.72 of the font size high + doc.text( + basketNumber(value), + x + basket.numberX, + y + basket.y + basket.size / 2 + basket.numberEm * 0.36, + { align: 'center' } + ); + } + if (layout.letter) { + doc.setFontSize(points(layout.letter.em)); + doc.text(mark.letter, x + layout.letter.x, y + height / 2 + layout.letter.em * 0.36, { + align: 'center', + }); + } } diff --git a/src/lib/sortSheetsPdf.ts b/src/lib/sortSheetsPdf.ts index 57f9fcb9..6f6a65e7 100644 --- a/src/lib/sortSheetsPdf.ts +++ b/src/lib/sortSheetsPdf.ts @@ -1,5 +1,5 @@ import { jsPDF } from 'jspdf'; -import { compareSortCodes } from '../shared/sortCode'; +import { clashingSortCodes, compareSortCodes } from '../shared/sortCode'; import { savePdf } from './saveFile'; import { drawSortMark } from './sortMarkPdf'; @@ -14,7 +14,8 @@ export interface SortSheetSeller { } /** A4 pages with two sheets each, in sorting order: one for each seller's basket. */ -export function buildSortSheetsPdf(sellers: SortSheetSeller[]): jsPDF { +export function buildSortSheetsPdf(sellers: SortSheetSeller[], clashNote = ''): jsPDF { + const clashing = clashingSortCodes(sellers.map((seller) => seller.sortCode)); const doc = new jsPDF({ orientation: 'portrait', unit: 'mm', format: 'a4' }); const sheetHeight = PAGE_HEIGHT / 2; const sorted = [...sellers].sort((a, b) => compareSortCodes(a.sortCode, b.sortCode)); @@ -31,6 +32,10 @@ export function buildSortSheetsPdf(sellers: SortSheetSeller[]): jsPDF { align: 'right', }); } + if (clashing.has(seller.sortCode)) { + doc.setFontSize(13); + doc.text(clashNote, MARGIN, y + MARGIN + 122, { maxWidth: PAGE_WIDTH - 2 * MARGIN }); + } if (i % 2 === 0) { doc.setDrawColor(190); doc.setLineWidth(0.1); @@ -40,6 +45,10 @@ export function buildSortSheetsPdf(sellers: SortSheetSeller[]): jsPDF { return doc; } -export async function downloadSortSheets(sellers: SortSheetSeller[]): Promise { - await savePdf(buildSortSheetsPdf(sellers), 'BazarPro-Sortierblaetter.pdf'); +/** `clashNote`: printed on the sheets of baskets that differ by the letter only. */ +export async function downloadSortSheets( + sellers: SortSheetSeller[], + clashNote: string +): Promise { + await savePdf(buildSortSheetsPdf(sellers, clashNote), 'BazarPro-Sortierblaetter.pdf'); } diff --git a/src/locales/de/common.json b/src/locales/de/common.json index 91ec0a22..2760d998 100644 --- a/src/locales/de/common.json +++ b/src/locales/de/common.json @@ -110,7 +110,7 @@ "sellerNumber": "Verkäufernummer", "qr": { "title": "QR-Code für {{title}}", - "text": "Das Etikett nutzt Format, Verkäufernummer und Preisregel des nächsten Basars dieses Artikels.", + "text": "Das Etikett nutzt Format, Sortierzeichen und Preisregel des nächsten Basars dieses Artikels.", "url": "Artikel-URL:", "downloadLabel": "Etikett als PDF" }, diff --git a/src/locales/de/company.json b/src/locales/de/company.json index 7263f1eb..593f2aaa 100644 --- a/src/locales/de/company.json +++ b/src/locales/de/company.json @@ -13,7 +13,7 @@ }, "qrLabels": { "title": "QR-Etiketten in zwei Größen", - "text": "Verkäufer drucken ihre Etiketten selbst: groß für Fahrräder, klein mit 40 pro Seite für Kleidung, mit Verkäufernummer oder als Universal-Etikett zum Wiederverwenden. Ohne Preis darauf gehen Rabatte ohne Neudruck." + "text": "Verkäufer drucken ihre Etiketten selbst: groß für Fahrräder, klein mit 40 pro Seite für Kleidung, als Universal-Etikett zum Wiederverwenden. Ohne Preis darauf gehen Rabatte ohne Neudruck." }, "phoneCheckout": { "title": "Kasse mit Warenkorb", @@ -46,25 +46,25 @@ }, "universalLabel": { "eyebrow": "Universal-Etikett", - "title": "Zurücksortieren, ohne zu lesen", - "text": "Bei Kinder- und Kleiderbasaren müssen am Ende Hunderte kleine Teile zurück zu ihren Verkäufern. Dabei hilft ein Zeichen aus Ziffer, Farben und Symbolen, das jeder Verkäufer behält.", + "title": "Zurücksortieren auf einen Blick", + "text": "Bei Basaren müssen am Ende Hunderte Teile zurück zu ihren Verkäufern. Dabei hilft ein Zeichen aus Farben, Formen und Zahlen, das jeder Verkäufer behält.", "example": "Beispiel für drei Etiketten eines Verkäufers mit demselben Sortierzeichen", "exampleItems": ["Body mit Bären", "Regenjacke", "Gummistiefel"], "steps": { "sort": { "title": "Auf einen Blick sortieren", - "text": "Helfer legen die Ware erst nach der großen Ziffer auf Stapel und dann nach Farben und Symbolen in die Kiste des Verkäufers. Die Sortierblätter für die Kisten druckt BazarPro." + "text": "Helfer legen die Ware erst nach dem großen Feld auf zehn Haufen und dann nach den beiden Zeichen in den Korb des Verkäufers. Die Schilder für die Körbe druckt BazarPro." }, "reuse": { "title": "Beim nächsten Basar wiederverwenden", - "text": "Das Zeichen bleibt beim Verkäufer. Unverkaufte Teile behalten ihr Etikett, wenn auch der nächste Basar Universal-Etiketten nutzt." + "text": "Das Zeichen bleibt beim Verkäufer und kommt nur einmal vor. Unverkaufte Teile behalten ihr Etikett, wenn auch der nächste Basar Universal-Etiketten nutzt." }, "print": { "title": "Auf jedem Drucker", - "text": "Jede Farbe hat ihr eigenes Symbol, deshalb klappt es auch im Schwarz-Weiß-Druck und für farbenblinde Helfer." + "text": "Jedes Zeichen zeigt auch seine Zahl, deshalb klappt es auch im Schwarz-Weiß-Druck und für farbenblinde Helfer." } }, - "default": "Bei den Vorlagen für Kinder- und Kleiderbasare schon eingestellt. Für wenige große Artikel wie Fahrräder bleibt die Verkäufernummer die bessere Wahl.", + "default": "Universal-Etiketten sind überall voreingestellt, in beiden Formaten. Die Verkäufernummer steht nicht mehr auf dem Etikett.", "guide": "So funktioniert das Universal-Etikett" }, "useCases": { @@ -103,7 +103,7 @@ "wizard": "Assistent zum Anlegen mit Vorlagen für Fahrradbörse, Kinderbasar und Flohmarkt", "registration": "Online-Anmeldung von Verkäufern mit Zugangscode und Teilnehmerlimit", "listing": "Artikel mit Foto und Preis online erfassen", - "labels": "QR-Code-Etiketten als PDF, groß oder klein, mit Verkäufernummer oder als wiederverwendbares Universal-Etikett", + "labels": "QR-Code-Etiketten als PDF, groß oder klein, als wiederverwendbares Universal-Etikett", "scan": "Warenannahme und Kasse per Smartphone-Scan", "cart": "Kasse mit Warenkorb, per Handykamera oder Hand-Scanner", "offline": "Offline-Kasse in der App: verkauft ohne Internet und bucht später nach", @@ -241,7 +241,7 @@ }, "universalLabels": { "question": "Was ist ein Universal-Etikett?", - "answer": "Ein kleines Etikett, das statt der Verkäufernummer ein festes Zeichen des Verkäufers aus Ziffer, Farben und Symbolen trägt. Helfer sortieren unverkaufte Ware danach zurück, ohne zu lesen. Unverkaufte Teile behalten ihr Etikett beim nächsten Basar mit Universal-Etiketten, und es funktioniert auch im Schwarz-Weiß-Druck." + "answer": "Ein Etikett mit einem festen Zeichen des Verkäufers aus Farben, Formen und Zahlen statt einer Verkäufernummer. Helfer sortieren unverkaufte Ware erst nach dem großen Feld auf zehn Haufen und dann in den Korb. Unverkaufte Teile behalten ihr Etikett beim nächsten Basar mit Universal-Etiketten, und es funktioniert auch im Schwarz-Weiß-Druck." }, "selfHost": { "question": "Kann ich BazarPro auf meinem eigenen Server betreiben?", diff --git a/src/locales/de/landing.json b/src/locales/de/landing.json index d846498b..9daabef6 100644 --- a/src/locales/de/landing.json +++ b/src/locales/de/landing.json @@ -18,7 +18,7 @@ }, "printer": { "title": "Etiketten als PDF", - "text": "Groß oder klein, mit Verkäufernummer oder als Universal-Etikett zum Wiederverwenden – einzeln oder alle auf einmal." + "text": "Groß oder klein, als wiederverwendbares Universal-Etikett oder nur mit QR-Code – einzeln oder alle auf einmal." }, "badgePercent": { "title": "Rabatte", diff --git a/src/locales/de/organizer.json b/src/locales/de/organizer.json index 08aa7633..349b9ba1 100644 --- a/src/locales/de/organizer.json +++ b/src/locales/de/organizer.json @@ -140,13 +140,10 @@ "labelsSmall": "Klein – 40 pro A4-Seite (z. B. Kleidung)", "labelsHint": "Auf jedem Etikett stehen QR-Code, Titel und – wenn angegeben – die Größe.", "labelMark": "Verkäufer auf dem Etikett", - "labelMarkNumber": "Verkäufernummer dieses Basars", - "labelMarkUniversal": "Universal-Etikett: Ziffer und Sortierzeichen (nur kleine Etiketten)", + "labelMarkUniversal": "Universal-Etikett: festes Sortierzeichen des Verkäufers", "labelMarkNone": "Nichts, nur QR-Code", - "labelMarkNumberHint": "Am einfachsten zu lesen. Die Nummer gilt nur für diesen Basar, Verkäufer drucken für den nächsten neu.", - "labelMarkUniversalHint": "Für viele kleine Teile: Helfer sortieren erst nach der großen Ziffer, dann nach Farben und Symbolen, ohne zu lesen. Das Zeichen bleibt beim Verkäufer, die Etiketten passen also auch bei anderen Basaren mit Universal-Etiketten. Es funktioniert auch im Schwarz-Weiß-Druck.", + "labelMarkUniversalHint": "Helfer sortieren erst nach dem großen Feld auf zehn Haufen, dann nach den beiden Zeichen in den Korb. Das Zeichen bleibt beim Verkäufer, die Etiketten passen also auch bei anderen Basaren mit Universal-Etiketten.", "labelMarkNoneHint": "Die Etiketten lassen sich wiederverwenden. Zum Zurücksortieren muss das Team aber jeden Artikel scannen.", - "labelMarkNeedsSmall": "Universal-Etiketten gibt es nur im kleinen Format. Im großen Format wird die Verkäufernummer gedruckt.", "priceOnLabel": "Preis aufs Etikett drucken", "priceOnLabelText": "Hilft an der Kasse ohne Scanner. Der Preis auf dem Etikett ist fest – bei Rabatten wird er deshalb nicht gedruckt.", "priceOnLabelDiscounts": "Rabatte sind eingeschaltet, deshalb erscheint kein Preis auf den Etiketten.", @@ -259,7 +256,6 @@ "labelsSmall": "Kleine Etiketten (40 pro Seite)", "labelsLarge": "Große Etiketten (12 pro Seite)", "priceOnLabel": "Preis auf dem Etikett", - "labelMarkNumber": "Verkäufernummer auf dem Etikett", "labelMarkUniversal": "Universal-Etikett mit Sortierzeichen", "questionsDuringEvent": "erst während des Basars", "requiredFields": "Pflichtangaben: {{fields}}", @@ -305,7 +301,10 @@ "appoint": "Als Helfer ernennen", "noAccess": "Keine Berechtigung", "addHelper": "Helfer hinzufügen", - "noHelpers": "Noch keine Helfer. Über „Helfer hinzufügen“ ernennst du Teilnehmer zu Helfern." + "noHelpers": "Noch keine Helfer. Über „Helfer hinzufügen“ ernennst du Teilnehmer zu Helfern.", + "sortClash_one": "{{count}} Korb hat dasselbe Muster wie ein anderer und unterscheidet sich nur im Buchstaben.", + "sortClash_other": "{{count}} Körbe haben dasselbe Muster wie ein anderer und unterscheiden sich nur im Buchstaben. Die Sortierblätter weisen darauf hin.", + "sortClashNote": "Achtung: Ein anderer Korb hat dasselbe Muster. Achte auf den Buchstaben: Etiketten ohne Buchstabe gehören in den Korb ohne Buchstabe." }, "settle": { "seller": "Verkäufer", @@ -793,9 +792,8 @@ "labelLarge": "Großes Etikett · 12 pro A4-Seite", "labelSmall": "Kleines Etikett · 40 pro A4-Seite", "labelPriceHidden": "Ohne Preis: Rabatte ändern ihn ja noch.", - "labelNumber": "Nr. {{seller}}", "labelReusable": "Ohne Verkäufernummer: Das Etikett passt auch beim nächsten Basar.", - "labelUniversal": "Universal-Etikett: Ziffer, Farben und Symbole bleiben beim Verkäufer. Das Team sortiert danach und braucht nichts zu lesen.", + "labelUniversal": "Universal-Etikett: Das Sortierzeichen aus Farben, Formen und Zahlen bleibt beim Verkäufer. Das Team sortiert danach und braucht kaum zu lesen.", "photoRequired": "Foto Pflicht", "photoOptional": "Ohne Foto", "maxItems": "Bis zu {{count}} Artikel pro Verkäufer", diff --git a/src/locales/de/seller.json b/src/locales/de/seller.json index f69ae6c3..a296f720 100644 --- a/src/locales/de/seller.json +++ b/src/locales/de/seller.json @@ -189,14 +189,15 @@ "summary_other": "{{count}} Etiketten auf {{pages}} A4-Seiten", "formatStandard": "Format Standard: {{perPage}} große Etiketten pro Seite", "formatSmall": "Format Klein: {{perPage}} kleine Etiketten pro Seite", - "formatPerItem": "Format und Verkäufernummer nach dem jeweils nächsten Basar des Artikels, sonst Standard", - "reusable": "Ohne Verkäufernummer: Du kannst diese Etiketten beim nächsten Basar wiederverwenden.", - "reusableUniversal": "Mit Sortierzeichen statt Nummer: Diese Etiketten kannst du bei anderen Basaren mit Universal-Etiketten wiederverwenden.", + "reusable": "Nur QR-Code: Du kannst diese Etiketten beim nächsten Basar wiederverwenden.", + "reusableUniversal": "Mit deinem festen Sortierzeichen: Diese Etiketten kannst du bei jedem Basar mit Universal-Etiketten wiederverwenden.", "startAt": "Erstes freies Feld auf dem Bogen", "startAtHint": "Für angebrochene Bögen: Zeile für Zeile gezählt, 1 bis {{perPage}}.", "download": "PDF herunterladen", "created_one": "{{count}} Etikett erstellt", "created_other": "{{count}} Etiketten erstellt", - "open": "Etiketten drucken" + "open": "Etiketten drucken", + "clash": "Achtung: Ein anderer Verkäufer bei diesem Basar hat dasselbe Muster wie du. Eure Etiketten unterscheiden sich nur im Buchstaben. Du musst nichts ändern, das Team sieht es auf den Sortierblättern. Bitte weise beim Abgeben darauf hin.", + "clashAt": "Achtung: Bei {{bazaars}} hat ein anderer Verkäufer dasselbe Muster wie du. Eure Etiketten unterscheiden sich nur im Buchstaben. Bitte weise beim Abgeben darauf hin." } } diff --git a/src/locales/en/common.json b/src/locales/en/common.json index 958a32cc..56b0528e 100644 --- a/src/locales/en/common.json +++ b/src/locales/en/common.json @@ -110,7 +110,7 @@ "sellerNumber": "Seller number", "qr": { "title": "QR code for {{title}}", - "text": "The label uses the format, seller number and price rule of this item's next bazaar.", + "text": "The label uses the format, sorting mark and price rule of this item's next bazaar.", "url": "Item URL:", "downloadLabel": "Label as PDF" }, diff --git a/src/locales/en/company.json b/src/locales/en/company.json index 4afc655e..f6bbea11 100644 --- a/src/locales/en/company.json +++ b/src/locales/en/company.json @@ -13,7 +13,7 @@ }, "qrLabels": { "title": "QR labels in two sizes", - "text": "Sellers print their own labels: large for bikes, small with 40 per page for clothes, with the seller number or as a reusable universal label. Without a price on them, discounts work without reprinting." + "text": "Sellers print their own labels: large for bikes, small with 40 per page for clothes, as a reusable universal label. Without a price on them, discounts work without reprinting." }, "phoneCheckout": { "title": "Checkout with a cart", @@ -46,25 +46,25 @@ }, "universalLabel": { "eyebrow": "Universal label", - "title": "Sort items back without reading", - "text": "At kids' and clothing bazaars, hundreds of small items have to go back to their sellers at the end. A mark made of a digit, colors and symbols, which each seller keeps, makes this easier.", + "title": "Sort back at a glance", + "text": "At the end of a bazaar hundreds of items go back to their sellers. A mark of colors, shapes and numbers that every seller keeps makes this easy.", "example": "Example of three labels from one seller with the same sorting mark", "exampleItems": ["Bodysuit with bears", "Rain jacket", "Rubber boots"], "steps": { "sort": { "title": "Sort at a glance", - "text": "Helpers pile the items by the large digit first, then put them into the seller's basket by colors and symbols. BazarPro prints the sorting sheets for the baskets." + "text": "Helpers first sort by the large field into ten piles, then by the two marks into the seller's basket. BazarPro prints the signs for the baskets." }, "reuse": { "title": "Reuse at the next bazaar", - "text": "The mark stays with the seller. Unsold items keep their label if the next bazaar uses universal labels too." + "text": "The mark stays with the seller and exists only once. Unsold items keep their label if the next bazaar uses universal labels too." }, "print": { "title": "On any printer", - "text": "Every color has its own symbol, so it also works in black and white and for color-blind helpers." + "text": "Every mark also shows its number, so it works in black and white and for color-blind helpers." } }, - "default": "Already set in the templates for kids' and clothing bazaars. For a few large items such as bikes, the seller number remains the better choice.", + "default": "Universal labels are the default everywhere, in both formats. The seller number is no longer on the label.", "guide": "How the universal label works" }, "useCases": { @@ -103,7 +103,7 @@ "wizard": "Creation wizard with presets for bike sales, kids' bazaars and flea markets", "registration": "Online seller registration with access code and participant limit", "listing": "Enter items online with photo and price", - "labels": "QR code labels as PDF, large or small, with seller number or as a reusable universal label", + "labels": "QR code labels as PDF, large or small, as a reusable universal label", "scan": "Drop-off and checkout by smartphone scan", "cart": "Checkout with a cart, by phone camera or hand scanner", "offline": "Offline checkout in the app: sells without internet and books the sales later", @@ -241,7 +241,7 @@ }, "universalLabels": { "question": "What is a universal label?", - "answer": "A small label that carries a seller's lasting mark made of a digit, colors and symbols instead of the seller number. Helpers sort unsold items back by it without reading. Unsold items keep their label at the next bazaar with universal labels, and it also works in black and white." + "answer": "A label with a lasting mark of the seller made of colors, shapes and numbers instead of a seller number. Helpers first sort unsold items by the large field into ten piles, then into the basket. Unsold items keep their label at the next bazaar with universal labels, and it also works in black and white." }, "selfHost": { "question": "Can I run BazarPro on my own server?", diff --git a/src/locales/en/organizer.json b/src/locales/en/organizer.json index b17407aa..c3a6f587 100644 --- a/src/locales/en/organizer.json +++ b/src/locales/en/organizer.json @@ -140,13 +140,10 @@ "labelsSmall": "Small – 40 per A4 page (e.g. clothes)", "labelsHint": "Every label shows QR code, title and – if given – the size.", "labelMark": "Seller on the label", - "labelMarkNumber": "Seller number of this bazaar", - "labelMarkUniversal": "Universal label: digit and sorting mark (small labels only)", + "labelMarkUniversal": "Universal label: the seller's lasting sorting mark", "labelMarkNone": "Nothing, QR code only", - "labelMarkNumberHint": "Easiest to read. The number is only valid for this bazaar, sellers print again for the next.", - "labelMarkUniversalHint": "For many small items: helpers sort by the large digit first, then by colors and symbols, without reading. The mark stays with the seller, so labels also work at other bazaars with universal labels. It also works in black and white.", + "labelMarkUniversalHint": "Helpers first sort by the large field into ten piles, then by the two marks into the basket. The mark stays with the seller, so the labels also fit other bazaars with universal labels.", "labelMarkNoneHint": "Labels can be reused. To sort items back, the team has to scan every one.", - "labelMarkNeedsSmall": "Universal labels only exist in the small format. The large format prints the seller number.", "priceOnLabel": "Print the price on the label", "priceOnLabelText": "Helps at a cash desk without scanner. The printed price is fixed – so it is not printed when discounts are on.", "priceOnLabelDiscounts": "Discounts are switched on, so no price appears on the labels.", @@ -259,7 +256,6 @@ "labelsSmall": "Small labels (40 per page)", "labelsLarge": "Large labels (12 per page)", "priceOnLabel": "Price on the label", - "labelMarkNumber": "Seller number on the label", "labelMarkUniversal": "Universal label with sorting mark", "questionsDuringEvent": "only during the bazaar", "requiredFields": "Required details: {{fields}}", @@ -305,7 +301,10 @@ "appoint": "Make helper", "noAccess": "No permission", "addHelper": "Add helper", - "noHelpers": "No helpers yet. Use “Add helper” to make participants helpers." + "noHelpers": "No helpers yet. Use “Add helper” to make participants helpers.", + "sortClash_one": "{{count}} basket has the same pattern as another one and differs by the letter only.", + "sortClash_other": "{{count}} baskets have the same pattern as another one and differ by the letter only. The sorting sheets point this out.", + "sortClashNote": "Note: another basket has the same pattern. Check the letter: labels without a letter belong in the basket without a letter." }, "settle": { "seller": "Seller", @@ -793,9 +792,8 @@ "labelLarge": "Large label · 12 per A4 page", "labelSmall": "Small label · 40 per A4 page", "labelPriceHidden": "No price: discounts may still change it.", - "labelNumber": "No. {{seller}}", "labelReusable": "No seller number: the label also works at the next bazaar.", - "labelUniversal": "Universal label: digit, colors and symbols stay with the seller. The team sorts by them without reading.", + "labelUniversal": "Universal label: the sorting mark of colors, shapes and numbers stays with the seller. The team sorts by it and hardly needs to read.", "photoRequired": "Photo required", "photoOptional": "No photo", "maxItems": "Up to {{count}} items per seller", diff --git a/src/locales/en/seller.json b/src/locales/en/seller.json index 521766fd..42edb7e6 100644 --- a/src/locales/en/seller.json +++ b/src/locales/en/seller.json @@ -189,14 +189,15 @@ "summary_other": "{{count}} labels on {{pages}} A4 pages", "formatStandard": "Standard format: {{perPage}} large labels per page", "formatSmall": "Small format: {{perPage}} small labels per page", - "formatPerItem": "Format and seller number from each item's next bazaar, otherwise standard", - "reusable": "No seller number: you can reuse these labels at the next bazaar.", - "reusableUniversal": "With a sorting mark instead of a number: you can reuse these labels at other bazaars with universal labels.", + "reusable": "QR code only: you can reuse these labels at the next bazaar.", + "reusableUniversal": "With your lasting sorting mark: you can reuse these labels at any bazaar with universal labels.", "startAt": "First free place on the sheet", "startAtHint": "For partly used sheets: counted row by row, 1 to {{perPage}}.", "download": "Download PDF", "created_one": "{{count}} label created", "created_other": "{{count}} labels created", - "open": "Print labels" + "open": "Print labels", + "clash": "Note: another seller at this bazaar has the same pattern as you. Your labels differ by the letter only. You need not change anything, the team sees it on the sorting sheets. Please point it out when you hand in your items.", + "clashAt": "Note: at {{bazaars}} another seller has the same pattern as you. Your labels differ by the letter only. Please point it out when you hand in your items." } } diff --git a/src/pages/account/components/DigitalIdCard.test.tsx b/src/pages/account/components/DigitalIdCard.test.tsx index 5834d0e7..d2cccb7d 100644 --- a/src/pages/account/components/DigitalIdCard.test.tsx +++ b/src/pages/account/components/DigitalIdCard.test.tsx @@ -17,8 +17,8 @@ vi.mock('../../../lib/checkInCode', async (actual) => ({ currentCodes: vi.fn(async () => ['12345678']), })); // The value of the QR code as text -vi.mock('qrcode.react', () => ({ - QRCodeSVG: ({ value }: { value: string }) => {value}, +vi.mock('../../../components/ui/QrCode', () => ({ + QrCode: ({ value }: { value: string }) => {value}, })); const USER = '0b6f1c3e-6a5b-4c7d-8e9f-0a1b2c3d4e5f'; diff --git a/src/pages/account/components/DigitalIdCard.tsx b/src/pages/account/components/DigitalIdCard.tsx index 3ac1f108..81abc304 100644 --- a/src/pages/account/components/DigitalIdCard.tsx +++ b/src/pages/account/components/DigitalIdCard.tsx @@ -11,8 +11,8 @@ import { } from '../../../lib/checkInCode'; import { isNetworkError } from '../../../lib/offlineMode'; import { Button } from '../../../components/ui/button'; -import { QrCode, EyeOff } from 'lucide-react'; -import { QRCodeSVG } from 'qrcode.react'; +import { QrCode as QrCodeIcon, EyeOff } from 'lucide-react'; +import { QrCode } from '../../../components/ui/QrCode'; import { toast } from 'sonner'; import { getUserFacingErrorMessage } from '../../../lib/errors'; import { useTranslation } from 'react-i18next'; @@ -132,7 +132,7 @@ export function DigitalIdCard() {
- +

{t('digitalId.title')}

{showDigitalId && ( @@ -152,7 +152,7 @@ export function DigitalIdCard() {
{/* While a new token loads the last code stays: the time-based codes work */} {qrValue ? ( - + ) : ( )} diff --git a/src/pages/organizer/events/components/EditEventFeatures.tsx b/src/pages/organizer/events/components/EditEventFeatures.tsx index 0be5213c..f7205682 100644 --- a/src/pages/organizer/events/components/EditEventFeatures.tsx +++ b/src/pages/organizer/events/components/EditEventFeatures.tsx @@ -222,7 +222,6 @@ export function EditEventFeatures({ } = useFormContext(); const discounts = watch('features.discounts') as boolean; const priceOnLabel = watch('features.priceOnLabel') as boolean; - const labelFormat = watch('features.labelFormat') as string; const labelMark = watch('features.labelMark') as string; const featureErrors = errors.features as | Partial< @@ -347,26 +346,16 @@ export function EditEventFeatures({ className="flex h-9 w-full max-w-sm rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-xs" {...register('features.labelMark')} > - - +

{t( - labelMark === 'universal' - ? 'features.labelMarkUniversalHint' - : labelMark === 'none' - ? 'features.labelMarkNoneHint' - : 'features.labelMarkNumberHint' + labelMark === 'none' + ? 'features.labelMarkNoneHint' + : 'features.labelMarkUniversalHint' )}

- {labelMark === 'universal' && labelFormat !== 'small' && ( -

- {t('features.labelMarkNeedsSmall')} -

- )}
@@ -369,18 +370,12 @@ function LabelPreview({ )} > -
- {small && mark === 'number' &&

Nr. 17

} - {small && mark === 'universal' && ( - - )} + {mark === 'universal' && }

- {[ - !small && mark === 'number' && number, - price !== undefined && `${formatPriceDE(price)} €`, - ] - .filter(Boolean) - .join(' · ')} + {price !== undefined && `${formatPriceDE(price)} €`}

@@ -419,7 +409,7 @@ export function ItemsPreview({ type }: { type?: EventType }) { const limit = given(features.maxItemsPerSeller); const small = features.labelFormat === 'small'; const showPrice = !!features.priceOnLabel && !features.discounts; - const mark = effectiveLabelMark({ features: features as StoredEventFeatures }); + const mark = resolveEventFeatures({ features: features as StoredEventFeatures }).labelMark; return ( (null); // URL-synced state @@ -362,24 +363,13 @@ export function ProductManagementPage() { } }; - const handleDownloadAllQRCodes = async () => { + const handleDownloadAllQRCodes = () => { if (!vendorProducts || vendorProducts.length === 0) { toast.error(t('products.noProducts')); return; } - const toastId = toast.loading(t('products.labelsCreating')); - try { - const count = await downloadLabelsPdf( - client, - vendorProducts.map((p) => p._id as Id<'products'>), - eventId - ); - toast.success(t('products.labelsCreated', { count }), { id: toastId }); - } catch (e) { - console.error('QR Export Error:', e); - toast.error(t('products.labelsFailed'), { id: toastId }); - } + setLabelsOpen(true); }; // Individual product action states @@ -891,6 +881,12 @@ export function ProductManagementPage() { /> )} + p._id as Id<'products'>)} + eventId={eventId} + />
); } diff --git a/src/pages/organizer/events/dashboard/SellerManagementPage.tsx b/src/pages/organizer/events/dashboard/SellerManagementPage.tsx index b40e79f8..6ca1c069 100644 --- a/src/pages/organizer/events/dashboard/SellerManagementPage.tsx +++ b/src/pages/organizer/events/dashboard/SellerManagementPage.tsx @@ -1,5 +1,6 @@ import { SortMarkBadge } from '../../../../components/sellers/SortMarkBadge'; import { downloadSortSheets } from '../../../../lib/sortSheetsPdf'; +import { clashingSortCodes } from '../../../../shared/sortCode'; import { PageSkeleton } from '../../../../components/ui/loading'; import { PageHeader } from '../../../../components/ui/page-header'; import { SearchInput } from '../../../../components/ui/search-input'; @@ -86,6 +87,9 @@ export function SellerManagementPage() { : [{ sortCode: v.sortCode, name: v.name ?? '-', sellerNumber: v.sellerNumber }] ); + // Baskets that differ by the letter only + const clashingCodes = clashingSortCodes(sortSheetSellers.map((seller) => seller.sortCode)); + const addHelper = useMutation(api.eventRoles.addCoOrganizerForEvent); useAssignMissingSellerNumbers(eventId as Id<'events'>, vendors, canManage); const removeHelper = useMutation(api.eventRoles.removeCoOrganizerForEvent); @@ -173,8 +177,8 @@ export function SellerManagementPage() { className="gap-2" title={t('sellers.sortSheetsHint')} onClick={() => - void downloadSortSheets(sortSheetSellers).catch((e: unknown) => - toast.error(getUserFacingErrorMessage(e)) + void downloadSortSheets(sortSheetSellers, t('sellers.sortClashNote')).catch( + (e: unknown) => toast.error(getUserFacingErrorMessage(e)) ) } > @@ -185,6 +189,15 @@ export function SellerManagementPage() { } /> + {clashingCodes.size > 0 && ( +

+ {t('sellers.sortClash', { count: clashingCodes.size })} +

+ )} +
{v.name} {v.sortCode !== undefined && ( - + )} {v.managedByEventId && } {v.isHelper && !isOwner && ( diff --git a/src/pages/organizer/events/dashboard/components/EventSettingsSummary.tsx b/src/pages/organizer/events/dashboard/components/EventSettingsSummary.tsx index 67b5e9b4..d7428e82 100644 --- a/src/pages/organizer/events/dashboard/components/EventSettingsSummary.tsx +++ b/src/pages/organizer/events/dashboard/components/EventSettingsSummary.tsx @@ -1,7 +1,7 @@ import type { ReactNode } from 'react'; import { Check, Minus } from 'lucide-react'; import type { Doc } from '../../../../../lib/api/types'; -import { effectiveLabelMark, resolveEventFeatures } from '../../../../../shared/eventFeatures'; +import { resolveEventFeatures } from '../../../../../shared/eventFeatures'; import { VISIBILITY_OPTIONS } from '../../../../../constants/records'; import { formatDateRangeDE, formatPriceDE } from '../../../../../lib/utils'; import { Badge } from '../../../../../components/ui/badge'; @@ -69,7 +69,6 @@ export function EventSettingsSummary({ event }: { event: EventWithLabels }) { minute: '2-digit', }); const features = resolveEventFeatures(event); - const labelMark = effectiveLabelMark(event); const logistics = event.sellerLogistics; const discountDetail = [ features.discountStartsAt @@ -166,12 +165,7 @@ export function EventSettingsSummary({ event }: { event: EventWithLabels }) { features.labelFormat === 'small' ? t('summary.labelsSmall') : t('summary.labelsLarge') } /> - + - +
- +

{title}

diff --git a/src/pages/public/landing/components/demo/Illustrations.tsx b/src/pages/public/landing/components/demo/Illustrations.tsx index 11ef655a..c8e26d9b 100644 --- a/src/pages/public/landing/components/demo/Illustrations.tsx +++ b/src/pages/public/landing/components/demo/Illustrations.tsx @@ -1,5 +1,5 @@ import { ShoppingBag } from 'lucide-react'; -import { QRCodeSVG } from 'qrcode.react'; +import { QrCode } from '../../../../../components/ui/QrCode'; import type { ReactNode } from 'react'; import { cn } from '../../../../../lib/utils'; @@ -160,13 +160,7 @@ export function HangTag({ itemNumber, className, overlay }: HangTagProps) {
- + {overlay}

diff --git a/src/pages/public/landing/components/demo/ProcessVisuals.tsx b/src/pages/public/landing/components/demo/ProcessVisuals.tsx index 8d2dd902..080c29fb 100644 --- a/src/pages/public/landing/components/demo/ProcessVisuals.tsx +++ b/src/pages/public/landing/components/demo/ProcessVisuals.tsx @@ -1,5 +1,5 @@ import { Banknote, Check, MapPin, PackageOpen, Printer, ScanLine } from 'lucide-react'; -import { QRCodeSVG } from 'qrcode.react'; +import { QrCode } from '../../../../../components/ui/QrCode'; import type { CSSProperties, ReactNode } from 'react'; import { cn } from '../../../../../lib/utils'; import { AppBar, BikePhoto, BikeWithTag, HangTag, PhoneFrame } from './Illustrations'; @@ -305,7 +305,7 @@ export function PickupScene() { className="landing-fade-up flex flex-col items-center gap-1 rounded-lg bg-white p-2 text-zinc-900" style={delay(800)} > - +

{t('account:digitalId.title')}

diff --git a/src/pages/seller/products/MyProductsPage.tsx b/src/pages/seller/products/MyProductsPage.tsx index 3791cd9f..9bee2a53 100644 --- a/src/pages/seller/products/MyProductsPage.tsx +++ b/src/pages/seller/products/MyProductsPage.tsx @@ -14,7 +14,6 @@ import { ProductFilters } from '../../../components/products/ProductFilters'; import { Button } from '../../../components/ui/button'; import { downloadPrivateInvoiceForProduct } from '../../../lib/privateInvoice'; import type { InvoiceCopy } from '../../../lib/saleBreakdown'; -import { downloadLabelsPdf } from '../../../lib/productQRCodePdf'; import { filterAndSortProducts } from '../../../hooks/useMyProductsFilters'; import { BulkEventAssignmentDialog } from './components/BulkEventAssignmentDialog'; import { @@ -24,13 +23,13 @@ import { import type { MyProductCardProduct } from './components/MyProductCard'; import { MyProductsGrid } from './components/MyProductsGrid'; import { MyProductsPageHeader } from './components/MyProductsPageHeader'; -import { LabelPrintDialog } from './components/LabelPrintDialog'; +import { LabelPrintDialog } from '../../../components/products/LabelPrintDialog'; import { ProductDiscountDialog } from './components/ProductDiscountDialog'; import { toast } from 'sonner'; import { getUserFacingErrorMessage } from '../../../lib/errors'; import { findProductsToComplete, type ProductToComplete } from '../../../lib/productCompletion'; import { uploadImages } from '../../../lib/uploadImages'; -import { FileDown, Tag, Trash2 } from 'lucide-react'; +import { AlertTriangle, FileDown, Tag, Trash2 } from 'lucide-react'; import { useMarkNoticesSeen } from '../../../hooks/useMarkNoticesSeen'; import { Trans, useTranslation } from 'react-i18next'; import { ListSkeleton, Loading } from '../../../components/ui/loading'; @@ -87,7 +86,7 @@ export function MyProductsPage() { const [isBulkEventDialogOpen, setIsBulkEventDialogOpen] = useState(false); const [bulkSelectedEvents, setBulkSelectedEvents] = useState([]); const [isBulkSubmitting, setIsBulkSubmitting] = useState(false); - const [isGeneratingPdf, setIsGeneratingPdf] = useState(false); + const [bulkLabelsOpen, setBulkLabelsOpen] = useState(false); const [isBulkSelectionEnabled, setIsBulkSelectionEnabled] = useState(false); const [isLabelDialogOpen, setIsLabelDialogOpen] = useState(false); // Items that lack e.g. a photo for the target events, and the save that waits for them @@ -104,6 +103,14 @@ export function MyProductsPage() { const products = useQuery(api.products.getMyProducts); const events = useQuery(api.events.getMyRegisteredEvents, {}); + // Bazaars where another seller's labels differ from the own ones by the letter only + const clashes = useQuery( + api.labels.getSortMarkClashes, + events?.length ? { eventIds: events.map((event) => event._id) } : 'skip' + ); + const clashingEvents = (events ?? []).filter( + (event) => event.endDate >= Date.now() && clashes?.includes(event._id) + ); const deleteProducts = useMutation(api.products.deleteProducts); const setProductEvents = useMutation(api.eventProducts.setProductEvents); const addProductToEvent = useMutation(api.eventProducts.addProductToEvent); @@ -486,25 +493,10 @@ export function MyProductsPage() { navigate('/products/new', { state: { initialEventId: filterEvent } }); }; - const handleBulkDownloadQR = async () => { - const selectedSet = new Set(selectedProducts); - const selectedIds = filteredProducts - .filter((p) => selectedSet.has(p._id) && !p.sold) - .map((p) => p._id); - if (selectedIds.length === 0) return; - setIsGeneratingPdf(true); - try { - await downloadLabelsPdf( - client, - selectedIds, - filterEvent === 'all' ? undefined : (filterEvent as Id<'events'>) - ); - } catch (e) { - toast.error(getUserFacingErrorMessage(e)); - } finally { - setIsGeneratingPdf(false); - } - }; + const selectedSet = new Set(selectedProducts); + const selectedForLabels = filteredProducts + .filter((p) => selectedSet.has(p._id) && !p.sold) + .map((p) => p._id); const selectedProductForDiscountDetails = useMemo(() => { if (!selectedProductForDiscount) return null; @@ -514,6 +506,15 @@ export function MyProductsPage() { return (
+ {clashingEvents.length > 0 && ( +

+ + {t('labels.clashAt', { bazaars: clashingEvents.map((e) => e.title).join(', ') })} +

+ )} - - - - - ); -} diff --git a/src/shared/constants.ts b/src/shared/constants.ts index 402bac93..abbe5580 100644 --- a/src/shared/constants.ts +++ b/src/shared/constants.ts @@ -25,8 +25,8 @@ export const PLACEHOLDER_PATTERN = /\[\[[^\]]+\]\]/; export const LABEL_FORMATS = ['standard', 'small'] as const; export type LabelFormat = (typeof LABEL_FORMATS)[number]; -/** What tells sellers' items apart on labels: see EventFeatures.labelMark */ -export const LABEL_MARKS = ['number', 'universal', 'none'] as const; +/** What tells sellers' items apart on labels: the lasting code or nothing, never a number of one bazaar */ +export const LABEL_MARKS = ['universal', 'none'] as const; export type LabelMark = (typeof LABEL_MARKS)[number]; export const SYSTEM_ROLES = ['admin', 'user'] as const; // leave admin always on position SYSTEM_ROLES[0]!! diff --git a/src/shared/eventFeatures.ts b/src/shared/eventFeatures.ts index ae602e1e..f5b27c65 100644 --- a/src/shared/eventFeatures.ts +++ b/src/shared/eventFeatures.ts @@ -38,9 +38,8 @@ export interface EventFeatures { /** Print the price on labels; only takes effect while discounts are off. */ priceOnLabel: boolean; /** - * The seller's mark on labels. `number`: the number at this bazaar. `universal`: a code - * that stays with the seller, read by sight (small labels only). `none`: only the QR code, - * which just links to the item. The last two can be reused at the next bazaar. + * The seller's mark on labels. `universal`: a code that stays with the seller, read by sight. + * `none`: only the QR code, which just links to the item. Both can be reused at the next bazaar. */ labelMark: LabelMark; /** Fixed fee in € per accepted item (sold or not), kept from the payout; unset means none. */ @@ -71,7 +70,7 @@ export const DEFAULT_EVENT_FEATURES: EventFeatures = { photosOptional: false, labelFormat: 'standard', priceOnLabel: false, - labelMark: 'number', + labelMark: 'universal', privateSellersOnly: false, fixedSellerData: false, }; @@ -85,6 +84,8 @@ export function resolveEventFeatures(event: { features?: StoredEventFeatures }): return { ...DEFAULT_EVENT_FEATURES, ...stored, + // Older bazaars may have stored the seller number, which labels no longer show + labelMark: stored.labelMark === 'none' ? 'none' : 'universal', maxDiscountPercent, }; } @@ -186,14 +187,6 @@ export function areOffersOpen( return listing.status === 'available' && listing.startDate <= now && now <= listing.endDate; } -/** The mark labels of this event really carry: universal ones need the small sheet. */ -export function effectiveLabelMark(event: { features?: StoredEventFeatures }): LabelMark { - const features = resolveEventFeatures(event); - return features.labelMark === 'universal' && features.labelFormat !== 'small' - ? 'number' - : features.labelMark; -} - /** Whether labels of this event show the price: a discount would make a printed price wrong. */ export function showsPriceOnLabel(event: { features?: StoredEventFeatures }): boolean { const features = resolveEventFeatures(event); diff --git a/src/shared/sortCode.test.ts b/src/shared/sortCode.test.ts index e7091533..64835118 100644 --- a/src/shared/sortCode.test.ts +++ b/src/shared/sortCode.test.ts @@ -1,37 +1,67 @@ import { describe, expect, it } from 'vitest'; -import { compareSortCodes, sortMark } from './sortCode'; - -const signature = (code: number) => { - const mark = sortMark(code); - return `${mark.digit}|${mark.fields.map((field) => field.id).join()}|${mark.letter}`; -}; +import { + SORT_COLORS, + SORT_SHAPES, + clashingSortCodes, + compareSortCodes, + sortMark, + sortMarkText, +} from './sortCode'; describe('sortMark', () => { - it('gives every seller an own mark', () => { - const marks = new Set(Array.from({ length: 30_000 }, (_, code) => signature(code + 1))); - expect(marks.size).toBe(30_000); + it('has ten colors and ten different shapes', () => { + expect(SORT_COLORS).toHaveLength(10); + expect(new Set(SORT_SHAPES.map((shape) => shape.id)).size).toBe(10); + }); + + it('never gives two sellers the same mark, also far beyond the first letter', () => { + const seen = new Set(); + for (let code = 0; code < 300_000; code++) seen.add(sortMarkText(code)); + expect(seen.size).toBe(300_000); + }); + + it('has no letter for the first 100,000 codes, then A, B, ... and never runs out', () => { + expect(sortMark(99_999).letter).toBe(''); + expect(sortMark(100_000).letter).toBe('A'); + expect(sortMark(200_000).letter).toBe('B'); + expect(sortMark(2_600_000).letter).toBe('Z'); + expect(sortMark(2_700_000).letter).toBe('AA'); }); - it('needs no letter for the first 2160 sellers', () => { - expect(sortMark(1).letter).toBe(''); - expect(sortMark(2159).letter).toBe(''); - expect(sortMark(2160).letter).toBe('A'); - expect(sortMark(2160 * 26).letter).toBe('Z'); - expect(sortMark(2160 * 27).letter).toBe('AA'); + it('takes the pile from the last digit of the code', () => { + expect(sortMark(247).pile).toBe(7); + expect(sortMark(2374).pile).toBe(4); }); - it('makes codes of one pile differ in all fields, also one after the other', () => { - const [a, b] = [sortMark(15), sortMark(25)]; - expect(a.digit).toBe(b.digit); - a.fields.forEach((field, i) => expect(field.id).not.toBe(b.fields[i].id)); + it('gives neighbors in a pile different colors and shapes in both marks', () => { + const digits = (value: number) => { + const [a, b] = sortMark(value).baskets; + return [Math.floor(a / 10), a % 10, Math.floor(b / 10), b % 10]; + }; + let shared = 0; + for (let code = 0; code < 99_990; code++) { + const next = digits(code + 10); + if (digits(code).some((digit, i) => digit === next[i])) shared++; + } + expect(shared).toBe(0); }); - it('stays the same: printed labels depend on it', () => { - expect(signature(175)).toBe('5|diamond,circle,bars|'); + it('shows the mark as text', () => { + expect(sortMarkText(247)).toBe('7 · 66 · 64'); + expect(sortMarkText(100_247)).toBe('7 · 66 · 64 A'); }); +}); + +describe('clashingSortCodes', () => { + it('finds baskets that differ by the letter only', () => { + expect(clashingSortCodes([247, 100_247, 248, 248])).toEqual(new Set([247, 100_247])); + expect(clashingSortCodes([1, 2, 3]).size).toBe(0); + }); +}); - it('sorts by digit first', () => { - const sorted = [13, 22, 31, 40].sort(compareSortCodes); - expect(sorted.map((code) => code % 10)).toEqual([0, 1, 2, 3]); +describe('compareSortCodes', () => { + it('sorts by pile, then by the marks, then by the letter', () => { + const codes = [100_247, 257, 248, 247]; + expect([...codes].sort(compareSortCodes)).toEqual([247, 100_247, 257, 248]); }); }); diff --git a/src/shared/sortCode.ts b/src/shared/sortCode.ts index 69d9ad09..5437bc09 100644 --- a/src/shared/sortCode.ts +++ b/src/shared/sortCode.ts @@ -1,44 +1,92 @@ /** - * Sorting code of universal labels. Unsold items are sorted back without reading: first - * into piles by the large digit, then by the three fields. A seller keeps the code at - * every bazaar, so printed labels stay valid. + * Sorting code of universal labels. Unsold items go back without reading: first into ten + * piles by the large field, then to the seller's basket by the two marks next to it. A + * seller keeps the code at every bazaar, so printed labels stay valid. * - * Every field has a color and its own symbol: most sellers print in black and white, and - * not every helper tells all colors apart. A letter only appears after the first 2160 - * sellers, to tell two sellers with the same digit and fields apart. + * A pile has one color, shape and digit. A basket mark is a number from 00 to 99: its tens + * give the color and its ones the shape, and the number is printed too. That makes 100,000 + * codes without any addition, and black and white prints still tell them apart by the number. + * After that a letter is added (A, B, ... Z, AA, ...), so codes never run out or repeat. */ -export interface SortSymbol { - id: 'circle' | 'triangle' | 'square' | 'diamond' | 'cross' | 'bars'; - /** Field color, also distinct for color-blind helpers (Okabe-Ito) */ - fill: [number, number, number]; - /** Color of the symbol on the field, the stronger contrast also in black and white */ - ink: [number, number, number]; -} +type Rgb = [number, number, number]; -const WHITE: [number, number, number] = [255, 255, 255]; -const BLACK: [number, number, number] = [0, 0, 0]; +const WHITE: Rgb = [255, 255, 255]; +const BLACK: Rgb = [0, 0, 0]; -export const SORT_SYMBOLS: readonly SortSymbol[] = [ - { id: 'circle', fill: [0, 114, 178], ink: WHITE }, - { id: 'triangle', fill: [230, 159, 0], ink: BLACK }, - { id: 'square', fill: [0, 120, 90], ink: WHITE }, - { id: 'diamond', fill: [240, 228, 66], ink: BLACK }, - { id: 'cross', fill: [204, 121, 167], ink: BLACK }, - { id: 'bars', fill: [30, 30, 30], ink: WHITE }, +export const SORT_COLORS: readonly { fill: Rgb; ink: Rgb }[] = [ + { fill: [17, 17, 17], ink: WHITE }, + { fill: [215, 38, 30], ink: WHITE }, + { fill: [11, 95, 196], ink: WHITE }, + { fill: [18, 133, 63], ink: WHITE }, + { fill: [255, 214, 10], ink: BLACK }, + { fill: [245, 124, 0], ink: BLACK }, + { fill: [123, 47, 181], ink: WHITE }, + { fill: [92, 200, 245], ink: BLACK }, + { fill: [242, 119, 180], ink: BLACK }, + { fill: [122, 74, 33], ink: WHITE }, ]; -const PATTERNS = SORT_SYMBOLS.length ** 3; +type Point = [number, number]; + +const arc = (from: number, to: number, steps: number): Point[] => + Array.from({ length: steps + 1 }, (_, i) => { + const angle = from + ((to - from) * i) / steps; + return [50 + 48 * Math.cos(angle), 50 + 48 * Math.sin(angle)]; + }); + +const heart: Point[] = Array.from({ length: 48 }, (_, i) => { + const t = (i / 48) * 2 * Math.PI; + return [ + 50 + 3 * 16 * Math.sin(t) ** 3, + 45 - 3 * (13 * Math.cos(t) - 5 * Math.cos(2 * t) - 2 * Math.cos(3 * t) - Math.cos(4 * t)), + ]; +}); + +/** Outlines in a box of 100 x 100, the same in the app and in the PDF. Index: the digit. */ +export const SORT_SHAPES: readonly { id: string; points: Point[] }[] = [ + { id: 'circle', points: arc(0, 2 * Math.PI, 40).slice(1) }, + { id: 'square', points: [[6, 6], [94, 6], [94, 94], [6, 94]] }, // prettier-ignore + { id: 'triangle', points: [[50, 4], [98, 94], [2, 94]] }, // prettier-ignore + { id: 'diamond', points: [[50, 1], [99, 50], [50, 99], [1, 50]] }, // prettier-ignore + { + id: 'star', + points: Array.from({ length: 10 }, (_, i) => { + const angle = -Math.PI / 2 + (i * Math.PI) / 5; + const radius = i % 2 === 0 ? 50 : 22; + return [50 + radius * Math.cos(angle), 53 + radius * Math.sin(angle)] as Point; + }), + }, + { id: 'half-circle', points: arc(Math.PI, 2 * Math.PI, 24).map(([x, y]) => [x, y + 24]) }, + { + id: 'cross', + points: [ + [33, 3], [67, 3], [67, 33], [97, 33], [97, 67], [67, 67], + [67, 97], [33, 97], [33, 67], [3, 67], [3, 33], [33, 33], + ], // prettier-ignore + }, + { id: 'heart', points: heart }, + { + id: 'arrow', + points: [[50, 3], [97, 50], [68, 50], [68, 97], [32, 97], [32, 50], [3, 50]], // prettier-ignore + }, + { id: 'hourglass', points: [[8, 4], [92, 4], [58, 50], [92, 96], [8, 96], [42, 50]] }, // prettier-ignore +]; + +/** Codes with the same pattern differ by the letter only. */ +const PATTERNS = 100_000; /** - * Walks through all patterns so that neighboring codes differ in all three fields: - * sellers who sign up one after the other are easy to tell apart. Coprime to PATTERNS. + * Walks through the basket marks so that sellers next to each other in a pile differ in the + * colors and shapes of both marks: every digit of the four changes. Coprime to 10,000. */ -const PATTERN_STEP = 121; +const BASKET_STEP = 1111; export interface SortMark { - digit: number; - fields: [SortSymbol, SortSymbol, SortSymbol]; - /** Empty for most sellers */ + /** The pile, 0 to 9: also the color and shape of the large field */ + pile: number; + /** The two basket marks, 00 to 99: tens are the color, ones the shape */ + baskets: [number, number]; + /** Empty for the first 100,000 codes */ letter: string; } @@ -51,33 +99,75 @@ function letterOf(index: number): string { } export function sortMark(code: number): SortMark { - const group = Math.floor(code / 10); - const pattern = (group * PATTERN_STEP) % PATTERNS; - const count = SORT_SYMBOLS.length; + const basket = (Math.floor(code / 10) * BASKET_STEP) % (PATTERNS / 10); return { - digit: code % 10, - fields: [ - SORT_SYMBOLS[Math.floor(pattern / count ** 2)], - SORT_SYMBOLS[Math.floor(pattern / count) % count], - SORT_SYMBOLS[pattern % count], - ], - letter: letterOf(Math.floor(group / PATTERNS)), + pile: code % 10, + baskets: [Math.floor(basket / 100), basket % 100], + letter: letterOf(Math.floor(code / PATTERNS)), }; } -/** For putting the baskets in a row in sorting order: by digit, then by the fields. */ +export const basketNumber = (basket: number) => String(basket).padStart(2, '0'); + +/** "7 · 66 · 64 A": the mark as text, for screen readers. */ +export function sortMarkText(code: number): string { + const { pile, baskets, letter } = sortMark(code); + return [`${pile} · ${baskets.map(basketNumber).join(' · ')}`, letter].filter(Boolean).join(' '); +} + +/** Baskets of a bazaar that look alike: same pattern, a different letter. */ +export function clashingSortCodes(codes: readonly number[]): Set { + const byPattern = new Map(); + for (const code of new Set(codes)) { + const pattern = code % PATTERNS; + byPattern.set(pattern, [...(byPattern.get(pattern) ?? []), code]); + } + return new Set([...byPattern.values()].filter((same) => same.length > 1).flat()); +} + +/** For putting the baskets in a row in sorting order: by pile, then by the marks. */ export function compareSortCodes(a: number, b: number): number { - const key = (code: number) => { - const mark = sortMark(code); - return [ - mark.digit, - ...mark.fields.map((field) => SORT_SYMBOLS.indexOf(field)), - mark.letter.length, - ]; + const [left, right] = [sortMark(a), sortMark(b)]; + return ( + left.pile - right.pile || + left.baskets[0] - right.baskets[0] || + left.baskets[1] - right.baskets[1] || + left.letter.length - right.letter.length || + left.letter.localeCompare(right.letter) + ); +} + +export interface SortMarkLayout { + pile: { width: number; shape: { x: number; y: number; size: number }; digitEm: number }; + baskets: { y: number; shapeX: number; numberX: number; size: number; numberEm: number }[]; + letter?: { x: number; em: number }; +} + +/** Where the parts of a mark go, in the app and in the PDF. Sizes in the unit of the box. */ +export function sortMarkLayout(mark: SortMark, width: number, height: number): SortMarkLayout { + const gap = height * 0.03; + const size = (height - gap) / 2; + const numberWidth = size * 0.72; + const letterWidth = mark.letter ? height * 0.24 * mark.letter.length : 0; + const pileWidth = width - size - numberWidth - letterWidth - gap; + const shapeSize = Math.min(height * 0.34, pileWidth * 0.7); + const shapeX = pileWidth + gap; + return { + pile: { + width: pileWidth, + shape: { x: (pileWidth - shapeSize) / 2, y: height * 0.07, size: shapeSize }, + digitEm: Math.min(height * 0.62, pileWidth * 1.3), + }, + baskets: [0, size + gap].map((y) => ({ + y, + shapeX, + numberX: shapeX + size + numberWidth / 2, + size, + // Two bold digits are about 1.15 of the font size wide + numberEm: numberWidth / 1.15, + })), + letter: mark.letter + ? { x: width - letterWidth / 2, em: Math.min(height * 0.3, letterWidth / mark.letter.length) } + : undefined, }; - const [left, right] = [key(a), key(b)]; - for (const [i, value] of left.entries()) { - if (value !== right[i]) return value - right[i]; - } - return sortMark(a).letter.localeCompare(sortMark(b).letter); } From 71d1f1a78fd9209e7638a27f3fe9494a6b5214bb Mon Sep 17 00:00:00 2001 From: Ivo Zeitz Date: Wed, 4 Nov 2026 16:53:38 +0100 Subject: [PATCH 09/14] test(account): find the digital ID by the role of the QR code The central QR component sizes itself with CSS and has no width attribute. Co-Authored-By: Claude Opus 5.5 --- src/tests/auth/profile.spec.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/tests/auth/profile.spec.ts b/src/tests/auth/profile.spec.ts index f544ca9e..8a2c6114 100644 --- a/src/tests/auth/profile.spec.ts +++ b/src/tests/auth/profile.spec.ts @@ -53,7 +53,7 @@ test.describe('profile page', () => { await page.getByRole('button', { name: 'Ausweis anzeigen' }).click(); await expect(page.getByText(/Gültig für \d+s/)).toBeVisible(); await expect(page.getByRole('button', { name: 'Jetzt aktualisieren' })).toBeVisible(); - const qrCode = page.locator('svg[width="180"][height="180"]'); + const qrCode = page.getByRole('img', { name: 'QR-Code' }); await expect(qrCode).toBeVisible(); const pathCount = await qrCode.locator('path').count(); expect(pathCount).toBeGreaterThan(0); From 6f333c91a335a7a73c96447b79e65e45ad087741 Mon Sep 17 00:00:00 2001 From: Ivo Zeitz Date: Wed, 4 Nov 2026 19:48:39 +0100 Subject: [PATCH 10/14] feat(labels): random sorting codes, cut lines and a framed mark Codes are drawn at random, so a code tells nothing about the age of an account and a new bazaar does not start at 00 00. Every label has a line to cut along, the mark has a frame that holds it together, and on large labels everything is centered. Co-Authored-By: Claude Opus 5.5 --- backend/migrations/0021_random_sort_codes.sql | 46 ++++++++++ backend/tests/api/reminders.rs | 44 +++++++++- src/components/sellers/SortMarkBadge.tsx | 40 ++++++--- src/lib/productQRCodePdf.test.ts | 11 ++- src/lib/productQRCodePdf.ts | 86 ++++++++++++------- src/lib/sortMarkPdf.ts | 31 +++---- .../components/wizard/WizardPreviews.tsx | 2 +- .../components/UniversalLabelSection.tsx | 2 +- src/shared/sortCode.test.ts | 22 ++--- src/shared/sortCode.ts | 84 ++++++++++++------ 10 files changed, 264 insertions(+), 104 deletions(-) create mode 100644 backend/migrations/0021_random_sort_codes.sql diff --git a/backend/migrations/0021_random_sort_codes.sql b/backend/migrations/0021_random_sort_codes.sql new file mode 100644 index 00000000..dd74eebe --- /dev/null +++ b/backend/migrations/0021_random_sort_codes.sql @@ -0,0 +1,46 @@ +-- A code must not tell when an account was made, and a new bazaar must not start at 00 00: +-- codes are drawn at random. A code without a letter is drawn while one is easy to find, +-- then one with the next letter (see src/shared/sortCode.ts). Codes stay unique and are +-- never given out again. No labels were printed with the numbers before. +CREATE FUNCTION assign_sort_code(seller uuid) RETURNS void LANGUAGE plpgsql AS $$ +DECLARE + patterns CONSTANT integer := 100000; + tries_per_letter CONSTANT integer := 20; + letter integer := 0; + candidate integer; +BEGIN + LOOP + FOR try IN 1..tries_per_letter LOOP + candidate := letter * patterns + floor(random() * patterns)::integer; + BEGIN + UPDATE users SET sort_code = candidate WHERE id = seller AND sort_code IS NULL; + RETURN; + EXCEPTION WHEN unique_violation THEN + NULL; -- Taken: draw again + END; + END LOOP; + letter := letter + 1; + END LOOP; +END; +$$; + +CREATE OR REPLACE FUNCTION give_sort_code() RETURNS trigger LANGUAGE plpgsql AS $$ +BEGIN + PERFORM assign_sort_code((to_jsonb(NEW) ->> TG_ARGV[0])::uuid); + RETURN NULL; +END; +$$; + +DO $$ +DECLARE + seller uuid; +BEGIN + CREATE TEMP TABLE sellers ON COMMIT DROP AS SELECT id FROM users WHERE sort_code IS NOT NULL; + UPDATE users SET sort_code = NULL; + FOR seller IN SELECT id FROM sellers LOOP + PERFORM assign_sort_code(seller); + END LOOP; +END; +$$; + +DROP SEQUENCE users_sort_code_seq; diff --git a/backend/tests/api/reminders.rs b/backend/tests/api/reminders.rs index 5ca96167..227d1699 100644 --- a/backend/tests/api/reminders.rs +++ b/backend/tests/api/reminders.rs @@ -461,10 +461,52 @@ async fn only_sellers_get_a_sort_code_and_never_the_same(db: PgPool) { let organizer = fixtures::user(&db, "Orga").await; let event = fixtures::event(&db, EventSpec::new("Basar", organizer)).await; fixtures::event_seller(&db, event, walk_in, 1, false).await; - assert!(code_of(walk_in).await.unwrap() > first); + assert_ne!(code_of(walk_in).await, Some(first)); assert_eq!(code_of(buyer).await, None); } +#[sqlx::test(migrator = "bazarpro_backend::MIGRATOR")] +async fn sort_codes_are_random_and_tell_nothing_about_the_order(db: PgPool) { + let mut codes: Vec = Vec::new(); + for i in 0..30 { + let seller = fixtures::user(&db, &format!("Seller {i}")).await; + fixtures::product(&db, seller, "Jacke", 15.0).await; + codes.push( + sqlx::query_scalar("SELECT sort_code FROM users WHERE id = $1") + .bind(seller) + .fetch_one(&db) + .await + .unwrap(), + ); + } + assert!(codes.iter().all(|code| (0..100_000).contains(code))); + // 30 draws from 100,000 are neither sorted nor all small + assert!(codes.windows(2).any(|pair| pair[0] > pair[1])); + assert!(codes.iter().any(|code| *code >= 1_000)); + let distinct: std::collections::HashSet<_> = codes.iter().collect(); + assert_eq!(distinct.len(), codes.len()); +} + +#[sqlx::test(migrator = "bazarpro_backend::MIGRATOR")] +async fn a_new_letter_starts_when_the_codes_without_one_are_taken(db: PgPool) { + // Takes all 100,000 codes without a letter by users who sell nothing + sqlx::query( + "INSERT INTO users (name, email, sort_code) + SELECT 'Filled', 'filled' || n || '@example.org', n FROM generate_series(0, 99999) n", + ) + .execute(&db) + .await + .unwrap(); + let seller = fixtures::user(&db, "Seller").await; + fixtures::product(&db, seller, "Jacke", 15.0).await; + let code: i32 = sqlx::query_scalar("SELECT sort_code FROM users WHERE id = $1") + .bind(seller) + .fetch_one(&db) + .await + .unwrap(); + assert!((100_000..200_000).contains(&code)); +} + #[sqlx::test(migrator = "bazarpro_backend::MIGRATOR")] async fn sellers_are_warned_about_the_same_pattern_at_a_bazaar(db: PgPool) { let app = TestApp::new(db.clone()); diff --git a/src/components/sellers/SortMarkBadge.tsx b/src/components/sellers/SortMarkBadge.tsx index b324fd41..93c2ec7b 100644 --- a/src/components/sellers/SortMarkBadge.tsx +++ b/src/components/sellers/SortMarkBadge.tsx @@ -45,20 +45,38 @@ export function SortMarkBadge({ code, className }: { code: number; className?: s const layout = sortMarkLayout(mark, WIDTH, HEIGHT); const { fill, ink } = SORT_COLORS[mark.pile]; const text = { fontFamily: 'Helvetica, Arial, sans-serif', fontWeight: 700 }; + const { pile } = layout; return ( - - + + + @@ -76,9 +94,9 @@ export function SortMarkBadge({ code, className }: { code: number; className?: s /> @@ -90,7 +108,7 @@ export function SortMarkBadge({ code, className }: { code: number; className?: s { expect(await downloadLabelsPdf(client, [])).toBe(0); }); - const label = (n: number) => ({ productId: id(n), title: `Teil ${n}`, sortCode: 175 }); + const label = (n: number) => ({ productId: id(n), title: `Teil ${n}`, sortCode: 88_875 }); const pages = (doc: ReturnType) => doc.getNumberOfPages(); it('starts on a free place and goes on with a new sheet', () => { @@ -72,10 +72,17 @@ describe('labels', () => { expect(pages(buildLabelsPdf(labels, 'small', -3))).toBe(1); }); + it('says where to cut in both formats', () => { + for (const format of ['small', 'standard'] as const) { + const doc = buildLabelsPdf([label(1), label(2)], format); + expect(doc.output()).toContain('Entlang der grauen Linien ausschneiden'); + } + }); + it('draws the sorting mark in both formats', () => { for (const format of ['small', 'standard'] as const) { const pdf = buildLabelsPdf([label(1)], format).output(); - // The pile and a basket mark of the code 175 + // The pile and a basket mark of the code 88875 expect(pdf).toContain('(5) Tj'); expect(pdf).toContain('(88) Tj'); } diff --git a/src/lib/productQRCodePdf.ts b/src/lib/productQRCodePdf.ts index 1dd79345..35586513 100644 --- a/src/lib/productQRCodePdf.ts +++ b/src/lib/productQRCodePdf.ts @@ -81,56 +81,74 @@ interface Cell { height: number; } -/** QR code on top, title below, then the sorting mark with size and price next to it. */ +/** Width to height of the sorting mark on labels */ +const MARK_RATIO = 18.3 / 11; + +function drawCutLines(doc: jsPDF, cell: Cell): void { + doc.setDrawColor(130); + doc.setLineWidth(0.2); + doc.rect(cell.x, cell.y, cell.width, cell.height); +} + +/** Centered from top to bottom: QR code, title, sorting mark, size and price. */ function drawStandard(doc: jsPDF, label: LabelData, cell: Cell): void { - const padding = 2; - const qrSize = Math.min(cell.width, cell.height - 20) - 4; + const padding = 2.5; + const centerX = cell.x + cell.width / 2; + const bottom = cell.y + cell.height - padding; + const info = labelInfoLine(label); + const infoHeight = info ? 5 : 0; + const markHeight = label.sortCode !== undefined ? 11.5 : 0; + const titleHeight = 8; + const qrSize = Math.min( + cell.width - 2 * padding, + cell.height - 2 * padding - titleHeight - markHeight - infoHeight + ); const qrY = cell.y + padding; - drawLabelQr(doc, labelUrl(label.productId), cell.x + (cell.width - qrSize) / 2, qrY, qrSize); + drawLabelQr(doc, labelUrl(label.productId), centerX - qrSize / 2, qrY, qrSize); - const centerX = cell.x + cell.width / 2; + doc.setTextColor(0, 0, 0); doc.setFont('helvetica', 'normal'); - doc.setFontSize(8); + doc.setFontSize(8.5); const titleLines = wrapTitle(doc, label.title, cell.width - 2 * padding, 2); + const titleY = qrY + qrSize + (titleHeight - titleLines.length * 3.5) / 2 + 2.6; titleLines.forEach((line, i) => { - doc.text(line, centerX, qrY + qrSize + 3 + i * 3.5, { align: 'center' }); + doc.text(line, centerX, titleY + i * 3.5, { align: 'center' }); }); - const rowY = qrY + qrSize + 3 + titleLines.length * 3.5 - 1.5; - const rowHeight = Math.min(cell.y + cell.height - padding - rowY, 11); - const markWidth = (rowHeight * 18.3) / 11; - const info = labelInfoLine(label); - doc.setFont('helvetica', 'bold'); - doc.setFontSize(10); if (label.sortCode !== undefined) { - drawSortMark(doc, label.sortCode, cell.x + padding, rowY, markWidth, rowHeight); + const markWidth = markHeight * MARK_RATIO; + const markY = qrY + qrSize + titleHeight; + drawSortMark(doc, label.sortCode, centerX - markWidth / 2, markY, markWidth, markHeight); + } + if (info) { + doc.setTextColor(0, 0, 0); doc.setFont('helvetica', 'bold'); doc.setFontSize(10); - if (info) doc.text(info, cell.x + padding + markWidth + 2, rowY + rowHeight / 2 + 1.2); - } else if (info) { - doc.text(info, centerX, rowY + rowHeight / 2 + 1.2, { align: 'center' }); + doc.text(info, centerX, bottom, { align: 'center' }); } + drawCutLines(doc, cell); } -/** QR code on the left, sorting mark, title and size/price on the right. */ +/** QR code on the left; sorting mark, title and size/price on the right. */ function drawSmall(doc: jsPDF, label: LabelData, cell: Cell): void { const padding = 1.5; const qrSize = cell.height - 2 * padding; drawLabelQr(doc, labelUrl(label.productId), cell.x + padding, cell.y + padding, qrSize); - const textX = cell.x + padding + qrSize + 1.5; + const textX = cell.x + padding + qrSize + 1; const textWidth = cell.x + cell.width - padding - textX; - let lineY = cell.y + padding + 4; + let lineY = cell.y + padding + 3; if (label.sortCode !== undefined) { - drawSortMark(doc, label.sortCode, textX, cell.y + padding, textWidth, 11); - lineY = cell.y + padding + 14; + const markHeight = textWidth / MARK_RATIO; + drawSortMark(doc, label.sortCode, textX, cell.y + padding, textWidth, markHeight); + lineY = cell.y + padding + markHeight + 3; } doc.setTextColor(0, 0, 0); doc.setFont('helvetica', 'normal'); doc.setFontSize(7); for (const line of wrapTitle(doc, label.title, textWidth, 2)) { doc.text(line, textX, lineY); - lineY += 3; + lineY += 2.8; } const info = labelInfoLine(label); if (info) { @@ -138,13 +156,19 @@ function drawSmall(doc: jsPDF, label: LabelData, cell: Cell): void { let size = 8; doc.setFontSize(size); while (size > 5 && doc.getTextWidth(info) > textWidth) doc.setFontSize((size -= 0.5)); - doc.text(info, textX, Math.min(lineY + 1, cell.y + cell.height - padding)); + doc.text(info, textX, cell.y + cell.height - padding - 0.3); } + drawCutLines(doc, cell); +} - // Light cut lines between the small labels - doc.setDrawColor(210); - doc.setLineWidth(0.1); - doc.rect(cell.x, cell.y, cell.width, cell.height); +/** Says below the labels where to cut. */ +function drawCutHint(doc: jsPDF): void { + doc.setTextColor(110); + doc.setFont('helvetica', 'normal'); + doc.setFontSize(7.5); + doc.text('Entlang der grauen Linien ausschneiden', PAGE_WIDTH / 2, PAGE_HEIGHT - 4, { + align: 'center', + }); } /** @@ -162,7 +186,10 @@ export function buildLabelsPdf(labels: LabelData[], format: LabelFormat, startAt const skipped = Math.min(Math.max(Math.trunc(startAt) || 1, 1), perPage) - 1; for (const [i, label] of labels.entries()) { const place = i + skipped; - if (i > 0 && place % perPage === 0) doc.addPage(); + if (i > 0 && place % perPage === 0) { + drawCutHint(doc); + doc.addPage(); + } const index = place % perPage; const cell = { x: MARGIN_MM + (index % cols) * width, @@ -173,6 +200,7 @@ export function buildLabelsPdf(labels: LabelData[], format: LabelFormat, startAt if (format === 'small') drawSmall(doc, label, cell); else drawStandard(doc, label, cell); } + drawCutHint(doc); return doc; } diff --git a/src/lib/sortMarkPdf.ts b/src/lib/sortMarkPdf.ts index b4228cb2..93afd969 100644 --- a/src/lib/sortMarkPdf.ts +++ b/src/lib/sortMarkPdf.ts @@ -26,7 +26,7 @@ function drawShape( doc.lines(deltas, x + outline[0][0] * scale, y + outline[0][1] * scale, [1, 1], style, true); } -/** The pile on the left, the two basket marks and, if any, the letter next to it. */ +/** A frame around the pile on the left, the two basket marks and, if any, the letter. */ export function drawSortMark( doc: jsPDF, code: number, @@ -38,37 +38,32 @@ export function drawSortMark( const mark = sortMark(code); const layout = sortMarkLayout(mark, width, height); const { fill, ink } = SORT_COLORS[mark.pile]; + const { pile } = layout; + + doc.setDrawColor(0, 0, 0); + doc.setLineWidth(layout.frame); + doc.roundedRect(x, y, width, height, layout.radius, layout.radius, 'S'); doc.setFillColor(...fill); - doc.rect(x, y, layout.pile.width, height, 'F'); + doc.roundedRect(x + pile.x, y + pile.y, pile.width, pile.height, pile.radius, pile.radius, 'F'); doc.setFillColor(...ink); - const { shape, digitEm } = layout.pile; - drawShape(doc, mark.pile, x + shape.x, y + shape.y, shape.size, 'F'); + drawShape(doc, mark.pile, x + pile.shape.x, y + pile.shape.y, pile.shape.size, 'F'); doc.setTextColor(...ink); doc.setFont('helvetica', 'bold'); - doc.setFontSize(points(digitEm)); - doc.text(String(mark.pile), x + layout.pile.width / 2, y + height * 0.95, { align: 'center' }); + doc.setFontSize(points(pile.digit.em)); + doc.text(String(mark.pile), x + pile.digit.x, y + pile.digit.y, { align: 'center' }); doc.setTextColor(0, 0, 0); - doc.setDrawColor(0, 0, 0); for (const [i, basket] of layout.baskets.entries()) { const value = mark.baskets[i]; doc.setFillColor(...SORT_COLORS[Math.floor(value / 10)].fill); doc.setLineWidth(basket.size * 0.03); drawShape(doc, value % 10, x + basket.shapeX, y + basket.y, basket.size, 'FD'); - doc.setFontSize(points(basket.numberEm)); - // Digits are about 0.72 of the font size high - doc.text( - basketNumber(value), - x + basket.numberX, - y + basket.y + basket.size / 2 + basket.numberEm * 0.36, - { align: 'center' } - ); + doc.setFontSize(points(basket.number.em)); + doc.text(basketNumber(value), x + basket.number.x, y + basket.number.y, { align: 'center' }); } if (layout.letter) { doc.setFontSize(points(layout.letter.em)); - doc.text(mark.letter, x + layout.letter.x, y + height / 2 + layout.letter.em * 0.36, { - align: 'center', - }); + doc.text(mark.letter, x + layout.letter.x, y + layout.letter.y, { align: 'center' }); } } diff --git a/src/pages/organizer/events/components/wizard/WizardPreviews.tsx b/src/pages/organizer/events/components/wizard/WizardPreviews.tsx index 247d7e38..243a2066 100644 --- a/src/pages/organizer/events/components/wizard/WizardPreviews.tsx +++ b/src/pages/organizer/events/components/wizard/WizardPreviews.tsx @@ -345,7 +345,7 @@ export function SalePreview({ type }: { type?: EventType }) { ); } -const EXAMPLE_SORT_CODE = 247; +const EXAMPLE_SORT_CODE = 66_647; /** The printed hang tag in the chosen format, as on the label sheet. */ function LabelPreview({ diff --git a/src/pages/public/company/components/UniversalLabelSection.tsx b/src/pages/public/company/components/UniversalLabelSection.tsx index 4a7b222a..c2572e4c 100644 --- a/src/pages/public/company/components/UniversalLabelSection.tsx +++ b/src/pages/public/company/components/UniversalLabelSection.tsx @@ -6,7 +6,7 @@ import { docsUrl } from '../../../../lib/links'; import { SectionHeading } from './MarketingHero'; /** Any code gives a realistic mark. */ -const EXAMPLE_SORT_CODE = 247; +const EXAMPLE_SORT_CODE = 66_647; const STEPS: { icon: LucideIcon; id: 'sort' | 'reuse' | 'print' }[] = [ { icon: ScanEye, id: 'sort' }, diff --git a/src/shared/sortCode.test.ts b/src/shared/sortCode.test.ts index 64835118..05ba2969 100644 --- a/src/shared/sortCode.test.ts +++ b/src/shared/sortCode.test.ts @@ -29,26 +29,18 @@ describe('sortMark', () => { }); it('takes the pile from the last digit of the code', () => { - expect(sortMark(247).pile).toBe(7); - expect(sortMark(2374).pile).toBe(4); + expect(sortMark(66_647).pile).toBe(7); + expect(sortMark(2_374).pile).toBe(4); }); - it('gives neighbors in a pile different colors and shapes in both marks', () => { - const digits = (value: number) => { - const [a, b] = sortMark(value).baskets; - return [Math.floor(a / 10), a % 10, Math.floor(b / 10), b % 10]; - }; - let shared = 0; - for (let code = 0; code < 99_990; code++) { - const next = digits(code + 10); - if (digits(code).some((digit, i) => digit === next[i])) shared++; - } - expect(shared).toBe(0); + it('reads the marks from the code, with color from the tens and shape from the ones', () => { + expect(sortMark(66_647).baskets).toEqual([66, 64]); + expect(sortMark(47_573).baskets).toEqual([47, 57]); }); it('shows the mark as text', () => { - expect(sortMarkText(247)).toBe('7 · 66 · 64'); - expect(sortMarkText(100_247)).toBe('7 · 66 · 64 A'); + expect(sortMarkText(66_647)).toBe('7 · 66 · 64'); + expect(sortMarkText(166_647)).toBe('7 · 66 · 64 A'); }); }); diff --git a/src/shared/sortCode.ts b/src/shared/sortCode.ts index 5437bc09..649b8e9c 100644 --- a/src/shared/sortCode.ts +++ b/src/shared/sortCode.ts @@ -7,6 +7,9 @@ * give the color and its ones the shape, and the number is printed too. That makes 100,000 * codes without any addition, and black and white prints still tell them apart by the number. * After that a letter is added (A, B, ... Z, AA, ...), so codes never run out or repeat. + * + * The backend draws codes at random (migration 0021), so a code tells nothing about the age + * of an account and the sellers of a bazaar spread evenly over the piles. */ type Rgb = [number, number, number]; @@ -75,11 +78,6 @@ export const SORT_SHAPES: readonly { id: string; points: Point[] }[] = [ /** Codes with the same pattern differ by the letter only. */ const PATTERNS = 100_000; -/** - * Walks through the basket marks so that sellers next to each other in a pile differ in the - * colors and shapes of both marks: every digit of the four changes. Coprime to 10,000. - */ -const BASKET_STEP = 1111; export interface SortMark { /** The pile, 0 to 9: also the color and shape of the large field */ @@ -99,7 +97,7 @@ function letterOf(index: number): string { } export function sortMark(code: number): SortMark { - const basket = (Math.floor(code / 10) * BASKET_STEP) % (PATTERNS / 10); + const basket = Math.floor(code / 10) % (PATTERNS / 10); return { pile: code % 10, baskets: [Math.floor(basket / 100), basket % 100], @@ -138,36 +136,70 @@ export function compareSortCodes(a: number, b: number): number { } export interface SortMarkLayout { - pile: { width: number; shape: { x: number; y: number; size: number }; digitEm: number }; - baskets: { y: number; shapeX: number; numberX: number; size: number; numberEm: number }[]; - letter?: { x: number; em: number }; + /** Width of the frame line around the whole mark */ + frame: number; + radius: number; + pile: { + x: number; + y: number; + width: number; + height: number; + radius: number; + shape: { x: number; y: number; size: number }; + digit: { x: number; y: number; em: number }; + }; + baskets: { + shapeX: number; + y: number; + size: number; + number: { x: number; y: number; em: number }; + }[]; + letter?: { x: number; y: number; em: number }; } /** Where the parts of a mark go, in the app and in the PDF. Sizes in the unit of the box. */ export function sortMarkLayout(mark: SortMark, width: number, height: number): SortMarkLayout { - const gap = height * 0.03; - const size = (height - gap) / 2; - const numberWidth = size * 0.72; - const letterWidth = mark.letter ? height * 0.24 * mark.letter.length : 0; - const pileWidth = width - size - numberWidth - letterWidth - gap; - const shapeSize = Math.min(height * 0.34, pileWidth * 0.7); - const shapeX = pileWidth + gap; + const frame = height * 0.022; + const inset = height * 0.07; + const inner = height - 2 * inset; + const gap = inner * 0.05; + const size = (inner - gap) / 2; + const numberWidth = size * 0.8; + const letterWidth = mark.letter ? inner * 0.24 * mark.letter.length : 0; + const pileWidth = width - 2 * inset - size - numberWidth - letterWidth - 2 * gap; + const shapeSize = Math.min(inner * 0.32, pileWidth * 0.7); + const shapeX = inset + pileWidth + 2 * gap; + const center = height / 2; + const digitEm = Math.min(inner * 0.6, pileWidth * 1.3); + // Digits are about 0.72 of the font size high return { + frame, + radius: height * 0.09, pile: { + x: inset, + y: inset, width: pileWidth, - shape: { x: (pileWidth - shapeSize) / 2, y: height * 0.07, size: shapeSize }, - digitEm: Math.min(height * 0.62, pileWidth * 1.3), + height: inner, + radius: height * 0.05, + shape: { x: inset + (pileWidth - shapeSize) / 2, y: inset + inner * 0.08, size: shapeSize }, + digit: { x: inset + pileWidth / 2, y: inset + inner * 0.94, em: digitEm }, }, - baskets: [0, size + gap].map((y) => ({ - y, - shapeX, - numberX: shapeX + size + numberWidth / 2, - size, + baskets: [inset, inset + size + gap].map((y) => { // Two bold digits are about 1.15 of the font size wide - numberEm: numberWidth / 1.15, - })), + const em = numberWidth / 1.15; + return { + shapeX, + y, + size, + number: { x: shapeX + size + numberWidth / 2, y: y + size / 2 + em * 0.36, em }, + }; + }), letter: mark.letter - ? { x: width - letterWidth / 2, em: Math.min(height * 0.3, letterWidth / mark.letter.length) } + ? { + x: width - inset - letterWidth / 2, + y: center + (inner * 0.3 * 0.72) / 2, + em: Math.min(inner * 0.3, letterWidth / mark.letter.length), + } : undefined, }; } From bbe353e26391daf7f78fd37979e18d6b3a8d233e Mon Sep 17 00:00:00 2001 From: Ivo Zeitz Date: Wed, 4 Nov 2026 20:38:00 +0100 Subject: [PATCH 11/14] feat(labels): sellers and the team print a label for the basket Sellers get a button on their items page, the team one for each seller next to the mark. The label is the sorting sheet of that basket and warns about a look-alike basket of the bazaar. Co-Authored-By: Claude Opus 5.5 --- backend/src/modules/labels.rs | 25 ++++++++++++++ backend/tests/api/reminders.rs | 25 ++++++++++++++ src/lib/api/types.ts | 5 +++ src/lib/sortSheetsPdf.test.ts | 17 ++++++++++ src/lib/sortSheetsPdf.ts | 22 ++++++++++-- src/locales/de/organizer.json | 3 +- src/locales/de/seller.json | 4 ++- src/locales/en/organizer.json | 3 +- src/locales/en/seller.json | 4 ++- .../events/dashboard/SellerManagementPage.tsx | 34 +++++++++++++++++-- src/pages/seller/products/MyProductsPage.tsx | 13 +++++++ .../components/MyProductsPageHeader.tsx | 16 ++++++++- 12 files changed, 161 insertions(+), 10 deletions(-) create mode 100644 src/lib/sortSheetsPdf.test.ts diff --git a/backend/src/modules/labels.rs b/backend/src/modules/labels.rs index 4f469ab3..62271eb5 100644 --- a/backend/src/modules/labels.rs +++ b/backend/src/modules/labels.rs @@ -24,6 +24,7 @@ const SORT_PATTERNS: i32 = 100_000; pub fn register(registry: &mut Registry) { register!(registry, Query "labels.getLabelData" => get_label_data); register!(registry, Query "labels.getSortMarkClashes" => get_sort_mark_clashes); + register!(registry, Query "labels.getMyBasketLabel" => get_my_basket_label); } #[derive(Deserialize)] @@ -190,3 +191,27 @@ async fn get_sort_mark_clashes(ctx: &mut Ctx, args: ClashArgs) -> AppResult, +} + +/// What the viewer's basket label shows; none before the first item or bazaar. +async fn get_my_basket_label(ctx: &mut Ctx, _: NoArgs) -> AppResult> { + let user = ctx.require_user()?; + ctx.read(Topic::User(user)); + let row: Option<(Option, Option)> = + sqlx::query_as("SELECT sort_code, name FROM users WHERE id = $1") + .bind(user) + .fetch_optional(ctx.conn()) + .await?; + Ok(row.and_then(|(code, name)| code.map(|sort_code| BasketLabel { sort_code, name }))) +} diff --git a/backend/tests/api/reminders.rs b/backend/tests/api/reminders.rs index 227d1699..f970d489 100644 --- a/backend/tests/api/reminders.rs +++ b/backend/tests/api/reminders.rs @@ -465,6 +465,31 @@ async fn only_sellers_get_a_sort_code_and_never_the_same(db: PgPool) { assert_eq!(code_of(buyer).await, None); } +#[sqlx::test(migrator = "bazarpro_backend::MIGRATOR")] +async fn sellers_get_their_own_basket_label(db: PgPool) { + let app = TestApp::new(db.clone()); + let seller = fixtures::user(&db, "Seller").await; + let as_seller = fixtures::session(&db, seller).await; + let label = async || { + app.query("labels.getMyBasketLabel", json!({}), Some(&as_seller)) + .await + .body["value"] + .clone() + }; + // No code before the first item + assert_eq!(label().await, Value::Null); + + fixtures::product(&db, seller, "Jacke", 15.0).await; + let code: i32 = sqlx::query_scalar("SELECT sort_code FROM users WHERE id = $1") + .bind(seller) + .fetch_one(&db) + .await + .unwrap(); + let body = label().await; + assert_eq!(body["sortCode"], code); + assert_eq!(body["name"], "Seller"); +} + #[sqlx::test(migrator = "bazarpro_backend::MIGRATOR")] async fn sort_codes_are_random_and_tell_nothing_about_the_order(db: PgPool) { let mut codes: Vec = Vec::new(); diff --git a/src/lib/api/types.ts b/src/lib/api/types.ts index 76241104..92317180 100644 --- a/src/lib/api/types.ts +++ b/src/lib/api/types.ts @@ -1707,6 +1707,11 @@ export interface Api { >; }; labels: { + getMyBasketLabel: FunctionReference< + 'query', + EmptyObject, + { sortCode: number; name?: string | undefined } | null + >; getSortMarkClashes: FunctionReference<'query', { eventIds: Id<'events'>[] }, Id<'events'>[]>; getLabelData: FunctionReference< 'query', diff --git a/src/lib/sortSheetsPdf.test.ts b/src/lib/sortSheetsPdf.test.ts new file mode 100644 index 00000000..a57b511c --- /dev/null +++ b/src/lib/sortSheetsPdf.test.ts @@ -0,0 +1,17 @@ +import { describe, expect, it } from 'vitest'; +import { buildSortSheetsPdf } from './sortSheetsPdf'; + +const NOTE = 'Achte auf den Buchstaben'; + +describe('sort sheets', () => { + it('prints two sheets per page, one for each basket', () => { + const sellers = [1, 2, 3].map((n) => ({ sortCode: n, name: `Verkäufer ${n}` })); + expect(buildSortSheetsPdf(sellers).getNumberOfPages()).toBe(2); + }); + + it('warns on a single basket label about a look-alike basket of the bazaar', () => { + const seller = { sortCode: 66_647, name: 'Anna' }; + expect(buildSortSheetsPdf([seller], NOTE).output()).not.toContain(NOTE); + expect(buildSortSheetsPdf([seller], NOTE, [66_647, 166_647]).output()).toContain(NOTE); + }); +}); diff --git a/src/lib/sortSheetsPdf.ts b/src/lib/sortSheetsPdf.ts index 6f6a65e7..f43af39f 100644 --- a/src/lib/sortSheetsPdf.ts +++ b/src/lib/sortSheetsPdf.ts @@ -13,9 +13,16 @@ export interface SortSheetSeller { sellerNumber?: number; } -/** A4 pages with two sheets each, in sorting order: one for each seller's basket. */ -export function buildSortSheetsPdf(sellers: SortSheetSeller[], clashNote = ''): jsPDF { - const clashing = clashingSortCodes(sellers.map((seller) => seller.sortCode)); +/** + * A4 pages with two sheets each, in sorting order: one for each seller's basket. `bazaarCodes`: + * all codes of the bazaar, when printing only some of its baskets. + */ +export function buildSortSheetsPdf( + sellers: SortSheetSeller[], + clashNote = '', + bazaarCodes = sellers.map((seller) => seller.sortCode) +): jsPDF { + const clashing = clashingSortCodes(bazaarCodes); const doc = new jsPDF({ orientation: 'portrait', unit: 'mm', format: 'a4' }); const sheetHeight = PAGE_HEIGHT / 2; const sorted = [...sellers].sort((a, b) => compareSortCodes(a.sortCode, b.sortCode)); @@ -52,3 +59,12 @@ export async function downloadSortSheets( ): Promise { await savePdf(buildSortSheetsPdf(sellers, clashNote), 'BazarPro-Sortierblaetter.pdf'); } + +/** The sheet for one basket, to stick on it. */ +export async function downloadBasketLabel( + seller: SortSheetSeller, + clashNote = '', + bazaarCodes?: number[] +): Promise { + await savePdf(buildSortSheetsPdf([seller], clashNote, bazaarCodes), 'BazarPro-Korb-Etikett.pdf'); +} diff --git a/src/locales/de/organizer.json b/src/locales/de/organizer.json index 349b9ba1..8fdf33e6 100644 --- a/src/locales/de/organizer.json +++ b/src/locales/de/organizer.json @@ -304,7 +304,8 @@ "noHelpers": "Noch keine Helfer. Über „Helfer hinzufügen“ ernennst du Teilnehmer zu Helfern.", "sortClash_one": "{{count}} Korb hat dasselbe Muster wie ein anderer und unterscheidet sich nur im Buchstaben.", "sortClash_other": "{{count}} Körbe haben dasselbe Muster wie ein anderer und unterscheiden sich nur im Buchstaben. Die Sortierblätter weisen darauf hin.", - "sortClashNote": "Achtung: Ein anderer Korb hat dasselbe Muster. Achte auf den Buchstaben: Etiketten ohne Buchstabe gehören in den Korb ohne Buchstabe." + "sortClashNote": "Achtung: Ein anderer Korb hat dasselbe Muster. Achte auf den Buchstaben: Etiketten ohne Buchstabe gehören in den Korb ohne Buchstabe.", + "basketLabel": "Korb-Etikett drucken" }, "settle": { "seller": "Verkäufer", diff --git a/src/locales/de/seller.json b/src/locales/de/seller.json index a296f720..7992dfee 100644 --- a/src/locales/de/seller.json +++ b/src/locales/de/seller.json @@ -198,6 +198,8 @@ "created_other": "{{count}} Etiketten erstellt", "open": "Etiketten drucken", "clash": "Achtung: Ein anderer Verkäufer bei diesem Basar hat dasselbe Muster wie du. Eure Etiketten unterscheiden sich nur im Buchstaben. Du musst nichts ändern, das Team sieht es auf den Sortierblättern. Bitte weise beim Abgeben darauf hin.", - "clashAt": "Achtung: Bei {{bazaars}} hat ein anderer Verkäufer dasselbe Muster wie du. Eure Etiketten unterscheiden sich nur im Buchstaben. Bitte weise beim Abgeben darauf hin." + "clashAt": "Achtung: Bei {{bazaars}} hat ein anderer Verkäufer dasselbe Muster wie du. Eure Etiketten unterscheiden sich nur im Buchstaben. Bitte weise beim Abgeben darauf hin.", + "basket": "Korb-Etikett drucken", + "basketHint": "Dein Sortierzeichen groß zum Aufkleben auf deinen Korb" } } diff --git a/src/locales/en/organizer.json b/src/locales/en/organizer.json index c3a6f587..b5d41766 100644 --- a/src/locales/en/organizer.json +++ b/src/locales/en/organizer.json @@ -304,7 +304,8 @@ "noHelpers": "No helpers yet. Use “Add helper” to make participants helpers.", "sortClash_one": "{{count}} basket has the same pattern as another one and differs by the letter only.", "sortClash_other": "{{count}} baskets have the same pattern as another one and differ by the letter only. The sorting sheets point this out.", - "sortClashNote": "Note: another basket has the same pattern. Check the letter: labels without a letter belong in the basket without a letter." + "sortClashNote": "Note: another basket has the same pattern. Check the letter: labels without a letter belong in the basket without a letter.", + "basketLabel": "Print basket label" }, "settle": { "seller": "Seller", diff --git a/src/locales/en/seller.json b/src/locales/en/seller.json index 42edb7e6..b328d019 100644 --- a/src/locales/en/seller.json +++ b/src/locales/en/seller.json @@ -198,6 +198,8 @@ "created_other": "{{count}} labels created", "open": "Print labels", "clash": "Note: another seller at this bazaar has the same pattern as you. Your labels differ by the letter only. You need not change anything, the team sees it on the sorting sheets. Please point it out when you hand in your items.", - "clashAt": "Note: at {{bazaars}} another seller has the same pattern as you. Your labels differ by the letter only. Please point it out when you hand in your items." + "clashAt": "Note: at {{bazaars}} another seller has the same pattern as you. Your labels differ by the letter only. Please point it out when you hand in your items.", + "basket": "Print basket label", + "basketHint": "Your sorting mark in large print to stick on your basket" } } diff --git a/src/pages/organizer/events/dashboard/SellerManagementPage.tsx b/src/pages/organizer/events/dashboard/SellerManagementPage.tsx index 6ca1c069..7ef1e2c7 100644 --- a/src/pages/organizer/events/dashboard/SellerManagementPage.tsx +++ b/src/pages/organizer/events/dashboard/SellerManagementPage.tsx @@ -1,5 +1,5 @@ import { SortMarkBadge } from '../../../../components/sellers/SortMarkBadge'; -import { downloadSortSheets } from '../../../../lib/sortSheetsPdf'; +import { downloadBasketLabel, downloadSortSheets } from '../../../../lib/sortSheetsPdf'; import { clashingSortCodes } from '../../../../shared/sortCode'; import { PageSkeleton } from '../../../../components/ui/loading'; import { PageHeader } from '../../../../components/ui/page-header'; @@ -90,6 +90,27 @@ export function SellerManagementPage() { // Baskets that differ by the letter only const clashingCodes = clashingSortCodes(sortSheetSellers.map((seller) => seller.sortCode)); + // The row opens the seller, the button only prints + const basketLabelButton = (vendor: VendorWithCalculations, sortCode: number) => ( + + ); + const addHelper = useMutation(api.eventRoles.addCoOrganizerForEvent); useAssignMissingSellerNumbers(eventId as Id<'events'>, vendors, canManage); const removeHelper = useMutation(api.eventRoles.removeCoOrganizerForEvent); @@ -265,7 +286,10 @@ export function SellerManagementPage() { {v.name} {v.sortCode !== undefined && ( - + <> + + {basketLabelButton(v, v.sortCode)} + )} {v.managedByEventId && } {v.isHelper && !isOwner && ( @@ -374,6 +398,12 @@ export function SellerManagementPage() {
{v.name} + {v.sortCode !== undefined && ( + <> + + {basketLabelButton(v, v.sortCode)} + + )} {v.managedByEventId && } {isOwner && } {v.isHelper && !isOwner && ( diff --git a/src/pages/seller/products/MyProductsPage.tsx b/src/pages/seller/products/MyProductsPage.tsx index 9bee2a53..28b1c566 100644 --- a/src/pages/seller/products/MyProductsPage.tsx +++ b/src/pages/seller/products/MyProductsPage.tsx @@ -23,6 +23,8 @@ import { import type { MyProductCardProduct } from './components/MyProductCard'; import { MyProductsGrid } from './components/MyProductsGrid'; import { MyProductsPageHeader } from './components/MyProductsPageHeader'; +import { downloadBasketLabel } from '../../../lib/sortSheetsPdf'; +import { resolveEventFeatures } from '../../../shared/eventFeatures'; import { LabelPrintDialog } from '../../../components/products/LabelPrintDialog'; import { ProductDiscountDialog } from './components/ProductDiscountDialog'; import { toast } from 'sonner'; @@ -493,6 +495,16 @@ export function MyProductsPage() { navigate('/products/new', { state: { initialEventId: filterEvent } }); }; + const basketLabel = useQuery(api.labels.getMyBasketLabel); + const printBasketLabel = + basketLabel && events?.some((event) => resolveEventFeatures(event).labelMark === 'universal') + ? () => + void downloadBasketLabel({ + sortCode: basketLabel.sortCode, + name: basketLabel.name ?? '', + }).catch((e: unknown) => toast.error(getUserFacingErrorMessage(e))) + : undefined; + const selectedSet = new Set(selectedProducts); const selectedForLabels = filteredProducts .filter((p) => selectedSet.has(p._id) && !p.sold) @@ -517,6 +529,7 @@ export function MyProductsPage() { )} !p.sold) ? () => setIsLabelDialogOpen(true) : undefined } diff --git a/src/pages/seller/products/components/MyProductsPageHeader.tsx b/src/pages/seller/products/components/MyProductsPageHeader.tsx index d2a0703e..0b11997e 100644 --- a/src/pages/seller/products/components/MyProductsPageHeader.tsx +++ b/src/pages/seller/products/components/MyProductsPageHeader.tsx @@ -1,5 +1,5 @@ import { PageHeader } from '../../../../components/ui/page-header'; -import { Plus, Printer } from 'lucide-react'; +import { Plus, Printer, ShoppingBasket } from 'lucide-react'; import { Button } from '../../../../components/ui/button'; import { useTranslation } from 'react-i18next'; @@ -11,11 +11,14 @@ interface MyProductsPageHeaderProps { onCreateProduct: () => void; /** Missing while there is nothing to label */ onPrintLabels?: () => void; + /** Missing without a sorting mark or a bazaar with universal labels */ + onPrintBasketLabel?: () => void; } export function MyProductsPageHeader({ onCreateProduct, onPrintLabels, + onPrintBasketLabel, }: MyProductsPageHeaderProps) { const { t } = useTranslation('seller'); return ( @@ -24,6 +27,17 @@ export function MyProductsPageHeader({ title={t('header.title')} actions={
+ {onPrintBasketLabel && ( + + )} {onPrintLabels && ( )} + {sellerMode === 'acceptance' && selectedVendor.sortCode !== undefined && ( +
+ + +
+ )} {sellerMode === 'acceptance' && ( - ); - const addHelper = useMutation(api.eventRoles.addCoOrganizerForEvent); useAssignMissingSellerNumbers(eventId as Id<'events'>, vendors, canManage); const removeHelper = useMutation(api.eventRoles.removeCoOrganizerForEvent); @@ -285,12 +263,6 @@ export function SellerManagementPage() {
{v.name} - {v.sortCode !== undefined && ( - <> - - {basketLabelButton(v, v.sortCode)} - - )} {v.managedByEventId && } {v.isHelper && !isOwner && ( @@ -398,12 +370,6 @@ export function SellerManagementPage() {
{v.name} - {v.sortCode !== undefined && ( - <> - - {basketLabelButton(v, v.sortCode)} - - )} {v.managedByEventId && } {isOwner && } {v.isHelper && !isOwner && ( diff --git a/src/shared/sortCode.test.ts b/src/shared/sortCode.test.ts index 05ba2969..42360cc4 100644 --- a/src/shared/sortCode.test.ts +++ b/src/shared/sortCode.test.ts @@ -1,3 +1,4 @@ +import { jsPDF } from 'jspdf'; import { describe, expect, it } from 'vitest'; import { SORT_COLORS, @@ -5,6 +6,7 @@ import { clashingSortCodes, compareSortCodes, sortMark, + sortMarkLayout, sortMarkText, } from './sortCode'; @@ -57,3 +59,48 @@ describe('compareSortCodes', () => { expect([...codes].sort(compareSortCodes)).toEqual([247, 100_247, 257, 248]); }); }); + +describe('sortMarkLayout', () => { + // Small and large labels, a sorting sheet and the badge in the app + const SIZES = [ + [18.3, 11], + [19.1, 11.5], + [180, 90], + [183, 110], + ]; + // A, W (the widest letter), AA, AAA + const LETTERED = [100_000, 2_300_000, 2_700_000, 70_300_000]; + + it('moves nothing for a letter, in any size', () => { + for (const [width, height] of SIZES) { + const { letters: none, ...plain } = sortMarkLayout(sortMark(66_647), width, height); + expect(none).toEqual([]); + for (const code of LETTERED) { + const { letters, ...lettered } = sortMarkLayout(sortMark(code + 66_647), width, height); + expect(lettered).toEqual(plain); + expect(letters).toHaveLength(sortMark(code).letter.length); + } + } + }); + + it('keeps letters inside the pile and clear of the digit, in any size', () => { + const doc = new jsPDF({ unit: 'mm' }); + doc.setFont('helvetica', 'bold'); + const pts = doc.internal.scaleFactor; + for (const [width, height] of SIZES) { + for (const code of LETTERED) { + const { pile, letters } = sortMarkLayout(sortMark(code + 66_647), width, height); + doc.setFontSize(pile.digit.em * pts); + const digitRight = pile.digit.x + doc.getTextWidth('7') / 2; + for (const { char, x, y, em } of letters) { + doc.setFontSize(em * pts); + const half = doc.getTextWidth(char) / 2; + expect(x - half).toBeGreaterThanOrEqual(digitRight); + expect(x + half).toBeLessThanOrEqual(pile.x + pile.width); + expect(y - em * 0.72).toBeGreaterThanOrEqual(pile.y); + expect(y).toBeLessThanOrEqual(pile.y + pile.height); + } + } + } + }); +}); diff --git a/src/shared/sortCode.ts b/src/shared/sortCode.ts index 649b8e9c..b102394c 100644 --- a/src/shared/sortCode.ts +++ b/src/shared/sortCode.ts @@ -154,7 +154,20 @@ export interface SortMarkLayout { size: number; number: { x: number; y: number; em: number }; }[]; - letter?: { x: number; y: number; em: number }; + /** Beside the digit, in the free space of the pile: nothing else moves for a letter */ + letters: { char: string; x: number; y: number; em: number }[]; +} + +/** Width of a bold digit and of the widest letter (W), in font sizes */ +const DIGIT_WIDTH = 0.56; +const LETTER_WIDTH = 0.95; +/** Distance of stacked letters, in font sizes */ +const LETTER_LINE = 0.85; + +/** As large as fits next to the digit, with more letters stacked as high as the digit. */ +function letterEm(digitEm: number, pileWidth: number, letters: number): number { + const beside = ((pileWidth - digitEm * DIGIT_WIDTH) / 2) * 0.9; + return Math.min(beside / LETTER_WIDTH, (digitEm * 0.85) / (letters * LETTER_LINE)); } /** Where the parts of a mark go, in the app and in the PDF. Sizes in the unit of the box. */ @@ -165,11 +178,9 @@ export function sortMarkLayout(mark: SortMark, width: number, height: number): S const gap = inner * 0.05; const size = (inner - gap) / 2; const numberWidth = size * 0.8; - const letterWidth = mark.letter ? inner * 0.24 * mark.letter.length : 0; - const pileWidth = width - 2 * inset - size - numberWidth - letterWidth - 2 * gap; + const pileWidth = width - 2 * inset - size - numberWidth - 2 * gap; const shapeSize = Math.min(inner * 0.32, pileWidth * 0.7); const shapeX = inset + pileWidth + 2 * gap; - const center = height / 2; const digitEm = Math.min(inner * 0.6, pileWidth * 1.3); // Digits are about 0.72 of the font size high return { @@ -194,12 +205,14 @@ export function sortMarkLayout(mark: SortMark, width: number, height: number): S number: { x: shapeX + size + numberWidth / 2, y: y + size / 2 + em * 0.36, em }, }; }), - letter: mark.letter - ? { - x: width - inset - letterWidth / 2, - y: center + (inner * 0.3 * 0.72) / 2, - em: Math.min(inner * 0.3, letterWidth / mark.letter.length), - } - : undefined, + letters: [...mark.letter].reverse().map((char, i) => { + const em = letterEm(digitEm, pileWidth, mark.letter.length); + return { + char, + x: inset + pileWidth - (pileWidth - digitEm * DIGIT_WIDTH) / 4, + y: inset + inner * 0.94 - i * em * LETTER_LINE, + em, + }; + }), }; } From b4fc4c1c68fbed5783f514acde7e4b1abf5945ef Mon Sep 17 00:00:00 2001 From: Ivo Zeitz Date: Wed, 4 Nov 2026 21:50:56 +0100 Subject: [PATCH 13/14] feat(labels): the team exports the labels of all sellers of a bazaar A button on the seller page opens the print dialog with all items that still need a label, seller by seller. The export asks the backend in batches and compresses the PDF, so a large bazaar fits. Co-Authored-By: Claude Opus 5.5 --- backend/src/modules/labels.rs | 28 +++++++++++ backend/tests/api/reminders.rs | 50 +++++++++++++++++++ src/lib/api/types.ts | 1 + src/lib/productQRCodePdf.test.ts | 25 +++++++++- src/lib/productQRCodePdf.ts | 33 +++++++++--- src/locales/de/organizer.json | 4 +- src/locales/en/organizer.json | 4 +- .../events/dashboard/SellerManagementPage.tsx | 23 +++++++++ 8 files changed, 157 insertions(+), 11 deletions(-) diff --git a/backend/src/modules/labels.rs b/backend/src/modules/labels.rs index 62271eb5..05a6cf7e 100644 --- a/backend/src/modules/labels.rs +++ b/backend/src/modules/labels.rs @@ -25,6 +25,7 @@ pub fn register(registry: &mut Registry) { register!(registry, Query "labels.getLabelData" => get_label_data); register!(registry, Query "labels.getSortMarkClashes" => get_sort_mark_clashes); register!(registry, Query "labels.getMyBasketLabel" => get_my_basket_label); + register!(registry, Query "labels.getEventLabelIds" => get_event_label_ids); } #[derive(Deserialize)] @@ -215,3 +216,30 @@ async fn get_my_basket_label(ctx: &mut Ctx, _: NoArgs) -> AppResult AppResult> { + let user = ctx.require_user()?; + if !has_any_role_or_admin(ctx.conn(), args.event_id.0, user, &TEAM).await? { + return Err(AppError::forbidden("auth.forbidden")); + } + ctx.read(Topic::Event(args.event_id.0)); + Ok(sqlx::query_scalar( + "SELECT p.id + FROM event_products ep + JOIN products p ON p.id = ep.product_id + JOIN users u ON u.id = p.vendor_id + WHERE ep.event_id = $1 AND ep.status IN ('announced', 'available') + ORDER BY u.sort_code, u.id, p.created_at, p.id", + ) + .bind(args.event_id.0) + .fetch_all(ctx.conn()) + .await?) +} diff --git a/backend/tests/api/reminders.rs b/backend/tests/api/reminders.rs index f970d489..9dc016b6 100644 --- a/backend/tests/api/reminders.rs +++ b/backend/tests/api/reminders.rs @@ -465,6 +465,56 @@ async fn only_sellers_get_a_sort_code_and_never_the_same(db: PgPool) { assert_eq!(code_of(buyer).await, None); } +#[sqlx::test(migrator = "bazarpro_backend::MIGRATOR")] +async fn the_team_exports_the_labels_of_all_sellers(db: PgPool) { + let app = TestApp::new(db.clone()); + let organizer = fixtures::user(&db, "Orga").await; + let first = fixtures::user(&db, "First").await; + let second = fixtures::user(&db, "Second").await; + let event = fixtures::event(&db, EventSpec::new("Basar", organizer)).await; + let other_event = fixtures::event(&db, EventSpec::new("Anderer", organizer)).await; + let item = async |seller: Uuid, target: Uuid, status: &str| { + let product = fixtures::product(&db, seller, "Teil", 5.0).await; + fixtures::event_product(&db, target, product, status).await; + product + }; + let announced = item(first, event, "announced").await; + let available = item(second, event, "available").await; + let also_first = item(first, event, "available").await; + item(first, event, "sold").await; + item(second, event, "returned").await; + item(second, other_event, "available").await; + for (seller, code) in [(first, 10), (second, 20)] { + sqlx::query("UPDATE users SET sort_code = $2 WHERE id = $1") + .bind(seller) + .bind(code) + .execute(&db) + .await + .unwrap(); + } + + let team = fixtures::session(&db, organizer).await; + let ids = app + .query( + "labels.getEventLabelIds", + json!({ "eventId": event }), + Some(&team), + ) + .await; + // Only open items of this bazaar, seller by seller + assert_eq!(ids.body["value"], json!([announced, also_first, available])); + + let as_seller = fixtures::session(&db, first).await; + let forbidden = app + .query( + "labels.getEventLabelIds", + json!({ "eventId": event }), + Some(&as_seller), + ) + .await; + assert_eq!(forbidden.body["code"], "auth.forbidden"); +} + #[sqlx::test(migrator = "bazarpro_backend::MIGRATOR")] async fn sellers_get_their_own_basket_label(db: PgPool) { let app = TestApp::new(db.clone()); diff --git a/src/lib/api/types.ts b/src/lib/api/types.ts index 48518281..f53ff083 100644 --- a/src/lib/api/types.ts +++ b/src/lib/api/types.ts @@ -1712,6 +1712,7 @@ export interface Api { EmptyObject, { sortCode: number; name?: string | undefined } | null >; + getEventLabelIds: FunctionReference<'query', { eventId: Id<'events'> }, Id<'products'>[]>; getSortMarkClashes: FunctionReference<'query', { eventIds: Id<'events'>[] }, Id<'events'>[]>; getLabelData: FunctionReference< 'query', diff --git a/src/lib/productQRCodePdf.test.ts b/src/lib/productQRCodePdf.test.ts index bf954466..9db1cfcb 100644 --- a/src/lib/productQRCodePdf.test.ts +++ b/src/lib/productQRCodePdf.test.ts @@ -60,6 +60,27 @@ describe('labels', () => { expect(await downloadLabelsPdf(client, [])).toBe(0); }); + it('asks the backend in batches, so a large bazaar fits', async () => { + const query = vi.fn(async (_fn: unknown, args: { productIds: string[] }) => ({ + format: 'small', + labels: args.productIds.map((productId) => ({ productId, title: 'Teil' })), + })); + const ids = Array.from({ length: 1201 }, (_, i) => id(i)); + expect(await downloadLabelsPdf({ query } as never, ids, 'event1' as Id<'events'>)).toBe(1201); + expect(query.mock.calls.map(([, args]) => args.productIds.length)).toEqual([500, 500, 201]); + }); + + it('compresses the labels of a whole bazaar', () => { + const labels = Array.from({ length: 80 }, (_, i) => ({ + productId: id(i), + title: `Teil ${i}`, + sortCode: 66_647, + })); + const size = (compress: boolean) => + buildLabelsPdf(labels, 'small', 1, compress).output('arraybuffer').byteLength; + expect(size(true)).toBeLessThan(size(false) / 2); + }); + const label = (n: number) => ({ productId: id(n), title: `Teil ${n}`, sortCode: 88_875 }); const pages = (doc: ReturnType) => doc.getNumberOfPages(); @@ -74,14 +95,14 @@ describe('labels', () => { it('says where to cut in both formats', () => { for (const format of ['small', 'standard'] as const) { - const doc = buildLabelsPdf([label(1), label(2)], format); + const doc = buildLabelsPdf([label(1), label(2)], format, 1, false); expect(doc.output()).toContain('Entlang der grauen Linien ausschneiden'); } }); it('draws the sorting mark in both formats', () => { for (const format of ['small', 'standard'] as const) { - const pdf = buildLabelsPdf([label(1)], format).output(); + const pdf = buildLabelsPdf([label(1)], format, 1, false).output(); // The pile and a basket mark of the code 88875 expect(pdf).toContain('(5) Tj'); expect(pdf).toContain('(88) Tj'); diff --git a/src/lib/productQRCodePdf.ts b/src/lib/productQRCodePdf.ts index 35586513..a2bb77ee 100644 --- a/src/lib/productQRCodePdf.ts +++ b/src/lib/productQRCodePdf.ts @@ -13,6 +13,9 @@ const PAGE_WIDTH = 210; const PAGE_HEIGHT = 297; const MARGIN_MM = 10; +/** MAX_LABELS in backend/src/modules/labels.rs */ +const LABELS_PER_REQUEST = 500; + /** Grid of one page: large labels (e.g. bikes) or small ones for clothes. */ export const LABEL_LAYOUTS: Record = { standard: { cols: 3, rows: 4 }, @@ -175,12 +178,17 @@ function drawCutHint(doc: jsPDF): void { * A4 pages with one label per item in the given format. `startAt`: the first free place on * a sheet that is partly used, counted from 1 row by row. */ -export function buildLabelsPdf(labels: LabelData[], format: LabelFormat, startAt = 1): jsPDF { +export function buildLabelsPdf( + labels: LabelData[], + format: LabelFormat, + startAt = 1, + compress = true +): jsPDF { const { cols, rows } = LABEL_LAYOUTS[format]; const width = (PAGE_WIDTH - 2 * MARGIN_MM) / cols; const height = (PAGE_HEIGHT - 2 * MARGIN_MM) / rows; const perPage = cols * rows; - const doc = new jsPDF({ orientation: 'portrait', unit: 'mm', format: 'a4' }); + const doc = new jsPDF({ orientation: 'portrait', unit: 'mm', format: 'a4', compress }); doc.setTextColor(0, 0, 0); const skipped = Math.min(Math.max(Math.trunc(startAt) || 1, 1), perPage) - 1; @@ -215,9 +223,20 @@ export async function downloadLabelsPdf( startAt = 1 ): Promise { if (productIds.length === 0) return 0; - const data = await client.query(api.labels.getLabelData, { productIds, eventId }); - if (data.labels.length === 0) return 0; - const doc = buildLabelsPdf(data.labels, data.format, startAt); - await savePdf(doc, 'BazarPro-Etiketten.pdf'); - return data.labels.length; + const labels: LabelData[] = []; + const formats = new Set(); + // The backend answers for a limited number of items at once + for (let i = 0; i < productIds.length; i += LABELS_PER_REQUEST) { + const data = await client.query(api.labels.getLabelData, { + productIds: productIds.slice(i, i + LABELS_PER_REQUEST), + eventId, + }); + if (data.labels.length > 0) formats.add(data.format); + labels.push(...data.labels); + } + if (labels.length === 0) return 0; + // Items of bazaars with different sheets: the large labels + const format = formats.size === 1 ? [...formats][0] : 'standard'; + await savePdf(buildLabelsPdf(labels, format, startAt), 'BazarPro-Etiketten.pdf'); + return labels.length; } diff --git a/src/locales/de/organizer.json b/src/locales/de/organizer.json index 8fdf33e6..a6cc4d32 100644 --- a/src/locales/de/organizer.json +++ b/src/locales/de/organizer.json @@ -305,7 +305,9 @@ "sortClash_one": "{{count}} Korb hat dasselbe Muster wie ein anderer und unterscheidet sich nur im Buchstaben.", "sortClash_other": "{{count}} Körbe haben dasselbe Muster wie ein anderer und unterscheiden sich nur im Buchstaben. Die Sortierblätter weisen darauf hin.", "sortClashNote": "Achtung: Ein anderer Korb hat dasselbe Muster. Achte auf den Buchstaben: Etiketten ohne Buchstabe gehören in den Korb ohne Buchstabe.", - "basketLabel": "Korb-Etikett drucken" + "basketLabel": "Korb-Etikett drucken", + "allLabels": "Alle Etiketten", + "allLabelsHint": "Die Artikel-Etiketten aller Verkäufer dieses Basars als ein PDF, Verkäufer für Verkäufer" }, "settle": { "seller": "Verkäufer", diff --git a/src/locales/en/organizer.json b/src/locales/en/organizer.json index b5d41766..c85cc924 100644 --- a/src/locales/en/organizer.json +++ b/src/locales/en/organizer.json @@ -305,7 +305,9 @@ "sortClash_one": "{{count}} basket has the same pattern as another one and differs by the letter only.", "sortClash_other": "{{count}} baskets have the same pattern as another one and differ by the letter only. The sorting sheets point this out.", "sortClashNote": "Note: another basket has the same pattern. Check the letter: labels without a letter belong in the basket without a letter.", - "basketLabel": "Print basket label" + "basketLabel": "Print basket label", + "allLabels": "All labels", + "allLabelsHint": "The item labels of all sellers of this bazaar as one PDF, seller by seller" }, "settle": { "seller": "Seller", diff --git a/src/pages/organizer/events/dashboard/SellerManagementPage.tsx b/src/pages/organizer/events/dashboard/SellerManagementPage.tsx index e00c8058..6cba4560 100644 --- a/src/pages/organizer/events/dashboard/SellerManagementPage.tsx +++ b/src/pages/organizer/events/dashboard/SellerManagementPage.tsx @@ -1,3 +1,4 @@ +import { LabelPrintDialog } from '../../../../components/products/LabelPrintDialog'; import { downloadSortSheets } from '../../../../lib/sortSheetsPdf'; import { clashingSortCodes } from '../../../../shared/sortCode'; import { PageSkeleton } from '../../../../components/ui/loading'; @@ -47,6 +48,8 @@ import { BroadcastList } from '../../../../components/broadcasts/BroadcastList'; import { HelperPickerDialog } from '../../../../components/helpers/HelperPickerDialog'; import { Trans, useTranslation } from 'react-i18next'; +const NO_LABELS: Id<'products'>[] = []; + type SellerFilter = 'all' | 'open' | 'paid' | 'helpers'; export function SellerManagementPage() { @@ -58,6 +61,11 @@ export function SellerManagementPage() { const [walkInDialogOpen, setWalkInDialogOpen] = useState(false); const [broadcastOpen, setBroadcastOpen] = useState(false); const [helperPickerOpen, setHelperPickerOpen] = useState(false); + const [allLabelsOpen, setAllLabelsOpen] = useState(false); + const allLabelIds = useQuery( + api.labels.getEventLabelIds, + allLabelsOpen ? { eventId: eventId as Id<'events'> } : 'skip' + ); // State for Helper Dialogs const [helperAction, setHelperAction] = useState<{ @@ -170,6 +178,14 @@ export function SellerManagementPage() { > {t('sellers.walkIn')} + {sortSheetSellers.length > 0 && (