diff --git a/Dockerfile b/Dockerfile index 3a69c4e5..a451385f 100644 --- a/Dockerfile +++ b/Dockerfile @@ -47,6 +47,8 @@ COPY server ./server # Code the web server shares with the app (server/dockerfile.test.ts checks the list) COPY src/lib/markdown.ts ./src/lib/markdown.ts COPY src/shared/productLinks.ts ./src/shared/productLinks.ts +COPY src/shared/appRoutes.ts ./src/shared/appRoutes.ts +COPY src/shared/eventJsonLd.ts ./src/shared/eventJsonLd.ts COPY --from=builder /app/dist ./dist USER node diff --git a/backend/migrations/0015_event_address.sql b/backend/migrations/0015_event_address.sql new file mode 100644 index 00000000..f59dbf57 --- /dev/null +++ b/backend/migrations/0015_event_address.sql @@ -0,0 +1,3 @@ +-- Address of the venue next to the free-text location (its name, e.g. "Turnhalle Nord"): +-- search engines show an event in their event results only with a postal address. +ALTER TABLE events ADD COLUMN street text, ADD COLUMN postal_code text, ADD COLUMN city text; diff --git a/backend/migrations/0016_event_country.sql b/backend/migrations/0016_event_country.sql new file mode 100644 index 00000000..73f6d913 --- /dev/null +++ b/backend/migrations/0016_event_country.sql @@ -0,0 +1,2 @@ +-- Country of the venue's address (ISO 3166-1 alpha-2, e.g. DE, AT, CH); empty is Germany. +ALTER TABLE events ADD COLUMN country text; diff --git a/backend/src/modules/docs.rs b/backend/src/modules/docs.rs index 886635cb..02e3f61e 100644 --- a/backend/src/modules/docs.rs +++ b/backend/src/modules/docs.rs @@ -141,6 +141,12 @@ pub struct Event { pub cover_image: Option, pub event_map_image: Option, pub location: String, + /// Address of the venue; `location` is its name or, in older events, all of it + pub street: Option, + pub postal_code: Option, + pub city: Option, + /// ISO 3166-1 alpha-2; none is Germany + pub country: Option, #[serde(with = "ms")] pub start_date: DateTime, #[serde(with = "ms")] @@ -181,6 +187,10 @@ struct EventRow { cover_image_id: Option, map_image_id: Option, location: String, + street: Option, + postal_code: Option, + city: Option, + country: Option, start_date: DateTime, end_date: DateTime, contact_info: String, @@ -242,6 +252,10 @@ impl From for Event { cover_image: row.cover_image_id, event_map_image: row.map_image_id, location: row.location, + street: row.street, + postal_code: row.postal_code, + city: row.city, + country: row.country, start_date: row.start_date, end_date: row.end_date, contact_info: row.contact_info, @@ -276,7 +290,8 @@ impl From for Event { /// SELECT list of the events table aliased `e`. pub const EVENT_COLUMNS: &str = "e.id, e.created_at, e.title, e.description, e.cover_image_id, - e.map_image_id, e.location, e.start_date, e.end_date, e.contact_info, + e.map_image_id, e.location, e.street, e.postal_code, e.city, e.country, + e.start_date, e.end_date, e.contact_info, ARRAY(SELECT c.category_id FROM event_categories c WHERE c.event_id = e.id ORDER BY c.position) AS categories, e.services::text[] AS services, e.visibility::text AS visibility, e.is_approved, diff --git a/backend/src/modules/events.rs b/backend/src/modules/events.rs index 659101b8..43220e24 100644 --- a/backend/src/modules/events.rs +++ b/backend/src/modules/events.rs @@ -746,6 +746,52 @@ struct Logistics { note: Option, } +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct AddressArgs { + street: Option, + postal_code: Option, + city: Option, + country: Option, +} + +/// Street, postal code and town of the venue; empty parts are stored as NULL. +struct Address { + street: Option, + postal_code: Option, + city: Option, + country: Option, +} + +/// Countries the address form offers (ISO 3166-1 alpha-2). +const COUNTRIES: [&str; 5] = ["DE", "AT", "CH", "LI", "LU"]; + +fn sanitize_address(args: Option) -> AppResult
{ + let part = |value: Option, max: usize| -> AppResult> { + let value = value.map(|v| v.trim().to_owned()).filter(|v| !v.is_empty()); + if value.as_ref().is_some_and(|v| v.chars().count() > max) { + return Err(AppError::bad_request("event.addressTooLong")); + } + Ok(value) + }; + let args = args.unwrap_or(AddressArgs { + street: None, + postal_code: None, + city: None, + country: None, + }); + let country = part(args.country, 2)?.map(|c| c.to_ascii_uppercase()); + if country.as_deref().is_some_and(|c| !COUNTRIES.contains(&c)) { + return Err(AppError::bad_request("event.countryUnknown")); + } + Ok(Address { + street: part(args.street, 200)?, + postal_code: part(args.postal_code, 10)?, + city: part(args.city, 100)?, + country, + }) +} + /// Checks the hand-in and pickup times; empty fields are dropped. fn sanitize_logistics(args: LogisticsArgs) -> AppResult { for (label, start, end) in [ @@ -857,6 +903,7 @@ struct CreateArgs { cover_image: Option, event_map_image: Option, location: String, + address: Option, start_date: f64, end_date: f64, contact_info: String, @@ -890,13 +937,15 @@ async fn create_event(ctx: &mut Ctx, args: CreateArgs) -> AppResult { .transpose()?; let logistics = args.seller_logistics.map(sanitize_logistics).transpose()?; let logistics = logistics.as_ref(); + let address = sanitize_address(args.address)?; let id: Uuid = sqlx::query_scalar( "INSERT INTO events (title, description, cover_image_id, map_image_id, location, start_date, end_date, contact_info, services, visibility, is_approved, approval_status, access_code, vendor_limit, commission, features, dropoff_start, dropoff_end, pickup_start, pickup_end, - logistics_note, organizer_id) + logistics_note, organizer_id, street, postal_code, city, country) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9::event_service[], $10::event_visibility, $11, - $12::approval_status, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22) + $12::approval_status, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23, $24, $25, + $26) RETURNING id", ) .bind(&args.title) @@ -921,6 +970,10 @@ async fn create_event(ctx: &mut Ctx, args: CreateArgs) -> AppResult { .bind(logistics.and_then(|l| l.pickup_end)) .bind(logistics.and_then(|l| l.note.clone())) .bind(user) + .bind(&address.street) + .bind(&address.postal_code) + .bind(&address.city) + .bind(&address.country) .fetch_one(ctx.conn()) .await?; set_categories(ctx, id, &args.categories).await?; @@ -941,6 +994,8 @@ struct EditArgs { cover_image: Option, event_map_image: Option, location: String, + /// Absent (older apps): the stored address stays + address: Option, start_date: f64, end_date: f64, categories: Vec, @@ -1022,6 +1077,8 @@ async fn edit_event(ctx: &mut Ctx, args: EditArgs) -> AppResult<()> { let logistics = args.seller_logistics.map(sanitize_logistics).transpose()?; let keep_logistics = logistics.is_none(); let logistics = logistics.as_ref(); + let keep_address = args.address.is_none(); + let address = sanitize_address(args.address)?; sqlx::query( "UPDATE events SET title = $2, description = $3, cover_image_id = CASE WHEN $4 THEN NULL ELSE COALESCE($5, cover_image_id) END, @@ -1037,7 +1094,11 @@ async fn edit_event(ctx: &mut Ctx, args: EditArgs) -> AppResult<()> { pickup_end = CASE WHEN $20 THEN pickup_end ELSE $24 END, logistics_note = CASE WHEN $20 THEN logistics_note ELSE $25 END, is_approved = CASE WHEN $26 THEN false ELSE is_approved END, - approval_status = CASE WHEN $26 THEN 'pending' ELSE approval_status END + approval_status = CASE WHEN $26 THEN 'pending' ELSE approval_status END, + street = CASE WHEN $27 THEN street ELSE $28 END, + postal_code = CASE WHEN $27 THEN postal_code ELSE $29 END, + city = CASE WHEN $27 THEN city ELSE $30 END, + country = CASE WHEN $27 THEN country ELSE $31 END WHERE id = $1", ) .bind(event.id) @@ -1066,6 +1127,11 @@ async fn edit_event(ctx: &mut Ctx, args: EditArgs) -> AppResult<()> { .bind(logistics.and_then(|l| l.pickup_end)) .bind(logistics.and_then(|l| l.note.clone())) .bind(making_public) + .bind(keep_address) + .bind(&address.street) + .bind(&address.postal_code) + .bind(&address.city) + .bind(&address.country) .execute(ctx.conn()) .await?; set_categories(ctx, event.id, &args.categories).await?; diff --git a/backend/tests/api/events.rs b/backend/tests/api/events.rs index 0c6cad4d..af1491ae 100644 --- a/backend/tests/api/events.rs +++ b/backend/tests/api/events.rs @@ -62,12 +62,65 @@ async fn edit_args(app: &TestApp, session: &str, id: Uuid) -> Value { }) } +async fn get_event(app: &TestApp, session: &str, id: Uuid) -> Value { + app.query("events.getEvent", json!({ "id": id }), Some(session)) + .await + .body["value"] + .clone() +} + async fn single_mode_app(db: &PgPool) -> TestApp { let mut config = Config::for_tests(""); config.mode = InstanceMode::Single; TestApp::with_config(db.clone(), config) } +#[sqlx::test(migrator = "bazarpro_backend::MIGRATOR")] +async fn the_address_is_stored_kept_by_older_apps_and_cleared(db: PgPool) { + let app = TestApp::new(db.clone()); + let organizer = fixtures::user(&db, "Orga").await; + let session = fixtures::session(&db, organizer).await; + let mut args = event_args("Kinderbasar", "logged-in"); + args["location"] = json!("Turnhalle Nord"); + args["address"] = json!({ "street": " Hauptstr. 5 ", "postalCode": "6020", "city": "Innsbruck", "country": "at" }); + let id = create(&app, &session, args).await; + let stored = get_event(&app, &session, id).await; + assert_eq!( + (&stored["street"], &stored["postalCode"], &stored["city"]), + (&json!("Hauptstr. 5"), &json!("6020"), &json!("Innsbruck")) + ); + assert_eq!(stored["country"], "AT"); + + // An app from before the address sends none: it stays + let reply = app + .mutation( + "events.editEvent", + edit_args(&app, &session, id).await, + Some(&session), + ) + .await; + assert_eq!(reply.status, StatusCode::OK, "{}", reply.body); + assert_eq!(get_event(&app, &session, id).await["city"], "Innsbruck"); + + // Empty parts clear it; an event without address leaves the fields out + let mut args = edit_args(&app, &session, id).await; + args["address"] = json!({ "street": "", "postalCode": " ", "city": null }); + let reply = app.mutation("events.editEvent", args, Some(&session)).await; + assert_eq!(reply.status, StatusCode::OK, "{}", reply.body); + let cleared = get_event(&app, &session, id).await; + assert!(cleared.get("street").is_none() && cleared.get("country").is_none()); + + for address in [ + json!({ "postalCode": "1".repeat(11) }), + json!({ "city": "Paris", "country": "FR" }), + ] { + let mut args = edit_args(&app, &session, id).await; + args["address"] = address; + let reply = app.mutation("events.editEvent", args, Some(&session)).await; + assert_eq!(reply.status, StatusCode::BAD_REQUEST, "{}", reply.body); + } +} + #[sqlx::test(migrator = "bazarpro_backend::MIGRATOR")] async fn creating_an_event_makes_the_creator_organizer(db: PgPool) { let app = TestApp::new(db.clone()); diff --git a/backend/tests/api/reminders.rs b/backend/tests/api/reminders.rs index 51eb2645..3557096e 100644 --- a/backend/tests/api/reminders.rs +++ b/backend/tests/api/reminders.rs @@ -251,6 +251,10 @@ fn pickup_text_with_a_fee_to_pay_and_a_long_item_list() { cover_image: None, event_map_image: None, location: "Halle".into(), + street: None, + postal_code: None, + city: None, + country: None, start_date: time("2026-10-17T08:00:00Z"), end_date: time("2026-10-17T12:00:00Z"), contact_info: String::new(), diff --git a/public/images/covers/bike.webp b/public/images/covers/bike.webp new file mode 100644 index 00000000..a6c77da2 Binary files /dev/null and b/public/images/covers/bike.webp differ diff --git a/public/images/covers/clothing.webp b/public/images/covers/clothing.webp new file mode 100644 index 00000000..02e9fa79 Binary files /dev/null and b/public/images/covers/clothing.webp differ diff --git a/public/images/covers/kids.webp b/public/images/covers/kids.webp new file mode 100644 index 00000000..695918c4 Binary files /dev/null and b/public/images/covers/kids.webp differ diff --git a/public/images/covers/market.webp b/public/images/covers/market.webp new file mode 100644 index 00000000..1a31c0e3 Binary files /dev/null and b/public/images/covers/market.webp differ diff --git a/public/images/covers/pattern.webp b/public/images/covers/pattern.webp new file mode 100644 index 00000000..04ce43e9 Binary files /dev/null and b/public/images/covers/pattern.webp differ diff --git a/public/images/covers/ski.webp b/public/images/covers/ski.webp new file mode 100644 index 00000000..7ff7d0c2 Binary files /dev/null and b/public/images/covers/ski.webp differ diff --git a/public/logo.png b/public/logo.png new file mode 100644 index 00000000..740d2fa4 Binary files /dev/null and b/public/logo.png differ diff --git a/scripts/event-covers/index.html b/scripts/event-covers/index.html new file mode 100644 index 00000000..d7732ec9 --- /dev/null +++ b/scripts/event-covers/index.html @@ -0,0 +1,27 @@ + + + + + + + +
+ + + diff --git a/scripts/event-covers/render.mjs b/scripts/event-covers/render.mjs new file mode 100644 index 00000000..8a7814ab --- /dev/null +++ b/scripts/event-covers/render.mjs @@ -0,0 +1,35 @@ +// Renders the scenes to public/images/covers/.webp: node scripts/event-covers/render.mjs +import { mkdirSync, writeFileSync } from 'node:fs'; +import { resolve } from 'node:path'; +import { chromium } from 'playwright'; +import { createServer } from 'vite'; + +const output = resolve('public/images/covers'); +mkdirSync(output, { recursive: true }); + +const server = await createServer({ server: { port: 5199 }, logLevel: 'error' }); +await server.listen(); +const browser = await chromium.launch(); +const page = await browser.newPage({ viewport: { width: 1600, height: 900 } }); +await page.goto('http://localhost:5199/scripts/event-covers/index.html'); +await page.waitForSelector('[data-cover]'); + +for (const cover of await page.locator('[data-cover]').all()) { + const id = await cover.getAttribute('data-cover'); + const png = (await cover.screenshot()).toString('base64'); + const webp = await page.evaluate(async (data) => { + const image = new Image(); + image.src = `data:image/png;base64,${data}`; + await image.decode(); + const canvas = document.createElement('canvas'); + canvas.width = image.width; + canvas.height = image.height; + canvas.getContext('2d').drawImage(image, 0, 0); + return canvas.toDataURL('image/webp', 0.85).split(',')[1]; + }, png); + writeFileSync(resolve(output, `${id}.webp`), Buffer.from(webp, 'base64')); + console.log(id, Math.round((webp.length * 0.75) / 1024), 'KB'); +} + +await browser.close(); +await server.close(); diff --git a/scripts/event-covers/scenes.tsx b/scripts/event-covers/scenes.tsx new file mode 100644 index 00000000..07686dc2 --- /dev/null +++ b/scripts/event-covers/scenes.tsx @@ -0,0 +1,156 @@ +/* eslint-disable react-refresh/only-export-components -- a page of its own, not hot-reloaded */ +import type { CSSProperties, ReactNode } from 'react'; +import { createRoot } from 'react-dom/client'; +import { + ItemDrawing, + type ItemDrawingId, +} from '../../src/components/illustrations/ItemIllustrations'; + +/* + * Source of the drawn cover templates in public/images/covers (see render.mjs; the others are + * photos, see src/lib/eventCovers.ts): scenes of 1600x900 + * made of the wizard's item drawings. The hero crops them to 21:9 and puts the title over + * the lower edge, so what matters stays between y 110 and 620 and x 80 and 1520. + */ + +function Item({ + id, + x, + y, + w, + rotate = 0, + filter, +}: { + id: ItemDrawingId; + x: number; + y: number; + w: number; + rotate?: number; + filter?: string; +}) { + const style: CSSProperties = { + position: 'absolute', + left: x, + top: y, + width: w, + height: w * 0.75, + transform: rotate ? `rotate(${rotate}deg)` : undefined, + filter, + }; + return ( +
+ +
+ ); +} + +function Backdrop({ children }: { children: ReactNode }) { + return ( + + {children} + + ); +} + +function SkiSlope() { + const fir = (x: number, y: number, scale: number) => ( + + + + + + ); + return ( + <> + + + + + + + + + + + + + {fir(120, 540, 1.1)} + {fir(230, 530, 0.8)} + {fir(1480, 520, 1.15)} + {fir(1370, 525, 0.75)} + + + + + + + ); +} + +function Pattern() { + const ids: ItemDrawingId[] = [ + 'jacket', + 'toyBricks', + 'skiHelmet', + 'handbag', + 'kidsClothes', + 'bikeLock', + 'ankleBoots', + 'skiBoots', + 'rainBoots', + 'kidsBike', + 'cityBike', + 'skis', + ]; + const tiles = ['#fef3c7', '#dbeafe', '#fce7f3', '#dcfce7']; + return ( + <> + {Array.from({ length: 24 }, (_, i) => { + const col = i % 6; + const row = Math.floor(i / 6); + return ( +
+
+ +
+
+ ); + })} + + ); +} + +const SCENES: Record ReactNode> = { + ski: SkiSlope, + pattern: Pattern, +}; + +function Scenes() { + return ( + <> + {Object.entries(SCENES).map(([id, Scene]) => ( +
+ +
+ ))} + + ); +} + +createRoot(document.getElementById('root')!).render(); diff --git a/server/index.test.ts b/server/index.test.ts index affb836c..e1056bfd 100644 --- a/server/index.test.ts +++ b/server/index.test.ts @@ -116,7 +116,14 @@ describe('static files', () => { const page = await get(`/P/${id.toUpperCase()}`, { redirect: 'manual' }); expect(page.response.status).toBe(301); expect(page.response.headers.get('location')).toBe(`/products/view/${id}`); - expect((await get('/p/', { redirect: 'manual' })).response.status).toBe(200); + expect((await get('/p/', { redirect: 'manual' })).response.status).toBe(404); + }); + + it('answers unknown paths with 404 and noindex, but still with the app', async () => { + const page = await get('/does-not-exist'); + expect(page.response.status).toBe(404); + expect(page.body).toContain('
'); + expect(page.body).toContain('noindex'); }); it('does not serve files outside the dist directory', async () => { diff --git a/server/index.ts b/server/index.ts index 5fb6368a..c00a8029 100644 --- a/server/index.ts +++ b/server/index.ts @@ -8,6 +8,7 @@ import { createGzip } from 'node:zlib'; import { createBackendClient, type BackendQueryClient } from './backend.ts'; import { isDynamicRoute, resolvePage, resolveSiteName, resolveSitemap } from './pages.ts'; import { isMarketingPath, parseInstanceMode, type InstanceMode } from './public-routes.ts'; +import { isAppRoute } from '../src/shared/appRoutes.ts'; import { shortProductLinkTarget } from '../src/shared/productLinks.ts'; import { injectRuntime, @@ -15,7 +16,7 @@ import { type ClientConfig, type RuntimeOptions, } from './runtime.ts'; -import { injectHead } from './seo.ts'; +import { injectHead, notFoundMeta } from './seo.ts'; /** * Production web server for the frontend. Serves the Vite build like the @@ -234,7 +235,21 @@ export async function createServer({ } // Client-side route: the SPA decides what to render - send(req, res, 200, CONTENT_TYPES['.html'], REVALIDATE, shellHtml); + if (isAppRoute(pathname)) { + send(req, res, 200, CONTENT_TYPES['.html'], REVALIDATE, shellHtml); + return; + } + + // Unknown path: the app sends visitors to the start page, search engines get a 404 + const siteName = backend ? await resolveSiteName(backend, mode) : undefined; + send( + req, + res, + 404, + CONTENT_TYPES['.html'], + REVALIDATE, + injectHead(shellHtml, notFoundMeta(siteName)) + ); } catch (err) { console.error('[server] request failed', req.url, err); if (!res.headersSent) res.writeHead(500); diff --git a/server/seo.test.ts b/server/seo.test.ts index 2870be64..d5dfbb72 100644 --- a/server/seo.test.ts +++ b/server/seo.test.ts @@ -66,6 +66,25 @@ describe('eventMeta', () => { expect(meta.title).toBe('Angebote bei Fahrradbasar in Ulm | BazarPro'); expect(meta.canonical).toBe('https://bazarpro.de/public-events/evt1/products'); expect(meta.image).toBeUndefined(); + // Both pages describe the same event; Google needs an image for event results + expect(meta.jsonLd).toMatchObject({ + url: 'https://bazarpro.de/public-events/evt1', + image: ['https://bazarpro.de/og-image.png'], + }); + }); + + it('structures the address of the venue', () => { + const meta = eventMeta( + { ...event, location: 'Turnhalle Nord, Hauptstr. 5, 89073 Ulm' }, + 'https://bazarpro.de', + 'event' + ); + expect(meta.jsonLd).toMatchObject({ + location: { + name: 'Turnhalle Nord', + address: { '@type': 'PostalAddress', postalCode: '89073', addressLocality: 'Ulm' }, + }, + }); }); it('describes the date when the event has no description', () => { diff --git a/server/seo.ts b/server/seo.ts index 0e81aa31..d56eac61 100644 --- a/server/seo.ts +++ b/server/seo.ts @@ -1,3 +1,4 @@ +import { eventJsonLd, eventTown } from '../src/shared/eventJsonLd.ts'; import { stripMarkdownToText } from '../src/lib/markdown.ts'; /** @@ -23,6 +24,10 @@ export interface PublicEvent { title: string; description?: string; location: string; + street?: string | null; + postalCode?: string | null; + city?: string | null; + country?: string | null; startDate: number; endDate: number; coverImageUrl?: string | null; @@ -39,6 +44,8 @@ export interface PublicProduct { /** Default site name; a self-hosted instance passes its association's name instead. */ export const SITE_NAME = 'BazarPro'; +/** General preview picture (public/og-image.png), like the client Seo component */ +const DEFAULT_IMAGE = '/og-image.png'; const DEFAULT_DESCRIPTION = 'Kostenlose Open-Source-Software für Kinderkleiderbasar, Fahrradbörse und Flohmarkt: QR-Etiketten, Kasse per Smartphone, automatische Abrechnung.'; @@ -76,7 +83,7 @@ export function eventMeta( ): PageMeta { const description = buildDescription( event.description, - `Event in ${event.location} am ${formatDateRange(event.startDate, event.endDate)}.` + `Event in ${eventTown(event)} am ${formatDateRange(event.startDate, event.endDate)}.` ); const eventUrl = `${siteUrl}/public-events/${event._id}`; const canonical = page === 'event' ? eventUrl : `${eventUrl}/products`; @@ -85,25 +92,25 @@ export function eventMeta( return { title: page === 'event' - ? `${event.title} in ${event.location} | ${siteName}` - : `Angebote bei ${event.title} in ${event.location} | ${siteName}`, + ? `${event.title} in ${eventTown(event)} | ${siteName}` + : `Angebote bei ${event.title} in ${eventTown(event)} | ${siteName}`, description, canonical, image, jsonLdId: page === 'event' ? `event-jsonld-${event._id}` : `event-products-jsonld-${event._id}`, - jsonLd: { - '@context': 'https://schema.org', - '@type': 'Event', - name: event.title, + jsonLd: eventJsonLd({ + title: event.title, description, - startDate: new Date(event.startDate).toISOString(), - endDate: new Date(event.endDate).toISOString(), - eventStatus: 'https://schema.org/EventScheduled', - eventAttendanceMode: 'https://schema.org/OfflineEventAttendanceMode', - location: { '@type': 'Place', name: event.location, address: event.location }, + location: event.location, + street: event.street, + postalCode: event.postalCode, + city: event.city, + country: event.country, + startDate: event.startDate, + endDate: event.endDate, url: eventUrl, - ...(image ? { image: [image] } : {}), - }, + image: image ?? `${siteUrl}${DEFAULT_IMAGE}`, + }), }; } diff --git a/src/App.tsx b/src/App.tsx index 6959d722..86b706ec 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -1,6 +1,6 @@ import './styles/App.css'; import { useAuthState, useQuery, useAuthActions } from './lib/api/react'; -import { useEffect } from 'react'; +import { Suspense, useEffect } from 'react'; import { BrowserRouter as Router, Routes, @@ -15,28 +15,20 @@ import { LoginPage } from './pages/public/auth/LoginPage'; import { ThemeProvider } from './components/ui/theme-provider'; import { Toaster } from 'sonner'; import { RegisterPage } from './pages/public/auth/RegisterPage'; -import { MyProductsPage } from './pages/seller/products/MyProductsPage'; -import { MySalesPage } from './pages/seller/sales/MySalesPage'; -import { ProductForm } from './pages/seller/products/ProductForm'; import { PublicProduct } from './pages/public/products/PublicProduct'; import { ShortProductLink } from './pages/public/products/ShortProductLink'; -import { EventManagementDashboard } from './pages/organizer/events/EventManagementDashboard'; -import { SettingsPage } from './pages/organizer/events/dashboard/SettingsPage'; import { UserRoleProvider } from './context/UserRoleProvider'; import { NavigationHistoryProvider } from './context/NavigationHistoryProvider'; import { LandingPage } from './pages/public/landing/LandingPage'; import { HomePage } from './pages/dashboard/HomePage'; import { CurrentBazaarRedirect, InstanceHomePage } from './pages/public/instance/InstanceHomePage'; -import { EditEventForm } from './pages/organizer/events/EditEventForm'; import { PublicEventLanding } from './pages/public/events/PublicEventPage'; import { PublicEventProductsPage } from './pages/public/events/PublicEventProductsPage'; -import { SearchEventsPage } from './pages/seller/events/SearchEventsPage'; import { FeaturesPage } from './pages/public/company/FeaturesPage'; import { PricingPage } from './pages/public/company/PricingPage'; import { AboutPage } from './pages/public/company/AboutPage'; import { ContactPage } from './pages/public/company/ContactPage'; import { LegalPage } from './pages/public/legal/LegalPage'; -import { AccountPage } from './pages/account/AccountPage'; import { UnsubscribePage } from './pages/public/notifications/UnsubscribePage'; import { useTheme } from './components/ui/theme-context'; import { ResponsiveSidebar } from './components/layout/ResponsiveSidebar'; @@ -47,20 +39,6 @@ import { Header } from './components/layout/Header'; import { SidebarProvider } from './context/SidebarProvider'; import { OnboardingProvider } from './context/OnboardingContext'; import { OnboardingOverlay } from './components/onboarding/OnboardingOverlay'; -import { AdminPage } from './pages/administrator/AdminPage'; -import { AdminUsersPage } from './pages/administrator/AdminUsersPage'; -import { AdminEventsPage } from './pages/administrator/AdminEventsPage'; -import { AdminOverviewPage } from './pages/administrator/AdminOverviewPage'; -import { AdminReportsPage } from './pages/administrator/AdminReportsPage'; -import { AdminContentPage } from './pages/administrator/AdminContentPage'; -import { AdminMessagesPage } from './pages/administrator/AdminMessagesPage'; -import { AdminLogPage } from './pages/administrator/AdminLogPage'; -import { AdminSettingsPage } from './pages/administrator/AdminSettingsPage'; -import { AdminLegalPagesPage } from './pages/administrator/AdminLegalPagesPage'; -import { SellerManagementPage } from './pages/organizer/events/dashboard/SellerManagementPage'; -import { ProductManagementPage } from './pages/organizer/events/dashboard/ProductManagementPage'; -import { CashReconciliationPage } from './pages/organizer/events/dashboard/CashReconciliationPage'; -import { CheckoutPage } from './pages/organizer/events/dashboard/CheckoutPage'; import { api } from './lib/api/functions'; import { loginPath } from './lib/loginRedirect'; import { runtimeConfig } from './lib/runtimeConfig'; @@ -69,6 +47,82 @@ import { useTranslation } from 'react-i18next'; import { Capacitor } from '@capacitor/core'; import { WELCOME_PATH } from './native/settings'; import { PageSkeleton } from './components/ui/loading'; +import { lazyPage, preloadPages } from './lib/lazyPage'; + +// Pages behind the sign-in: own chunks, so the public pages load faster +const MyProductsPage = lazyPage( + () => import('./pages/seller/products/MyProductsPage'), + 'MyProductsPage' +); +const MySalesPage = lazyPage(() => import('./pages/seller/sales/MySalesPage'), 'MySalesPage'); +const ProductForm = lazyPage(() => import('./pages/seller/products/ProductForm'), 'ProductForm'); +const EventManagementDashboard = lazyPage( + () => import('./pages/organizer/events/EventManagementDashboard'), + 'EventManagementDashboard' +); +const SettingsPage = lazyPage( + () => import('./pages/organizer/events/dashboard/SettingsPage'), + 'SettingsPage' +); +const EditEventForm = lazyPage( + () => import('./pages/organizer/events/EditEventForm'), + 'EditEventForm' +); +const SearchEventsPage = lazyPage( + () => import('./pages/seller/events/SearchEventsPage'), + 'SearchEventsPage' +); +const AccountPage = lazyPage(() => import('./pages/account/AccountPage'), 'AccountPage'); +const AdminPage = lazyPage(() => import('./pages/administrator/AdminPage'), 'AdminPage'); +const AdminUsersPage = lazyPage( + () => import('./pages/administrator/AdminUsersPage'), + 'AdminUsersPage' +); +const AdminEventsPage = lazyPage( + () => import('./pages/administrator/AdminEventsPage'), + 'AdminEventsPage' +); +const AdminOverviewPage = lazyPage( + () => import('./pages/administrator/AdminOverviewPage'), + 'AdminOverviewPage' +); +const AdminReportsPage = lazyPage( + () => import('./pages/administrator/AdminReportsPage'), + 'AdminReportsPage' +); +const AdminContentPage = lazyPage( + () => import('./pages/administrator/AdminContentPage'), + 'AdminContentPage' +); +const AdminMessagesPage = lazyPage( + () => import('./pages/administrator/AdminMessagesPage'), + 'AdminMessagesPage' +); +const AdminLogPage = lazyPage(() => import('./pages/administrator/AdminLogPage'), 'AdminLogPage'); +const AdminSettingsPage = lazyPage( + () => import('./pages/administrator/AdminSettingsPage'), + 'AdminSettingsPage' +); +const AdminLegalPagesPage = lazyPage( + () => import('./pages/administrator/AdminLegalPagesPage'), + 'AdminLegalPagesPage' +); +const SellerManagementPage = lazyPage( + () => import('./pages/organizer/events/dashboard/SellerManagementPage'), + 'SellerManagementPage' +); +const ProductManagementPage = lazyPage( + () => import('./pages/organizer/events/dashboard/ProductManagementPage'), + 'ProductManagementPage' +); +const CashReconciliationPage = lazyPage( + () => import('./pages/organizer/events/dashboard/CashReconciliationPage'), + 'CashReconciliationPage' +); +const CheckoutPage = lazyPage( + () => import('./pages/organizer/events/dashboard/CheckoutPage'), + 'CheckoutPage' +); function PublicEventWrapper() { const { eventId } = useParams(); @@ -113,6 +167,21 @@ function landingPage() { return isSingleInstance ? : ; } +/** Signed in: loads the remaining pages while idle, they then also open without connection. */ +function PreloadSignedInPages() { + const { isAuthenticated } = useAuthState(); + useEffect(() => { + if (!isAuthenticated) return; + if (typeof window.requestIdleCallback === 'function') { + const id = window.requestIdleCallback(preloadPages, { timeout: 5000 }); + return () => window.cancelIdleCallback(id); + } + const timer = setTimeout(preloadPages, 2000); + return () => clearTimeout(timer); + }, [isAuthenticated]); + return null; +} + /** Takes over the language saved at the account after login. */ function AccountLocaleSync() { useSyncAccountLocale(); @@ -126,6 +195,7 @@ function App() { + @@ -176,6 +246,22 @@ function App() { element={} /> + {/* Visitors try the creation wizard before signing up (platform only) */} + + + + ) : ( + }> + + + ) + } + /> + }> } /> - } /> } /> + + + ); +} + +/** Pages behind the sign-in: visitors go to the login and come back afterwards. */ +function RequireSignIn({ children }: { children: React.ReactNode }) { const location = useLocation(); const { isAuthenticated, isLoading } = useAuthState(); const { signOut } = useAuthActions(); @@ -262,7 +356,7 @@ function PrivateMainAppContent() { return ; } - return ; + return }>{children}; } export default App; diff --git a/src/assets/landing-page-hero.jpg b/src/assets/landing-page-hero.jpg deleted file mode 100644 index c11a5e81..00000000 Binary files a/src/assets/landing-page-hero.jpg and /dev/null differ diff --git a/src/components/auth/PasswordInput.tsx b/src/components/auth/PasswordInput.tsx new file mode 100644 index 00000000..7be33516 --- /dev/null +++ b/src/components/auth/PasswordInput.tsx @@ -0,0 +1,28 @@ +import { Eye, EyeOff } from 'lucide-react'; +import { useState, type ComponentProps } from 'react'; +import { useTranslation } from 'react-i18next'; +import { cn } from '../utils'; +import { Input } from '../ui/input'; + +/** + * Password field with a button to show what was typed: instead of a second field to + * repeat the password. Takes the props of Input, also `register(...)` of react-hook-form. + */ +export function PasswordInput({ className, ...props }: Omit, 'type'>) { + const { t } = useTranslation('auth'); + const [shown, setShown] = useState(false); + return ( +
+ + +
+ ); +} diff --git a/src/components/illustrations/ItemIllustrations.tsx b/src/components/illustrations/ItemIllustrations.tsx new file mode 100644 index 00000000..7b9583a1 --- /dev/null +++ b/src/components/illustrations/ItemIllustrations.tsx @@ -0,0 +1,614 @@ +import type { ReactNode } from 'react'; +import { BikeIllustration } from '../../pages/public/landing/components/demo/Illustrations'; +import { cn } from '../utils'; + +/* + * Drawn items for the creation wizard and the landing page: what sellers bring to each + * kind of bazaar. SVG like the bike of the landing page, so they scale, stay license-free + * and look the same in both themes (they sit on a light backdrop). Every drawing uses the + * same 200x150 box with the item centered, so they line up at any size. + */ + +export type ItemKind = 'kids' | 'clothing' | 'ski' | 'bike'; + +export type ItemDrawingId = + | 'kidsClothes' + | 'toyBricks' + | 'rainBoots' + | 'jacket' + | 'ankleBoots' + | 'handbag' + | 'skis' + | 'skiBoots' + | 'skiHelmet' + | 'cityBike' + | 'kidsBike' + | 'bikeLock'; + +/** The three example items of each kind, in the order of eventTypes..exampleItems. */ +const KIND_ITEMS: Record = { + kids: ['kidsClothes', 'toyBricks', 'rainBoots'], + clothing: ['jacket', 'ankleBoots', 'handbag'], + ski: ['skis', 'skiBoots', 'skiHelmet'], + bike: ['cityBike', 'kidsBike', 'bikeLock'], +}; + +const INK = '#27272a'; + +function Svg({ children, className }: { children: ReactNode; className?: string }) { + return ( + + ); +} + +/** A striped children's T-shirt and denim dungarees with bib pocket and rolled-up legs. */ +function KidsClothes() { + return ( + <> + {/* T-shirt: sloping shoulders, sleeves angled out and down, wide body */} + + {[76, 88, 100].map((y) => ( + + ))} + + + + {/* dungarees */} + + + + + + + + + + + + ); +} + +// Isometric projection for the building bricks: one stud is U wide +const U = 12; +const ISO_X = 0.866; +function iso(ox: number, oy: number, i: number, j: number, k: number): string { + return `${ox + (i - j) * ISO_X * U},${oy + (i + j) * 0.5 * U - k}`; +} + +/** One building brick in isometric view: top and two sides, studs as small cylinders. */ +function IsoBrick({ + ox, + oy, + w, + d, + colors, +}: { + ox: number; + oy: number; + w: number; + d: number; + colors: [top: string, left: string, right: string]; +}) { + const h = 11; + const [top, left, right] = colors; + const studs = []; + for (let j = 0; j < d; j++) { + for (let i = 0; i < w; i++) studs.push([i + 0.5, j + 0.5]); + } + studs.sort((a, b) => a[0] + a[1] - (b[0] + b[1])); + return ( + + + + + {studs.map(([i, j]) => { + const [cx, cy] = iso(ox, oy, i, j, h).split(',').map(Number); + const rx = 3.3; + const ry = 1.9; + return ( + + + + + ); + })} + + ); +} + +const RED: [string, string, string] = ['#f87171', '#dc2626', '#b91c1c']; +const YELLOW: [string, string, string] = ['#fde047', '#eab308', '#ca8a04']; +const BLUE: [string, string, string] = ['#60a5fa', '#2563eb', '#1d4ed8']; +const GREEN: [string, string, string] = ['#4ade80', '#16a34a', '#15803d']; + +/** Building bricks: a stack of three and two loose ones, back to front. */ +function ToyBricks() { + return ( + <> + + + + + + + + ); +} + +/** One children's rubber boot, toe to the left: shaft, rounded toe, thin sole on the foot. */ +function RubberBoot({ x, y }: { x: number; y: number }) { + const fill = '#ef4444'; + const shade = '#b91c1c'; + return ( + + + + {[ + [40, 28], + [58, 38], + [42, 50], + [60, 62], + [22, 76], + [44, 76], + ].map(([cx, cy]) => ( + + ))} + + + ); +} + +/** A pair of children's rubber boots with white dots. */ +function RainBoots() { + return ( + <> + + + + ); +} + +/** A zipped jacket laid flat: stand-up collar, sleeves with cuffs, pockets. */ +function Jacket() { + return ( + <> + {/* sleeves */} + + + + + {/* body */} + + {/* collar */} + + + + + + + ); +} + +/** + * One women's ankle boot, toe to the left, in a 90x90 box: the foot slopes down from the + * heel to the toe, zip on the side, thin sole along the foot and a block heel. + */ +function AnkleBoot({ x, y }: { x: number; y: number }) { + const fill = '#b45309'; + const shade = '#78350f'; + return ( + + {/* block heel */} + + {/* upper */} + + {/* zip */} + + + + {/* thin sole */} + + + ); +} + +/** A pair of women's ankle boots. */ +function AnkleBoots() { + return ( + <> + + + + ); +} + +/** A leather handbag with two handles and a flap. */ +function Handbag() { + return ( + <> + + + + + + + + ); +} + +/** One ski from above, tip at the top, with toe and heel piece of the binding. 14x132. */ +function Ski() { + return ( + + + + + {/* binding: toe piece, heel piece with brake arms */} + + + + + + + ); +} + +/** One ski pole from grip to tip: grip, strap, shaft, basket. */ +function Pole({ from, to }: { from: [number, number]; to: [number, number] }) { + const [x1, y1] = from; + const [x2, y2] = to; + const at = (t: number): [number, number] => [x1 + (x2 - x1) * t, y1 + (y2 - y1) * t]; + const angle = (Math.atan2(y2 - y1, x2 - x1) * 180) / Math.PI - 90; + const [bx, by] = at(0.88); + const [gx, gy] = at(0.1); + return ( + + + + + + + + ); +} + +/** A pair of skis leaning in an A, the poles next to them. */ +function Skis() { + return ( + <> + + + + + + + + + + ); +} + +/** + * A ski boot, toe to the left: forward-leaning black cuff over the shell, buckles lying on + * the front, power strap at the top and a sole with lips at toe and heel. + */ +function SkiBoots() { + const buckle = (x: number, y: number, angle: number) => ( + + + + + ); + return ( + <> + {/* liner and tongue */} + + {/* lower shell */} + + + {/* cuff, leaning forward */} + + + + {buckle(88, 46, -18)} + {buckle(94, 66, -18)} + {buckle(74, 92, -22)} + {/* sole with lips */} + + + + ); +} + +/** A ski helmet from the side: shell down over the ears, ear pad, chin strap, goggles. */ +function SkiHelmet() { + return ( + <> + + + + + + + + {/* goggles on the front, strap around the shell */} + + + + + ); +} + +/** A children's bike with training wheel: proper frame, fork, chain guard. */ +function KidsBike() { + const wheel = (cx: number) => ( + + + + {[0, 45, 90, 135].map((a) => { + const r = (a * Math.PI) / 180; + return ( + + ); + })} + + + ); + return ( + <> + {wheel(54)} + {wheel(146)} + {/* training wheel on the rear axle */} + + + + {/* chain and seat stays, seat tube, top tube, down tube, fork */} + + + + + + + + + + + + ); +} + +/** A U-lock: thin coated steel shackle, thick crossbar with lock cylinder, keys on a ring. */ +function BikeLock() { + return ( + <> + + + + + + + + {/* keys */} + + + + + ); +} + +const DRAWINGS: Record, () => ReactNode> = { + kidsClothes: KidsClothes, + toyBricks: ToyBricks, + rainBoots: RainBoots, + jacket: Jacket, + ankleBoots: AnkleBoots, + handbag: Handbag, + skis: Skis, + skiBoots: SkiBoots, + skiHelmet: SkiHelmet, + kidsBike: KidsBike, + bikeLock: BikeLock, +}; + +/** One item, drawn in the shared 200x150 box. */ +export function ItemDrawing({ id, className }: { id: ItemDrawingId; className?: string }) { + // The old city bike of the landing page story has its own, slightly wider box + if (id === 'cityBike') return ; + const Drawing = DRAWINGS[id]; + return ( + + + + ); +} + +const BACKDROPS: Record = { + kids: 'from-amber-100 via-orange-50 to-rose-100', + clothing: 'from-rose-100 via-stone-50 to-emerald-100', + ski: 'from-sky-200 via-white to-slate-200', + bike: 'from-sky-200 via-sky-100 to-stone-300', +}; + +/** + * An item as a "photo" on the light backdrop of its kind: `item` picks one of the three + * examples; without it the three are arranged like a group shot (cards, page headers). + */ +export function ItemPhoto({ + kind, + item, + className, +}: { + kind: ItemKind; + item?: 0 | 1 | 2; + className?: string; +}) { + const [main, second, third] = KIND_ITEMS[kind]; + return ( +
+ {item !== undefined ? ( + + ) : ( +
+ + + +
+ )} +
+ ); +} diff --git a/src/components/seo/Seo.tsx b/src/components/seo/Seo.tsx index 82966a0a..b40868c4 100644 --- a/src/components/seo/Seo.tsx +++ b/src/components/seo/Seo.tsx @@ -1,14 +1,12 @@ import { useEffect } from 'react'; import { buildSeoDescription, + DEFAULT_SEO_IMAGE, getDefaultDescription, getDefaultSiteName, toAbsoluteUrl, } from '../../lib/seo'; -/** Preview image for links shared on social media and in search results */ -const DEFAULT_IMAGE = '/og-image.png'; - type JsonLd = Record | Record[]; interface SeoProps { @@ -75,7 +73,7 @@ export function Seo({ title, description, canonical, - image = DEFAULT_IMAGE, + image = DEFAULT_SEO_IMAGE, type = 'website', jsonLd, jsonLdId = 'seo-jsonld', diff --git a/src/components/ui/ImageUpload.tsx b/src/components/ui/ImageUpload.tsx index d801e447..aac5d968 100644 --- a/src/components/ui/ImageUpload.tsx +++ b/src/components/ui/ImageUpload.tsx @@ -8,6 +8,8 @@ import { useTranslation } from 'react-i18next'; interface ImageUploadProps { onFilesChange: (files: File[]) => void; initialImageUrls?: string[]; + /** Files chosen before, e.g. when a step of a wizard is opened again */ + initialFiles?: File[]; onRemoveExistingImage?: (index: number) => void; maxFiles?: number; accept?: Accept; @@ -19,12 +21,13 @@ const NO_IMAGE_URLS: string[] = []; export function ImageUpload({ onFilesChange, initialImageUrls = NO_IMAGE_URLS, + initialFiles, onRemoveExistingImage, maxFiles = 3, accept = { 'image/*': ['.jpeg', '.jpg', '.png', '.webp'] }, }: ImageUploadProps) { const { t } = useTranslation(); - const [files, setFiles] = useState([]); + const [files, setFiles] = useState(initialFiles ?? []); const [rejected, setRejected] = useState([]); const [processingError, setProcessingError] = useState(null); const [displayedInitialImageUrls, setDisplayedInitialImageUrls] = diff --git a/src/lib/api/types.ts b/src/lib/api/types.ts index a771487c..eaf0ea9a 100644 --- a/src/lib/api/types.ts +++ b/src/lib/api/types.ts @@ -123,6 +123,11 @@ export interface Docs { title: string; description: string; location: string; + /** Address of the venue; `location` is its name or, in older events, all of it */ + street?: string | undefined; + postalCode?: string | undefined; + city?: string | undefined; + country?: string | undefined; startDate: number; endDate: number; contactInfo: string; @@ -991,6 +996,10 @@ export interface Api { title: string; description: string; location: string; + street?: string | undefined; + postalCode?: string | undefined; + city?: string | undefined; + country?: string | undefined; startDate: number; endDate: number; contactInfo: string; @@ -1054,6 +1063,10 @@ export interface Api { title: string; description: string; location: string; + street?: string | undefined; + postalCode?: string | undefined; + city?: string | undefined; + country?: string | undefined; startDate: number; endDate: number; contactInfo: string; @@ -1119,6 +1132,10 @@ export interface Api { title: string; description: string; location: string; + street?: string | undefined; + postalCode?: string | undefined; + city?: string | undefined; + country?: string | undefined; startDate: number; endDate: number; contactInfo: string; @@ -1184,6 +1201,10 @@ export interface Api { title: string; description: string; location: string; + street?: string | undefined; + postalCode?: string | undefined; + city?: string | undefined; + country?: string | undefined; startDate: number; endDate: number; contactInfo: string; @@ -1257,6 +1278,10 @@ export interface Api { title: string; description: string; location: string; + street?: string | undefined; + postalCode?: string | undefined; + city?: string | undefined; + country?: string | undefined; startDate: number; endDate: number; contactInfo: string; @@ -1323,6 +1348,10 @@ export interface Api { title: string; description: string; location: string; + street?: string | undefined; + postalCode?: string | undefined; + city?: string | undefined; + country?: string | undefined; startDate: number; endDate: number; contactInfo: string; @@ -1386,6 +1415,10 @@ export interface Api { title: string; description: string; location: string; + street?: string | undefined; + postalCode?: string | undefined; + city?: string | undefined; + country?: string | undefined; startDate: number; endDate: number; contactInfo: string; @@ -1434,6 +1467,9 @@ export interface Api { title: string; description: string; location: string; + address?: + | { street?: string; postalCode?: string; city?: string; country?: string } + | undefined; startDate: number; endDate: number; contactInfo: string; @@ -1485,6 +1521,9 @@ export interface Api { title: string; description: string; location: string; + address?: + | { street?: string; postalCode?: string; city?: string; country?: string } + | undefined; startDate: number; endDate: number; contactInfo: string; @@ -1549,6 +1588,10 @@ export interface Api { title: string; description: string; location: string; + street?: string | undefined; + postalCode?: string | undefined; + city?: string | undefined; + country?: string | undefined; startDate: number; endDate: number; contactInfo: string; @@ -2617,6 +2660,10 @@ export interface Api { title: string; description: string; location: string; + street?: string | undefined; + postalCode?: string | undefined; + city?: string | undefined; + country?: string | undefined; startDate: number; endDate: number; createdAt: number; diff --git a/src/lib/eventCovers.ts b/src/lib/eventCovers.ts new file mode 100644 index 00000000..5ff1ef98 --- /dev/null +++ b/src/lib/eventCovers.ts @@ -0,0 +1,28 @@ +import type { ItemKind } from '../components/illustrations/ItemIllustrations'; + +/* + * Cover templates of the creation wizard (public/images/covers). Choosing one needs no + * account: only the id waits in the draft, the picture is uploaded like an own one when + * the bazaar is created. + * + * Drawn, source in scripts/event-covers: ski, pattern. Photos from Unsplash (free to use), + * the same ones as in the demo data: kids photo-1596461404969-9ae70f2830c1, + * clothing photo-1470309864661-68328b2cd0a5, bike photo-1485965120184-e220f721d03e, + * market photo-1558060370-d644479cb6f7. + */ + +export const EVENT_COVERS = ['kids', 'clothing', 'ski', 'bike', 'market', 'pattern'] as const; +export type EventCoverId = (typeof EVENT_COVERS)[number]; + +/** Without a kind of bazaar: the one that fits every bazaar. */ +export const DEFAULT_COVER: EventCoverId = 'market'; + +export const coverForKind = (kind: ItemKind): EventCoverId => kind; + +export const coverUrl = (id: string) => `/images/covers/${id}.webp`; + +export async function coverFile(id: string): Promise { + const response = await fetch(coverUrl(id)); + if (!response.ok) throw new Error(`Cover template ${id}: ${response.status}`); + return new File([await response.blob()], `${id}.webp`, { type: 'image/webp' }); +} diff --git a/src/lib/eventDraft.ts b/src/lib/eventDraft.ts new file mode 100644 index 00000000..dfc98056 --- /dev/null +++ b/src/lib/eventDraft.ts @@ -0,0 +1,53 @@ +/** + * A bazaar set up in the creation wizard before signing up. It waits in this browser + * until the account exists; the wizard then creates it (src/pages/organizer/events/ + * EditEventForm.tsx). Pictures are not kept: they are added once the bazaar exists. + */ + +const KEY = 'bazarpro.eventDraft'; +const MAX_AGE_MS = 14 * 24 * 3600 * 1000; + +/** Where the wizard creates the waiting draft after sign-up. */ +export const CREATE_DRAFT_PATH = '/events/new?draft=1'; + +export interface EventDraft { + values: Values; + pendingLocationCategories: string[]; + eventType?: string; + savedAt: number; +} + +export function saveEventDraft(draft: Omit, 'savedAt'>) { + try { + // Empty number fields hold NaN, which JSON would turn into null: leave them out + const json = JSON.stringify({ ...draft, savedAt: Date.now() }, (_key, value: unknown) => + typeof value === 'number' && Number.isNaN(value) ? undefined : value + ); + localStorage.setItem(KEY, json); + } catch { + // Private mode or full storage: the draft is only lost on the way to the account + } +} + +export function loadEventDraft(now = Date.now()): EventDraft | null { + try { + const raw = localStorage.getItem(KEY); + if (!raw) return null; + const draft = JSON.parse(raw) as EventDraft; + if (!draft?.values || typeof draft.savedAt !== 'number' || now - draft.savedAt > MAX_AGE_MS) { + localStorage.removeItem(KEY); + return null; + } + return draft; + } catch { + return null; + } +} + +export function clearEventDraft() { + try { + localStorage.removeItem(KEY); + } catch { + // nothing to clear + } +} diff --git a/src/lib/eventTypes.test.ts b/src/lib/eventTypes.test.ts index fa14ec6c..278d7990 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 } from './eventTypes'; -import { resolveEventFeatures, showsPriceOnLabel } from '../shared/eventFeatures'; +import { EVENT_TYPES, findEventType } from './eventTypes'; +import { showsPriceOnLabel } from '../shared/eventFeatures'; import { REQUIRABLE_FIELD_KEYS } from '../shared/categoryFields'; import i18n from '../i18n'; @@ -21,17 +21,35 @@ describe('event types', () => { } }); - it('the bike market of the KV Ulm: record with fixed data and frame number', () => { - const market = EVENT_TYPES.find((type) => type.id === 'bikeMarketRecord')!; - expect(market.commission).toBe(20); - expect(resolveEventFeatures(market)).toMatchObject({ - fixedSellerData: true, - privateSellersOnly: true, - maxItemsPerSeller: 5, - requiredFields: ['frameNumber'], - questionsDuringEventOnly: true, - }); - expect(market.categoryMatch?.test('Fahrräder')).toBe(true); - expect(market.categoryMatch?.test('Radios')).toBe(false); + it('the most asked for kinds come first, each with examples for the previews', () => { + expect(EVENT_TYPES.map((type) => type.id)).toEqual([ + 'kidsBazaar', + 'clothingBazaar', + 'skiBazaar', + 'bikeExchange', + ]); + for (const type of EVENT_TYPES) { + for (const lng of ['de', 'en']) { + const t = i18n.getFixedT(lng, 'organizer'); + const items = t(`eventTypes.${type.id}.exampleItems`, { returnObjects: true }); + const highlights = t(`eventTypes.${type.id}.highlights`, { returnObjects: true }); + expect(items, `${lng} ${type.id}`).toHaveLength(type.examplePrices.length); + expect(highlights, `${lng} ${type.id}`).toHaveLength(3); + } + } + }); + + it('preselects the categories of each kind', () => { + const match = (id: string, label: string) => + EVENT_TYPES.find((type) => type.id === id)!.categoryMatch!.test(label); + expect(match('kidsBazaar', 'Spielzeug')).toBe(true); + expect(match('skiBazaar', 'Sport')).toBe(true); + expect(match('bikeExchange', 'Fahrräder')).toBe(true); + expect(match('bikeExchange', 'Radios')).toBe(false); + }); + + it('drafts may name a kind that no longer exists', () => { + expect(findEventType('bikeMarketRecord')).toBeUndefined(); + expect(findEventType('skiBazaar')?.item).toBe('ski'); }); }); diff --git a/src/lib/eventTypes.ts b/src/lib/eventTypes.ts index 1ce248d9..0db4bc4b 100644 --- a/src/lib/eventTypes.ts +++ b/src/lib/eventTypes.ts @@ -1,16 +1,19 @@ -import type { LucideIcon } from 'lucide-react'; -import { Baby, Bike, ShieldCheck, Store } from 'lucide-react'; +import type { ItemKind } from '../components/illustrations/ItemIllustrations'; import type { StoredEventFeatures } from '../shared/eventFeatures'; /** - * Kinds of bazaars with suggested settings for the creation wizard. They only fill the - * form; the organizer can change everything afterwards. Texts: organizer.eventTypes.. + * Kinds of bazaars with suggested settings for the creation wizard, the most asked for + * first. They only fill the form; the organizer can change everything afterwards. + * Texts: organizer.eventTypes. (title, text, highlights, example item and title). */ -export type EventTypeId = 'bikeExchange' | 'bikeMarketRecord' | 'kidsBazaar' | 'fleaMarket'; +export type EventTypeId = 'kidsBazaar' | 'clothingBazaar' | 'skiBazaar' | 'bikeExchange'; export interface EventType { id: EventTypeId; - icon: LucideIcon; + /** Drawing for the picker and the previews of the wizard */ + item: ItemKind; + /** Prices of the example items in the previews (titles: eventTypes..exampleItems) */ + examplePrices: [number, number, number]; commission: number; features: StoredEventFeatures; /** Categories preselected by name, e.g. all bike categories */ @@ -20,50 +23,15 @@ export interface EventType { const BIKES = /fahrr|räder|\brad\b|rad$|bike|pedelec|\bmtb\b|bmx/i; export const EVENT_TYPES: EventType[] = [ - { - // Classic bike exchange: items are handed in, sold at a cash desk, paid out after - id: 'bikeExchange', - icon: Bike, - commission: 10, - features: { - discounts: false, - priceOffers: true, - minimumPrice: true, - questions: true, - photosOptional: false, - labelFormat: 'standard', - priceOnLabel: true, - }, - categoryMatch: BIKES, - }, - { - // Like the bike market of the KV Ulm: a record of who offered which bike, e.g. for the police - id: 'bikeMarketRecord', - icon: ShieldCheck, - commission: 20, - features: { - discounts: false, - priceOffers: false, - minimumPrice: false, - questions: true, - questionsDuringEventOnly: true, - photosOptional: true, - requiredFields: ['frameNumber'], - maxItemsPerSeller: 5, - labelFormat: 'standard', - priceOnLabel: true, - privateSellersOnly: true, - fixedSellerData: true, - }, - categoryMatch: BIKES, - }, { // Many small items per seller: small labels, no photos needed, discounts at the end id: 'kidsBazaar', - icon: Baby, + item: 'kids', + examplePrices: [9, 15, 6], commission: 15, features: { discounts: true, + maxDiscountPercent: 50, priceOffers: false, minimumPrice: false, questions: false, @@ -75,17 +43,62 @@ export const EVENT_TYPES: EventType[] = [ categoryMatch: /kind|baby|spiel|kleid|schuh|buch/i, }, { - id: 'fleaMarket', - icon: Store, + // Second-hand for everyone, e.g. a women's clothing bazaar or a flea market + id: 'clothingBazaar', + item: 'clothing', + examplePrices: [35, 24, 28], commission: 10, features: { discounts: true, + maxDiscountPercent: 30, priceOffers: true, minimumPrice: false, questions: true, photosOptional: true, - labelFormat: 'standard', + maxItemsPerSeller: 30, + labelFormat: 'small', priceOnLabel: false, }, + categoryMatch: /kleid|schuh|accessoir|haushalt|buch|spiel/i, + }, + { + // Fewer, pricier items: a negotiable price and questions about size and condition + id: 'skiBazaar', + item: 'ski', + examplePrices: [90, 45, 25], + commission: 10, + features: { + discounts: false, + priceOffers: true, + minimumPrice: true, + questions: true, + photosOptional: true, + maxItemsPerSeller: 15, + labelFormat: 'standard', + priceOnLabel: true, + }, + categoryMatch: /ski|snowboard|winter|sport|schuh/i, + }, + { + // Classic bike exchange: items are handed in, sold at a cash desk, paid out after + id: 'bikeExchange', + item: 'bike', + examplePrices: [140, 65, 25], + commission: 10, + features: { + discounts: false, + priceOffers: true, + minimumPrice: true, + questions: true, + photosOptional: false, + labelFormat: 'standard', + priceOnLabel: true, + }, + categoryMatch: BIKES, }, ]; + +/** The type of a draft or of the picker; drafts from before may name a removed one. */ +export function findEventType(id: string | undefined): EventType | undefined { + return EVENT_TYPES.find((type) => type.id === id); +} diff --git a/src/lib/lazyPage.ts b/src/lib/lazyPage.ts new file mode 100644 index 00000000..ad89003a --- /dev/null +++ b/src/lib/lazyPage.ts @@ -0,0 +1,51 @@ +import { lazy, type ComponentType } from 'react'; + +/** + * Pages behind the sign-in load as their own chunks, so visitors of the public pages + * (and search engines) download less. Signed-in users preload them all (preloadPages), + * so a lost connection at the cash desk does not stop them from switching pages. + */ + +const loaders: (() => Promise)[] = []; + +const RELOADED_KEY = 'bazarpro.chunkReload'; +const RELOAD_PAUSE_MS = 10_000; + +/** + * 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. + */ +function reloadForNewDeploy(error: unknown): never { + if (typeof navigator !== 'undefined' && navigator.onLine) { + try { + const last = Number(sessionStorage.getItem(RELOADED_KEY) ?? 0); + if (Date.now() - last > RELOAD_PAUSE_MS) { + sessionStorage.setItem(RELOADED_KEY, String(Date.now())); + window.location.reload(); + } + } catch { + // No session storage: show the error instead of risking a reload loop + } + } + throw error; +} + +/** 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 + ) + ); +} + +let preloaded = false; + +/** Loads all lazy pages in the background, once. */ +export function preloadPages() { + if (preloaded) return; + preloaded = true; + for (const load of loaders) void load().catch(() => undefined); +} diff --git a/src/lib/seo.ts b/src/lib/seo.ts index 4d08a40c..7a07997b 100644 --- a/src/lib/seo.ts +++ b/src/lib/seo.ts @@ -5,6 +5,9 @@ import { dateLocale } from '../i18n/format'; const DEFAULT_SITE_NAME = 'BazarPro'; +/** Preview image for links shared on social media and in search results */ +export const DEFAULT_SEO_IMAGE = '/og-image.png'; + export function getDefaultSiteName(): string { return DEFAULT_SITE_NAME; } diff --git a/src/lib/structuredData.ts b/src/lib/structuredData.ts index 9378b9f7..d50f2344 100644 --- a/src/lib/structuredData.ts +++ b/src/lib/structuredData.ts @@ -30,7 +30,7 @@ export function organization() { '@type': 'Organization', name: 'BazarPro', url: siteUrl, - logo: `${siteUrl}/favicon.svg`, + logo: `${siteUrl}/logo.png`, sameAs: [GITHUB_URL], }; } diff --git a/src/locales/de/account.json b/src/locales/de/account.json index 8f76bac9..c149a144 100644 --- a/src/locales/de/account.json +++ b/src/locales/de/account.json @@ -31,9 +31,6 @@ "oldPassword": "Aktuelles Passwort", "oldPasswordPlaceholder": "Dein aktuelles Passwort", "newPassword": "Neues Passwort setzen", - "newPasswordPlaceholder": "Mindestens 10 Zeichen", - "confirmPassword": "Passwort bestätigen", - "confirmPlaceholder": "Passwort erneut eingeben", "save": "Passwort aktualisieren", "saved": "Passwort erfolgreich geändert!", "wrongOld": "Das aktuelle Passwort stimmt nicht. Bitte überprüfe deine Eingabe.", @@ -42,20 +39,9 @@ "incomplete": "Das Passwortkonto ist unvollständig konfiguriert. Bitte Support kontaktieren.", "failed": "Passwort konnte nicht aktualisiert werden. Bitte versuche es erneut.", "oldRequired": "Altes Passwort ist erforderlich", - "confirmRequired": "Passwort-Bestätigung ist erforderlich", "rules": { - "length": "Mindestens 10 Zeichen", - "uppercase": "1 Großbuchstabe", - "lowercase": "1 Kleinbuchstabe", - "number": "1 Zahl", - "special": "1 Sonderzeichen" - }, - "strength": { - "weak": "Schwach", - "medium": "Mittel", - "strong": "Stark" - }, - "mismatch": "Die Passwörter stimmen nicht überein" + "length": "Mindestens 10 Zeichen" + } }, "digitalId": { "title": "Digitaler Ausweis", diff --git a/src/locales/de/auth.json b/src/locales/de/auth.json index c5d08b4f..3155407c 100644 --- a/src/locales/de/auth.json +++ b/src/locales/de/auth.json @@ -3,9 +3,9 @@ "emailPlaceholder": "deine@email.de", "password": "Passwort", "or": "Oder", - "continueWith": "Oder fortfahren mit", - "signInWithGoogle": "Mit Google anmelden", - "signInWithGithub": "Mit GitHub anmelden", + "continueWithGoogle": "Weiter mit Google", + "continueWithGithub": "Weiter mit GitHub", + "orWithEmail": "oder mit E-Mail", "signedIn": "Erfolgreich angemeldet.", "signedOut": "Erfolgreich abgemeldet.", "login": { @@ -20,9 +20,8 @@ }, "register": { "title": "Konto erstellen", - "subtitle": "Erstelle dein BazarPro-Konto und starte noch heute", - "confirmPassword": "Passwort bestätigen", - "terms": "Ich akzeptiere die Nutzungsbedingungen und Datenschutzrichtlinien von BazarPro.", + "subtitle": "Kostenlos und in einer Minute erledigt.", + "terms": "Mit der Registrierung akzeptierst du die Nutzungsbedingungen und die Datenschutzhinweise.", "submit": "Konto erstellen", "haveAccount": "Bereits ein Konto?", "loginNow": "Jetzt anmelden", @@ -31,26 +30,14 @@ "exists": "Zu dieser E-Mail existiert bereits ein Konto. Bitte melde dich an oder nutze Passwort vergessen.", "deletedOrBanned": "Der Account zu dieser E-Mail wurde gelöscht oder gesperrt. Um ihn zu reaktivieren, melde dich über die Anmeldeseite an. Falls das nicht klappt oder dein Account gesperrt wurde, wende dich an den Support.", "failed": "Registrierung fehlgeschlagen. Bitte versuche es später erneut.", - "linkInvalid": "Verifizierungslink ungültig oder abgelaufen. Bitte fordere einen neuen Code an." + "linkInvalid": "Verifizierungslink ungültig oder abgelaufen. Bitte fordere einen neuen Code an.", + "passwordHint": "Mindestens 10 Zeichen", + "showPassword": "Passwort anzeigen", + "hidePassword": "Passwort verbergen" }, "validation": { "email": "Ungültige E-Mail-Adresse", - "minLength": "Mindestens 10 Zeichen", - "uppercase": "Mindestens ein Großbuchstabe", - "lowercase": "Mindestens ein Kleinbuchstabe", - "number": "Mindestens eine Zahl", - "special": "Mindestens ein Sonderzeichen", - "terms": "Bitte akzeptiere die Nutzungsbedingungen", - "mismatch": "Passwörter stimmen nicht überein" - }, - "passwordRules": { - "length": "10+ Zeichen", - "uppercase": "Großbuchstabe", - "lowercase": "Kleinbuchstabe", - "number": "Zahl", - "special": "Sonderzeichen", - "match": "Passwörter stimmen überein", - "noMatch": "Passwörter stimmen nicht überein" + "minLength": "Mindestens 10 Zeichen" }, "verify": { "title": "Prüfe dein Postfach", @@ -89,9 +76,6 @@ "subtitleSet": "Gib den Code ein, den wir an {{email}} gesendet haben, sofern dort ein Konto existiert.", "requestCode": "Code anfordern", "newPassword": "Neues Passwort", - "newPasswordPlaceholder": "Mindestens 10 Zeichen", - "confirmNew": "Neues Passwort bestätigen", - "repeatPlaceholder": "Passwort wiederholen", "save": "Passwort speichern", "linkDetected": "Reset-Link erkannt. Bitte setze jetzt dein neues Passwort.", "enterEmail": "Bitte gib deine E-Mail-Adresse ein.", @@ -100,7 +84,6 @@ "requestFailed": "Passwort-Reset konnte nicht gestartet werden. Bitte versuche es erneut.", "fillAll": "Bitte fülle alle Felder aus.", "notValid": "Das neue Passwort erfüllt nicht alle Anforderungen.", - "mismatch": "Die Passwörter stimmen nicht überein.", "done": "Passwort erfolgreich zurückgesetzt. Du bist jetzt angemeldet.", "codeInvalid": "Der Code ist ungültig oder abgelaufen. Bitte fordere einen neuen an.", "failed": "Passwort konnte nicht zurückgesetzt werden. Bitte versuche es erneut." diff --git a/src/locales/de/errors.json b/src/locales/de/errors.json index 2b0786d2..24697369 100644 --- a/src/locales/de/errors.json +++ b/src/locales/de/errors.json @@ -59,6 +59,8 @@ "notPublic": "Diese Veranstaltung ist nicht öffentlich.", "over": "Die Veranstaltung ist bereits vorbei.", "pastNoDelete": "Vergangene Veranstaltungen können nicht gelöscht werden.", + "countryUnknown": "Dieses Land wird nicht unterstützt.", + "addressTooLong": "Die Adresse ist zu lang.", "pastNoEdit": "Vergangene Veranstaltungen können nicht mehr bearbeitet werden.", "rejectionReasonRequired": "Bitte gib einen Grund für die Ablehnung an.", "runningNoDate": "Während der Veranstaltung kann das Datum nicht geändert werden.", diff --git a/src/locales/de/landing.json b/src/locales/de/landing.json index d760cb08..17d4629b 100644 --- a/src/locales/de/landing.json +++ b/src/locales/de/landing.json @@ -243,5 +243,11 @@ "meta": { "defaultDescription": "Kostenlose Open-Source-Software für Kinderkleiderbasar, Fahrradbörse und Flohmarkt: QR-Etiketten, Kasse per Smartphone, automatische Abrechnung.", "appDescription": "Open-Source-Software für Second-Hand-Basare wie Kinderkleiderbasar, Fahrradbörse, Skibasar und Flohmarkt: Artikel online anmelden, QR-Etiketten drucken, an der Kasse per Smartphone scannen, automatische Abrechnung." + }, + "kinds": { + "eyebrow": "Vorlagen", + "title": "Für jeden Basar die passende Vorlage", + "text": "Kinderbasar, Kleiderbasar, Skibasar oder Fahrradbörse: Die Vorlage stellt Etiketten, Rabatte und Verhandeln passend ein. Ausprobieren geht ohne Konto.", + "start": "Mit dieser Vorlage starten" } } diff --git a/src/locales/de/organizer.json b/src/locales/de/organizer.json index dc736307..2ec052b0 100644 --- a/src/locales/de/organizer.json +++ b/src/locales/de/organizer.json @@ -35,7 +35,10 @@ "create": "Veranstaltung erstellen", "registeredMaxCommission": "Verkäufer sind angemeldet: höchstens {{percent}} %", "registeredMaxIntakeFee": "Verkäufer sind angemeldet: höchstens {{fee}} €", - "registeredMinItems": "Verkäufer sind angemeldet: mindestens {{min}} Artikel" + "registeredMinItems": "Verkäufer sind angemeldet: mindestens {{min}} Artikel", + "postalCodeInvalid": "Bitte eine gültige Postleitzahl eingeben", + "cityRequired": "Bitte gib zur Postleitzahl auch den Ort an", + "addressTooLong": "Zu lang" }, "basic": { "title": "Grundinformationen", @@ -53,7 +56,21 @@ "link": "Link", "noDescription": "Noch keine Beschreibung vorhanden. Wechsle zu „Bearbeiten“, um Inhalte zu erfassen.", "markdownHint": "Markdown erlaubt z. B. Überschriften (##, ###), Absätze, **fett**, *kursiv*, Listen mit - und Links wie [Text](https://...).", - "location": "Ort *", + "location": "Veranstaltungsort *", + "locationPlaceholder": "z. B. Turnhalle der Grundschule Nord", + "address": "Adresse", + "addressHint": "Mit Adresse finden Besucher den Weg, und Google zeigt deinen Basar in der Veranstaltungssuche.", + "street": "Straße und Hausnummer", + "postalCode": "PLZ", + "city": "Ort", + "country": "Land", + "countries": { + "DE": "Deutschland", + "AT": "Österreich", + "CH": "Schweiz", + "LI": "Liechtenstein", + "LU": "Luxemburg" + }, "start": "Startdatum *", "end": "Enddatum *" }, @@ -136,7 +153,9 @@ "privateSellers": "Nur Privatverkäufer", "privateSellersText": "Beim Anmelden bestätigen Verkäufer, dass sie als Privatperson verkaufen und nicht gewerblich.", "fixedData": "Feste Daten für den Nachweis", - "fixedDataText": "Bei der Annahme vor Ort prüfst du Name und Anschrift mit dem Ausweis; weichen sie ab, korrigiert der Verkäufer sie vorher in seinem Profil. Mit dem ersten angenommenen Artikel sind sie fest, ebenso Titel, Kategorie, Preis und Pflichtangaben jedes angenommenen Artikels. So entsteht ein verlässlicher Nachweis, wer was angeboten hat, z. B. für die Polizei. Verkäufer brauchen dafür ein vollständiges Profil." + "fixedDataText": "Bei der Annahme vor Ort prüfst du Name und Anschrift mit dem Ausweis; weichen sie ab, korrigiert der Verkäufer sie vorher in seinem Profil. Mit dem ersten angenommenen Artikel sind sie fest, ebenso Titel, Kategorie, Preis und Pflichtangaben jedes angenommenen Artikels. So entsteht ein verlässlicher Nachweis, wer was angeboten hat, z. B. für die Polizei. Verkäufer brauchen dafür ein vollständiges Profil.", + "discountFromNeedsDates": "Wähle zuerst Beginn und Ende der Veranstaltung.", + "discountStartLater": "Ab wann die Rabatte gelten, legst du bei „Wann und wo?“ fest, sobald der Termin steht." }, "logistics": { "title": "Abgabe & Abholung", @@ -727,36 +746,36 @@ "progress": "Schritt {{step}} von {{total}}", "steps": { "type": { - "title": "Welche Art von Basar planst du?", - "text": "Die Art setzt passende Einstellungen vor, z. B. Provision, Etiketten und ob ihr eine Kasse habt. Du kannst in den nächsten Schritten alles ändern. Alternativ übernimmst du die Einstellungen eines früheren Basars." - }, - "basics": { - "title": "Wann und wo?", - "text": "Titel, Beschreibung, Datum und Ort erscheinen auf der Basar-Seite und in den Mails an Verkäufer. Ein Titelbild und ein Lageplan helfen Besuchern, sind aber freiwillig." + "title": "Was für ein Basar wird's?", + "text": "Wähle eine Vorlage – sie stellt alles passend ein. In jedem Schritt siehst du in der Vorschau, was Käufer und Verkäufer davon merken. Ändern kannst du später alles." }, "sale": { "title": "Wie wird verkauft?", - "text": "Wie wird an der Kasse verkauft? Dürfen Verkäufer während des Basars Rabatte geben, und dürfen Käufer vorab Preise vorschlagen oder Fragen stellen? Alles, was du hier einschaltest, sehen Verkäufer vor der Anmeldung." - }, - "fees": { - "title": "Was kostet es die Verkäufer?", - "text": "Die Provision ist ein Anteil am Verkaufspreis. Eine Annahmegebühr fällt pro angenommenem Artikel an, auch wenn er nicht verkauft wird. Beides siehst du in der Zusammenfassung mit Rechenbeispiel. Sobald sich der erste Verkäufer angemeldet hat, lassen sich die Gebühren nur noch senken." + "text": "Rabatte, Verhandeln und Fragen: Was du einschaltest, zeigt die Vorschau so, wie Käufer den Artikel auf dem Handy sehen." }, "items": { "title": "Welche Artikel?", - "text": "Kategorien bestimmen, was angeboten werden darf, und welche Zusatzfelder es gibt, z. B. die Rahmennummer bei Rädern. Lege fest, welche Angaben Pflicht sind, ob Fotos nötig sind, wie viele Artikel ein Verkäufer anmelden darf und welche Etiketten gedruckt werden." + "text": "Kategorien, Fotos und Etiketten. Die Vorschau zeigt das Etikett, das Verkäufer ausdrucken und an jedes Teil hängen." + }, + "fees": { + "title": "Was kostet es die Verkäufer?", + "text": "Eine Provision vom Verkaufspreis und, wenn du willst, eine Annahmegebühr pro Artikel. Die Vorschau rechnet es an einem Artikel vor." }, "registration": { "title": "Wer darf mitmachen?", - "text": "Öffentliche Basare erscheinen nach einer kurzen Prüfung auf der Startseite. Mit einem Zugangscode kann sich nur anmelden, wer den Code von dir bekommt. Für einen Nachweis gegenüber der Polizei kannst du Privatverkäufer verlangen und die Daten nach der Anmeldung festschreiben." + "text": "Öffentliche Basare erscheinen nach einer kurzen Prüfung auf der Startseite von BazarPro. Mit einem Zugangscode kommt nur rein, wer den Code von dir bekommt." + }, + "basics": { + "title": "Wann und wo?", + "text": "Titel, Beschreibung, Ort und Termin – so steht dein Basar auf seiner Seite und in den Mails an Verkäufer." }, "logistics": { "title": "Abgabe und Abholung", - "text": "Wann bringen Verkäufer ihre Artikel, und wann holen sie Unverkauftes und ihr Geld ab? Die Zeiten stehen in den Bedingungen und in der Mail am Vorabend. Du kannst sie auch später ergänzen." + "text": "Wann bringen Verkäufer ihre Sachen, und wann holen sie Unverkauftes und ihr Geld ab? Du kannst die Zeiten auch später ergänzen." }, - "summary": { - "title": "Alles im Blick", - "text": "Prüfe die wichtigsten Angaben und die Bedingungen, wie Verkäufer sie vor der Anmeldung sehen. Nach dem Anlegen kannst du alles in den Einstellungen des Basars ändern." + "preview": { + "title": "So sieht dein Basar aus", + "text": "Das ist die Seite, die Besucher und Verkäufer sehen. Passt alles? Dann leg den Basar an – ändern kannst du danach noch alles." } }, "summary": { @@ -766,24 +785,135 @@ "categories": "Kategorien", "sellersSee": "So sehen Verkäufer die Bedingungen vor der Anmeldung:" }, - "fixErrors": "Bitte prüfe die markierten Angaben." + "fixErrors": "Bitte prüfe die markierten Angaben.", + "guestCreate": "Konto anlegen und Basar erstellen", + "draftRestored": "Dein Entwurf ist wieder da.", + "creatingDraft": "Dein Basar wird angelegt …", + "preview": { + "label": "Vorschau", + "buyerPhone": "So sieht es ein Käufer", + "sellerView": "So sieht es ein Verkäufer", + "listing": "So steht dein Basar in der Liste", + "discount": "−{{percent}} %", + "discountFrom": "Ab {{from}} dürfen Verkäufer bis zu {{percent}} % nachlassen.", + "discountAlways": "Verkäufer dürfen bis zu {{percent}} % nachlassen, z. B. gegen Ende.", + "negotiable": "VB · verhandelbar", + "negotiableHint": "An der Kasse bis zum Mindestpreis des Verkäufers – den sieht nur das Team.", + "offerTitle": "Preis vorschlagen", + "offerAmount": "{{price}}", + "offerSend": "Senden", + "offerHint": "Nimmt der Verkäufer an, gilt der Preis an der Kasse.", + "questionsTitle": "Fragen zum Artikel", + "question": "Ist alles komplett und sauber?", + "answer": "Ja, kaum benutzt und gewaschen.", + "questionsLater": "Fragen erst während des Basars", + "plain": "Nur Foto und Preis: schnell an der Kasse, ohne Verhandeln.", + "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}}", + "photoRequired": "Foto Pflicht", + "photoOptional": "Ohne Foto", + "maxItems": "Bis zu {{count}} Artikel pro Verkäufer", + "unlimited": "Beliebig viele Artikel pro Verkäufer", + "requiredFields": "Pflichtangaben: {{fields}}", + "categories": "Erlaubt: {{categories}}", + "noCategories": "Noch keine Kategorie gewählt", + "feeItem": "Ein Artikel für {{price}}", + "sellerGets": "Verkäufer bekommt", + "bazaarKeeps": "Basar behält", + "free": "Keine Gebühren: Verkäufer bekommen den vollen Preis.", + "intakePerItem": "+ {{fee}} Annahmegebühr pro abgegebenem Artikel, auch wenn er nicht verkauft wird", + "public": "Öffentlich auf bazarpro.de", + "logged-in": "Angebote nach Login", + "approved": "Nur für Freigeschaltete", + "accessCode": "Anmeldung nur mit Code", + "spots": "{{count}} Plätze für Verkäufer", + "privateOnly": "Nur Privatverkäufer", + "fixedData": "Daten fest ab Anmeldung", + "join": "Als Verkäufer anmelden", + "dateOpen": "Termin folgt", + "placeOpen": "Ort folgt", + "descriptionOpen": "Hier steht deine Beschreibung – was es gibt, wo man parkt, ob es Kaffee und Kuchen gibt.", + "dropoff": "Abgabe", + "sale": "Basar", + "pickup": "Abholung", + "open": "noch offen", + "browserUrl": "bazarpro.de/basar", + "offersTitle": "Angebote", + "offersHint": "Beispiele: so erscheinen die Artikel deiner Verkäufer.", + "facts": "Das Wichtigste", + "photosOptionalNote": "Fotos freiwillig", + "jump": "Vorschau ansehen", + "mapExample": "Nur ein Beispiel: Hier erscheint dein eigener Plan, sobald du ihn hochlädst.", + "mapRow": "Reihe {{row}}", + "mapCashDesk": "Kasse", + "mapEntrance": "Eingang" + }, + "short": { + "type": "Art", + "sale": "Verkauf", + "items": "Artikel", + "fees": "Gebühren", + "registration": "Mitmachen", + "basics": "Termin & Ort", + "logistics": "Abgabe", + "preview": "Vorschau" + }, + "pictures": { + "title": "Bilder", + "intro": "Mit Bild wirkt dein Basar gleich einladender. Du kannst alles später ändern.", + "cover": "Titelbild", + "coverText": "Wähle eine Vorlage oder lade ein eigenes Bild hoch.", + "coverPick": "Vorlage „{{name}}“ wählen", + "names": { + "kids": "Holzeisenbahn", + "clothing": "Kleiderstange", + "ski": "Skipiste", + "bike": "Fahrrad", + "market": "Flohmarkt", + "pattern": "Bunte Kacheln" + }, + "own": "Eigenes Bild", + "map": "Lageplan", + "mapText": "Zeigt Besuchern, wo sie Stände, Kasse und Eingang finden.", + "locked": "Eigene Bilder kannst du nach dem Anmelden hochladen. Dein Basar bleibt erhalten.", + "login": "Anmelden und hochladen", + "noCover": "Kein Titelbild" + } }, "eventTypes": { - "bikeExchange": { - "title": "Fahrradbörse mit Kasse", - "text": "Verkäufer geben ihre Räder ab, verkauft wird an der Kasse, danach wird ausgezahlt. Mit Fotos, Verhandlungsbasis und Preisvorschlägen." + "kidsBazaar": { + "title": "Kinderbasar", + "text": "Kinderkleidung, Spielzeug, Bücher und Ausstattung – viele kleine Teile pro Familie.", + "highlights": ["Kleine Etiketten", "Fotos freiwillig", "Rabatte zum Schluss"], + "exampleTitle": "Kinderbasar", + "exampleItems": [ + "T-Shirt und Latzhose, Gr. 98", + "Lego-Kiste, gemischt", + "Gummistiefel, Gr. 27" + ] }, - "bikeMarketRecord": { - "title": "Fahrradmarkt mit Nachweis", - "text": "Für Märkte, bei denen ihr nachweisen müsst, wer welches Rad angeboten hat, z. B. für die Polizei: bis zu 5 Räder pro Verkäufer, Rahmennummer Pflicht, nur Privatleute, feste Daten ab der Anmeldung und Fragen erst während des Markts." + "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"], + "exampleTitle": "Second-Hand-Basar", + "exampleItems": ["Jacke, Gr. 38", "Lederstiefel, Gr. 39", "Handtasche, Leder"] }, - "kidsBazaar": { - "title": "Kinderbasar (Nummernbasar)", - "text": "Viele kleine Artikel pro Verkäufer: kleine Etiketten, Fotos freiwillig, Artikel-Limit und Rabatte zum Ende des Basars. Eine Annahmegebühr kannst du ergänzen." + "skiBazaar": { + "title": "Skibasar", + "text": "Ski, Skischuhe, Helme und Wintersportkleidung – weniger, dafür wertvollere Artikel.", + "highlights": ["Verhandeln (VB)", "Preisvorschläge", "Preis aufs Etikett"], + "exampleTitle": "Skibasar", + "exampleItems": ["Kinderski 120 cm mit Bindung", "Skischuhe, Gr. 38", "Skihelm, Gr. M"] }, - "fleaMarket": { - "title": "Flohmarkt oder allgemeiner Basar", - "text": "Wenige Vorgaben: Fotos freiwillig, Rabatte, Preisvorschläge und Fragen eingeschaltet." + "bikeExchange": { + "title": "Fahrradbörse", + "text": "Räder, Schlösser und Zubehör: abgeben, an der Kasse verkaufen, danach auszahlen.", + "highlights": ["Fotos Pflicht", "Verhandeln (VB)", "Große Etiketten"], + "exampleTitle": "Fahrradbörse", + "exampleItems": ["Hollandrad, 28 Zoll", "Kinderrad 20 Zoll", "Bügelschloss"] } }, "conflicts": { diff --git a/src/locales/en/account.json b/src/locales/en/account.json index 29d7790a..19a06890 100644 --- a/src/locales/en/account.json +++ b/src/locales/en/account.json @@ -31,9 +31,6 @@ "oldPassword": "Current password", "oldPasswordPlaceholder": "Your current password", "newPassword": "Set a new password", - "newPasswordPlaceholder": "At least 10 characters", - "confirmPassword": "Confirm password", - "confirmPlaceholder": "Enter the password again", "save": "Update password", "saved": "Password changed!", "wrongOld": "The current password is wrong. Please check your input.", @@ -42,20 +39,9 @@ "incomplete": "The password account is not set up completely. Please contact support.", "failed": "The password could not be updated. Please try again.", "oldRequired": "The current password is required", - "confirmRequired": "Please confirm the password", "rules": { - "length": "At least 10 characters", - "uppercase": "1 uppercase letter", - "lowercase": "1 lowercase letter", - "number": "1 number", - "special": "1 special character" - }, - "strength": { - "weak": "Weak", - "medium": "Medium", - "strong": "Strong" - }, - "mismatch": "The passwords do not match" + "length": "At least 10 characters" + } }, "digitalId": { "title": "Digital ID", diff --git a/src/locales/en/auth.json b/src/locales/en/auth.json index 2372a854..babfe109 100644 --- a/src/locales/en/auth.json +++ b/src/locales/en/auth.json @@ -3,9 +3,9 @@ "emailPlaceholder": "you@example.com", "password": "Password", "or": "Or", - "continueWith": "Or continue with", - "signInWithGoogle": "Sign in with Google", - "signInWithGithub": "Sign in with GitHub", + "continueWithGoogle": "Continue with Google", + "continueWithGithub": "Continue with GitHub", + "orWithEmail": "or with email", "signedIn": "Signed in successfully.", "signedOut": "Signed out successfully.", "login": { @@ -20,9 +20,8 @@ }, "register": { "title": "Create account", - "subtitle": "Create your BazarPro account and get started today", - "confirmPassword": "Confirm password", - "terms": "I accept the terms of use and the privacy policy of BazarPro.", + "subtitle": "Free, and done in a minute.", + "terms": "By signing up you accept the terms of use and the privacy notice.", "submit": "Create account", "haveAccount": "Already have an account?", "loginNow": "Log in now", @@ -31,26 +30,14 @@ "exists": "An account with this email already exists. Please log in or use “Forgot password”.", "deletedOrBanned": "The account for this email was deleted or blocked. To reactivate it, log in on the login page. If that does not work or your account was blocked, please contact support.", "failed": "Sign-up failed. Please try again later.", - "linkInvalid": "The verification link is invalid or has expired. Please request a new code." + "linkInvalid": "The verification link is invalid or has expired. Please request a new code.", + "passwordHint": "At least 10 characters", + "showPassword": "Show password", + "hidePassword": "Hide password" }, "validation": { "email": "Invalid email address", - "minLength": "At least 10 characters", - "uppercase": "At least one uppercase letter", - "lowercase": "At least one lowercase letter", - "number": "At least one number", - "special": "At least one special character", - "terms": "Please accept the terms of use", - "mismatch": "Passwords do not match" - }, - "passwordRules": { - "length": "10+ characters", - "uppercase": "Uppercase letter", - "lowercase": "Lowercase letter", - "number": "Number", - "special": "Special character", - "match": "Passwords match", - "noMatch": "Passwords do not match" + "minLength": "At least 10 characters" }, "verify": { "title": "Check your inbox", @@ -89,9 +76,6 @@ "subtitleSet": "Enter the code we sent to {{email}}, if an account exists there.", "requestCode": "Request code", "newPassword": "New password", - "newPasswordPlaceholder": "At least 10 characters", - "confirmNew": "Confirm new password", - "repeatPlaceholder": "Repeat password", "save": "Save password", "linkDetected": "Reset link detected. Please set your new password now.", "enterEmail": "Please enter your email address.", @@ -100,7 +84,6 @@ "requestFailed": "The password reset could not be started. Please try again.", "fillAll": "Please fill in all fields.", "notValid": "The new password does not meet all requirements.", - "mismatch": "The passwords do not match.", "done": "Password reset. You are now logged in.", "codeInvalid": "The code is invalid or has expired. Please request a new one.", "failed": "The password could not be reset. Please try again." diff --git a/src/locales/en/errors.json b/src/locales/en/errors.json index 6666a494..b99d21d5 100644 --- a/src/locales/en/errors.json +++ b/src/locales/en/errors.json @@ -59,6 +59,8 @@ "notPublic": "This event is not public.", "over": "The event is already over.", "pastNoDelete": "Past events cannot be deleted.", + "countryUnknown": "This country is not supported.", + "addressTooLong": "The address is too long.", "pastNoEdit": "Past events can no longer be edited.", "rejectionReasonRequired": "Please give a reason for the rejection.", "runningNoDate": "The date cannot be changed during the event.", diff --git a/src/locales/en/landing.json b/src/locales/en/landing.json index 2994eb11..286e8ef8 100644 --- a/src/locales/en/landing.json +++ b/src/locales/en/landing.json @@ -243,5 +243,11 @@ "meta": { "defaultDescription": "Free open-source software for children's clothing bazaars, bike sales and flea markets: QR labels, smartphone checkout, automatic settlement.", "appDescription": "Open-source software for second-hand bazaars such as children's clothing bazaars, bike sales, ski bazaars and flea markets: register items online, print QR labels, scan at the checkout with a smartphone, automatic settlement." + }, + "kinds": { + "eyebrow": "Templates", + "title": "A template for every bazaar", + "text": "Children's, clothing or ski bazaar, or a bike sale: the template sets labels, discounts and haggling to match. Try it without an account.", + "start": "Start with this template" } } diff --git a/src/locales/en/organizer.json b/src/locales/en/organizer.json index d2ff828d..8f11f2bf 100644 --- a/src/locales/en/organizer.json +++ b/src/locales/en/organizer.json @@ -35,7 +35,10 @@ "create": "Create event", "registeredMaxCommission": "Sellers have registered: at most {{percent}} %", "registeredMaxIntakeFee": "Sellers have registered: at most {{fee}} €", - "registeredMinItems": "Sellers have registered: at least {{min}} items" + "registeredMinItems": "Sellers have registered: at least {{min}} items", + "postalCodeInvalid": "Please enter a valid postal code", + "cityRequired": "Please add the town to the postal code", + "addressTooLong": "Too long" }, "basic": { "title": "Basic information", @@ -53,7 +56,21 @@ "link": "Link", "noDescription": "No description yet. Switch to “Edit” to add content.", "markdownHint": "Markdown supports e.g. headings (##, ###), paragraphs, **bold**, *italic*, lists with - and links like [Text](https://...).", - "location": "Location *", + "location": "Venue *", + "locationPlaceholder": "e.g. gym of the north primary school", + "address": "Address", + "addressHint": "With an address visitors find their way, and Google shows your bazaar in its event search.", + "street": "Street and number", + "postalCode": "Postal code", + "city": "Town", + "country": "Country", + "countries": { + "DE": "Germany", + "AT": "Austria", + "CH": "Switzerland", + "LI": "Liechtenstein", + "LU": "Luxembourg" + }, "start": "Start date *", "end": "End date *" }, @@ -136,7 +153,9 @@ "privateSellers": "Private sellers only", "privateSellersText": "When registering, sellers confirm that they sell as private persons, not commercially.", "fixedData": "Fixed data for the record", - "fixedDataText": "At the intake on site you check name and address against the ID card; if they differ, the seller corrects them in their profile first. From the first accepted item on they are fixed, and so are title, category, price and required details of every accepted item. This gives a reliable record of who offered what, e.g. for the police. Sellers need a complete profile for this." + "fixedDataText": "At the intake on site you check name and address against the ID card; if they differ, the seller corrects them in their profile first. From the first accepted item on they are fixed, and so are title, category, price and required details of every accepted item. This gives a reliable record of who offered what, e.g. for the police. Sellers need a complete profile for this.", + "discountFromNeedsDates": "Choose the start and end of the event first.", + "discountStartLater": "You set when the discounts start under “When and where?”, once the date is fixed." }, "logistics": { "title": "Drop-off & pickup", @@ -727,36 +746,36 @@ "progress": "Step {{step}} of {{total}}", "steps": { "type": { - "title": "What kind of bazaar are you planning?", - "text": "The kind sets suitable defaults, e.g. commission, labels and whether you have a cash desk. You can change everything in the next steps. Alternatively, copy the settings of a past bazaar." - }, - "basics": { - "title": "When and where?", - "text": "Title, description, date and location appear on the bazaar page and in the emails to sellers. A cover image and a site map help visitors but are optional." + "title": "What kind of bazaar is it?", + "text": "Pick a template – it sets everything up to match. At every step the preview shows what buyers and sellers notice. You can change everything later." }, "sale": { - "title": "How are items sold?", - "text": "How are items sold at the cash desk? May sellers give discounts during the bazaar, and may buyers suggest prices or ask questions beforehand? Everything you switch on here is shown to sellers before they register." - }, - "fees": { - "title": "What does it cost sellers?", - "text": "The commission is a share of the sale price. An intake fee applies per accepted item, even if it does not sell. You see both with a worked example in the summary. Once the first seller has registered, the fees can only be lowered." + "title": "How is it sold?", + "text": "Discounts, haggling and questions: whatever you switch on, the preview shows the way buyers see the item on their phone." }, "items": { "title": "Which items?", - "text": "Categories decide what may be offered and which extra fields exist, e.g. the frame number for bikes. Choose which details are required, whether photos are needed, how many items a seller may register and which labels are printed." + "text": "Categories, photos and labels. The preview shows the label sellers print and attach to every item." + }, + "fees": { + "title": "What do sellers pay?", + "text": "A commission on the sale price and, if you like, an intake fee per item. The preview works it out for one item." }, "registration": { - "title": "Who may take part?", - "text": "Public bazaars appear on the start page after a short review. With an access code only those who get the code from you can register. For a record for the police you can require private sellers and fix the data after registration." + "title": "Who can take part?", + "text": "Public bazaars appear on the BazarPro start page after a short check. With an access code only people who get the code from you can join." + }, + "basics": { + "title": "When and where?", + "text": "Title, description, place and date – this is how your bazaar appears on its page and in the emails to sellers." }, "logistics": { - "title": "Hand-in and pickup", - "text": "When do sellers bring their items, and when do they pick up unsold items and their money? The times appear in the conditions and in the email the evening before. You can also add them later." + "title": "Drop-off and pickup", + "text": "When do sellers bring their items, and when do they collect what is left and their money? You can add the times later." }, - "summary": { - "title": "Everything at a glance", - "text": "Check the key details and the conditions as sellers see them before registering. After creating you can change everything in the settings of the bazaar." + "preview": { + "title": "This is your bazaar", + "text": "This is the page visitors and sellers see. All good? Then create the bazaar – you can still change everything afterwards." } }, "summary": { @@ -766,24 +785,135 @@ "categories": "Categories", "sellersSee": "This is how sellers see the conditions before registering:" }, - "fixErrors": "Please check the marked details." + "fixErrors": "Please check the marked details.", + "guestCreate": "Sign up and create bazaar", + "draftRestored": "Your draft is back.", + "creatingDraft": "Creating your bazaar …", + "preview": { + "label": "Preview", + "buyerPhone": "What a buyer sees", + "sellerView": "What a seller sees", + "listing": "How your bazaar is listed", + "discount": "−{{percent}} %", + "discountFrom": "From {{from}} sellers may take up to {{percent}} % off.", + "discountAlways": "Sellers may take up to {{percent}} % off, e.g. towards the end.", + "negotiable": "Negotiable", + "negotiableHint": "At the cash desk down to the seller's minimum price – only the team sees it.", + "offerTitle": "Suggest a price", + "offerAmount": "{{price}}", + "offerSend": "Send", + "offerHint": "If the seller accepts, the price applies at the cash desk.", + "questionsTitle": "Questions about the item", + "question": "Is everything complete and clean?", + "answer": "Yes, barely used and washed.", + "questionsLater": "Questions only during the bazaar", + "plain": "Just photo and price: quick at the cash desk, no haggling.", + "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}}", + "photoRequired": "Photo required", + "photoOptional": "No photo", + "maxItems": "Up to {{count}} items per seller", + "unlimited": "Any number of items per seller", + "requiredFields": "Required: {{fields}}", + "categories": "Allowed: {{categories}}", + "noCategories": "No category chosen yet", + "feeItem": "One item for {{price}}", + "sellerGets": "Seller gets", + "bazaarKeeps": "Bazaar keeps", + "free": "No fees: sellers get the full price.", + "intakePerItem": "+ {{fee}} intake fee per item handed in, even if it does not sell", + "public": "Public on bazarpro.de", + "logged-in": "Offers after login", + "approved": "Approved users only", + "accessCode": "Joining only with a code", + "spots": "{{count}} places for sellers", + "privateOnly": "Private sellers only", + "fixedData": "Data fixed from registration", + "join": "Register as seller", + "dateOpen": "Date to follow", + "placeOpen": "Place to follow", + "descriptionOpen": "Your description goes here – what there is, where to park, whether there is coffee and cake.", + "dropoff": "Drop-off", + "sale": "Bazaar", + "pickup": "Pickup", + "open": "open", + "browserUrl": "bazarpro.de/bazaar", + "offersTitle": "Offers", + "offersHint": "Examples: this is how your sellers' items appear.", + "facts": "Key facts", + "photosOptionalNote": "Photos optional", + "jump": "See the preview", + "mapExample": "Just an example: your own plan appears here once you upload it.", + "mapRow": "Row {{row}}", + "mapCashDesk": "Cash desk", + "mapEntrance": "Entrance" + }, + "short": { + "type": "Kind", + "sale": "Sale", + "items": "Items", + "fees": "Fees", + "registration": "Joining", + "basics": "Date & place", + "logistics": "Drop-off", + "preview": "Preview" + }, + "pictures": { + "title": "Pictures", + "intro": "A picture makes your bazaar more inviting. You can change everything later.", + "cover": "Cover picture", + "coverText": "Pick a template or upload your own picture.", + "coverPick": "Choose template “{{name}}”", + "names": { + "kids": "Wooden train", + "clothing": "Clothes rail", + "ski": "Ski slope", + "bike": "Bicycle", + "market": "Flea market", + "pattern": "Colourful tiles" + }, + "own": "Your own picture", + "map": "Site plan", + "mapText": "Shows visitors where to find stalls, cash desk and entrance.", + "locked": "You can upload your own pictures after logging in. Your bazaar is kept.", + "login": "Log in and upload", + "noCover": "No cover picture" + } }, "eventTypes": { - "bikeExchange": { - "title": "Bike exchange with cash desk", - "text": "Sellers hand in their bikes, a cash desk sells them, payouts follow. With photos, negotiable prices and price offers." + "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"], + "exampleTitle": "Children's bazaar", + "exampleItems": ["T-shirt and dungarees, size 98", "Lego box, mixed", "Rubber boots, size 27"] }, - "bikeMarketRecord": { - "title": "Bike market with record", - "text": "For markets that must prove who offered which bike, e.g. to the police: up to 5 bikes per seller, frame number required, private persons only, fixed data from registration on and questions only during the market." + "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"], + "exampleTitle": "Second-hand bazaar", + "exampleItems": ["Jacket, size 38", "Leather boots, size 39", "Leather handbag"] }, - "kidsBazaar": { - "title": "Children's bazaar (number bazaar)", - "text": "Many small items per seller: small labels, photos optional, an item limit and discounts towards the end. You can add an intake fee." + "skiBazaar": { + "title": "Ski bazaar", + "text": "Skis, ski boots, helmets and winter sportswear – fewer but pricier items.", + "highlights": ["Negotiable price", "Price offers", "Price on the label"], + "exampleTitle": "Ski bazaar", + "exampleItems": [ + "Children's skis 120 cm with bindings", + "Ski boots, size 38", + "Ski helmet, size M" + ] }, - "fleaMarket": { - "title": "Flea market or general bazaar", - "text": "Few rules: photos optional, discounts, price offers and questions switched on." + "bikeExchange": { + "title": "Bike sale", + "text": "Bikes, locks and accessories: hand in, sell at the cash desk, pay out afterwards.", + "highlights": ["Photos required", "Negotiable price", "Large labels"], + "exampleTitle": "Bike sale", + "exampleItems": ["City bike, 28 inch", "Children's bike 20 inch", "U-lock"] } }, "conflicts": { diff --git a/src/pages/account/components/SecurityCard.test.tsx b/src/pages/account/components/SecurityCard.test.tsx new file mode 100644 index 00000000..8c79a9f4 --- /dev/null +++ b/src/pages/account/components/SecurityCard.test.tsx @@ -0,0 +1,29 @@ +import { fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { describe, expect, it, vi } from 'vitest'; +import { SecurityCard } from './SecurityCard'; + +const changePassword = vi.hoisted(() => vi.fn(async () => undefined)); +vi.mock('../../../lib/api/react', () => ({ + useAuthActions: () => ({ changePassword }), +})); + +describe('SecurityCard', () => { + it('changes the password with one field and 10 characters, shown on request', async () => { + render(); + expect(screen.queryByLabelText('Passwort bestätigen')).toBeNull(); + + fireEvent.change(screen.getByLabelText('Aktuelles Passwort'), { target: { value: '123456' } }); + const newPassword = screen.getByLabelText('Neues Passwort setzen'); + fireEvent.change(newPassword, { target: { value: 'kurz' } }); + fireEvent.click(screen.getByRole('button', { name: 'Passwort aktualisieren' })); + expect(await screen.findByText('Mindestens 10 Zeichen')).toHaveClass('text-destructive'); + expect(changePassword).not.toHaveBeenCalled(); + + const [, showNew] = screen.getAllByRole('button', { name: 'Passwort anzeigen' }); + fireEvent.click(showNew); + expect(newPassword).toHaveAttribute('type', 'text'); + fireEvent.change(newPassword, { target: { value: 'kinderbasar' } }); + fireEvent.click(screen.getByRole('button', { name: 'Passwort aktualisieren' })); + await waitFor(() => expect(changePassword).toHaveBeenCalledWith('123456', 'kinderbasar')); + }); +}); diff --git a/src/pages/account/components/SecurityCard.tsx b/src/pages/account/components/SecurityCard.tsx index 6d298988..64508e63 100644 --- a/src/pages/account/components/SecurityCard.tsx +++ b/src/pages/account/components/SecurityCard.tsx @@ -4,25 +4,20 @@ import { zodResolver } from '@hookform/resolvers/zod'; import { z } from 'zod'; import { useAuthActions } from '../../../lib/api/react'; import { Button } from '../../../components/ui/button'; -import { Input } from '../../../components/ui/input'; import { Label } from '../../../components/ui/label'; -import { Shield, Check, X } from 'lucide-react'; +import { Shield } from 'lucide-react'; +import { PasswordInput } from '../../../components/auth/PasswordInput'; +import { MIN_PASSWORD_LENGTH } from '../../../shared/constants'; import { toast } from 'sonner'; import { apiErrorCode } from '../../../lib/errors'; import { useTranslation } from 'react-i18next'; import type { TFunction } from 'i18next'; function buildSecuritySchema(t: TFunction<'account'>) { - return z - .object({ - oldPassword: z.string().min(1, t('security.oldRequired')), - newPassword: z.string().min(10, t('security.rules.length')), - confirmPassword: z.string().min(1, t('security.confirmRequired')), - }) - .refine((data) => data.newPassword === data.confirmPassword, { - message: t('security.mismatch'), - path: ['confirmPassword'], - }); + return z.object({ + oldPassword: z.string().min(1, t('security.oldRequired')), + newPassword: z.string().min(MIN_PASSWORD_LENGTH, t('security.rules.length')), + }); } type SecurityFormData = z.infer>; @@ -42,7 +37,6 @@ export function SecurityCard({ providers }: SecurityCardProps) { register, handleSubmit, reset, - watch, setError, formState: { errors, isSubmitting, isDirty }, } = useForm({ @@ -51,13 +45,9 @@ export function SecurityCard({ providers }: SecurityCardProps) { defaultValues: { oldPassword: '', newPassword: '', - confirmPassword: '', }, }); - const newPasswordValue = watch('newPassword') || ''; - const confirmPasswordValue = watch('confirmPassword') || ''; - const onSubmit = async (data: SecurityFormData) => { try { await changePassword(data.oldPassword, data.newPassword); @@ -82,25 +72,6 @@ export function SecurityCard({ providers }: SecurityCardProps) { } }; - const passwordRequirements = { - length: newPasswordValue.length >= 10, - uppercase: /[A-Z]/.test(newPasswordValue), - lowercase: /[a-z]/.test(newPasswordValue), - number: /[0-9]/.test(newPasswordValue), - special: /[!@#$%^&*(),.?":{}|<>]/.test(newPasswordValue), - }; - - const getPasswordStrength = () => { - const metRequirements = Object.values(passwordRequirements).filter(Boolean).length; - if (!newPasswordValue) return { text: '', color: '' }; - if (metRequirements <= 2) return { text: t('security.strength.weak'), color: 'bg-red-500' }; - if (metRequirements <= 4) - return { text: t('security.strength.medium'), color: 'bg-yellow-500' }; - return { text: t('security.strength.strong'), color: 'bg-green-500' }; - }; - - const strength = getPasswordStrength(); - return (
@@ -136,9 +107,9 @@ export function SecurityCard({ providers }: SecurityCardProps) {
- @@ -151,83 +122,19 @@ export function SecurityCard({ providers }: SecurityCardProps) {
- - {errors.newPassword && ( -

- {errors.newPassword.message} -

- )} - - {newPasswordValue && ( -
-
- {[1, 2, 3, 4, 5].map((i) => ( -
- ))} -
- {strength.text && ( -

{strength.text}

- )} -
- )} - -
- {(['length', 'uppercase', 'lowercase', 'number', 'special'] as const).map( - (rule) => ( - - ) - )} -
-
- -
- - - {errors.confirmPassword && ( -

- {errors.confirmPassword.message} -

- )} - {!errors.confirmPassword && newPasswordValue && confirmPasswordValue && ( -
- {newPasswordValue === confirmPasswordValue ? ( - <> - - - {t('passwordRules.match', { ns: 'auth' })} - - - ) : ( - <> - - - {t('passwordRules.noMatch', { ns: 'auth' })} - - - )} -
- )} +

+ {t('security.rules.length')} +

{isDirty && ( @@ -249,12 +156,3 @@ export function SecurityCard({ providers }: SecurityCardProps) {
); } - -function RequirementItem({ met, text }: { met: boolean; text: string }) { - return ( -
- {met ? : } - {text} -
- ); -} diff --git a/src/pages/administrator/AdminEventsPage.tsx b/src/pages/administrator/AdminEventsPage.tsx index 6ba04c97..d5f0a170 100644 --- a/src/pages/administrator/AdminEventsPage.tsx +++ b/src/pages/administrator/AdminEventsPage.tsx @@ -34,6 +34,7 @@ import { getUserFacingErrorMessage } from '../../lib/errors'; import { AdminGuard, AdminPageHeader, FilterTabs } from './components/AdminShared'; import { useTranslation } from 'react-i18next'; import { TableRowsSkeleton } from '../../components/ui/loading'; +import { formatEventPlace } from '../../shared/eventJsonLd'; type AdminEvent = Doc<'events'> & { isApproved: boolean; @@ -85,7 +86,7 @@ function Events() { (event) => !term || event.title.toLowerCase().includes(term) || - event.location.toLowerCase().includes(term) || + formatEventPlace(event).toLowerCase().includes(term) || (event.organizerName ?? '').toLowerCase().includes(term) || (event.organizerEmail ?? '').toLowerCase().includes(term) ) diff --git a/src/pages/dashboard/DashboardPage.test.tsx b/src/pages/dashboard/DashboardPage.test.tsx index fc34ff7e..7b7f49e7 100644 --- a/src/pages/dashboard/DashboardPage.test.tsx +++ b/src/pages/dashboard/DashboardPage.test.tsx @@ -277,11 +277,12 @@ describe('HomePage', () => { expect(screen.getByText('Landingpage')).toBeInTheDocument(); }); - it('remembers the sign-in, so returning users see no landing page while loading', () => { + it('remembers the sign-in, so returning users see no landing page while loading', async () => { seller(); vi.mocked(useAuthState).mockReturnValue({ isLoading: false, isAuthenticated: true }); renderAt(); - expect(screen.getByRole('heading', { name: 'Hallo Erika!' })).toBeInTheDocument(); + // The overview is its own chunk + expect(await screen.findByRole('heading', { name: 'Hallo Erika!' })).toBeInTheDocument(); expect(localStorage.getItem('bazarpro.signedIn')).toBe('1'); vi.mocked(useAuthState).mockReturnValue({ isLoading: true, isAuthenticated: false }); diff --git a/src/pages/dashboard/DashboardPage.tsx b/src/pages/dashboard/DashboardPage.tsx index 7aafbacb..f2a9b7df 100644 --- a/src/pages/dashboard/DashboardPage.tsx +++ b/src/pages/dashboard/DashboardPage.tsx @@ -31,6 +31,7 @@ import { useMarkNoticesSeen } from '../../hooks/useMarkNoticesSeen'; import { selectEvent, selectedOrCurrent, useSelectedEventId } from '../../lib/selectedEvent'; import { formatDateRangeDE, formatPriceDE } from '../../lib/utils'; import { AdminOverviewPage } from '../administrator/AdminOverviewPage'; +import { formatEventPlace } from '../../shared/eventJsonLd'; /** * Start page for signed-in users (#158), one per role of the role switch: sellers see @@ -507,7 +508,7 @@ function BazaarHero({ {event.location && ( - {event.location} + {formatEventPlace(event)} )}
diff --git a/src/pages/dashboard/HomePage.tsx b/src/pages/dashboard/HomePage.tsx index 36a250e5..7664db9d 100644 --- a/src/pages/dashboard/HomePage.tsx +++ b/src/pages/dashboard/HomePage.tsx @@ -1,8 +1,11 @@ -import { useEffect } from 'react'; +import { Suspense, useEffect } from 'react'; import { useAuthState } from '../../lib/api/react'; -import { DashboardPage } from './DashboardPage'; +import { lazyPage } from '../../lib/lazyPage'; import { PageSkeleton } from '../../components/ui/loading'; +// Visitors of `/` get the landing page; the overview loads only for signed-in users +const DashboardPage = lazyPage(() => import('./DashboardPage'), 'DashboardPage'); + /** Remembered sign-in, so a returning user sees no flash of the landing page */ const SIGNED_IN_KEY = 'bazarpro.signedIn'; @@ -28,7 +31,13 @@ export function HomePage({ landing }: { landing: React.ReactNode }) { } }, [isLoading, isAuthenticated]); - if (isAuthenticated) return ; + if (isAuthenticated) { + return ( + }> + + + ); + } if (isLoading && rememberedSignIn()) { return ; } diff --git a/src/pages/organizer/events/EditEventForm.edit.test.tsx b/src/pages/organizer/events/EditEventForm.edit.test.tsx index ad8ad906..9634fe5c 100644 --- a/src/pages/organizer/events/EditEventForm.edit.test.tsx +++ b/src/pages/organizer/events/EditEventForm.edit.test.tsx @@ -9,6 +9,7 @@ vi.mock('../../../lib/api/react', () => ({ useQuery: vi.fn(), useMutation: vi.fn(), useApiClient: () => ({}), + useAuthState: () => ({ isLoading: false, isAuthenticated: true }), })); // Radix checkboxes measure themselves; jsdom has no ResizeObserver @@ -141,6 +142,7 @@ describe('editing an event', () => { }); describe('creation wizard', () => { + const next = () => fireEvent.click(screen.getByRole('button', { name: 'Weiter' })); const fillBasics = (start: string, end: string) => { fireEvent.change(screen.getByLabelText('Titel der Veranstaltung *'), { target: { value: 'Kinderbasar' }, @@ -148,50 +150,63 @@ describe('creation wizard', () => { fireEvent.change(document.getElementById('description')!, { target: { value: 'Kleidung und Spielzeug für Kinder' }, }); - fireEvent.change(screen.getByLabelText('Ort *'), { target: { value: 'Turnhalle' } }); + fireEvent.change(screen.getByLabelText('Veranstaltungsort *'), { + target: { value: 'Turnhalle' }, + }); fireEvent.change(document.getElementById('startDate')!, { target: { value: start } }); fireEvent.change(document.getElementById('endDate')!, { target: { value: end } }); + fireEvent.change(screen.getByLabelText('Kontaktdaten / Veranstalter-Info *'), { + target: { value: 'Elternbeirat' }, + }); + }; + /** Picks the children's bazaar and goes through the settings to the details. */ + const toDetails = async () => { + fireEvent.click(screen.getByRole('button', { name: /^Kinderbasar/ })); + for (const step of [3, 4, 5, 6]) { + await screen.findByText(`Schritt ${step - 1} von 8`); + next(); + } + expect(await screen.findByText('Wann und wo?')).toBeInTheDocument(); }; it('does not move on with an end before the start, and goes back', async () => { mockBackend({}); renderAt('/events/new'); - fireEvent.click(screen.getByRole('button', { name: 'Ohne Vorlage weiter' })); - expect(await screen.findByText('Schritt 2 von 8')).toBeInTheDocument(); + await toDetails(); fillBasics('2099-04-18T13:00', '2099-04-18T09:00'); - fireEvent.click(screen.getByRole('button', { name: 'Weiter' })); + next(); expect(await screen.findByText('Enddatum muss nach dem Startdatum liegen')).toBeInTheDocument(); - expect(screen.getByText('Schritt 2 von 8')).toBeInTheDocument(); + expect(screen.getByText('Schritt 6 von 8')).toBeInTheDocument(); fireEvent.click(screen.getByRole('button', { name: 'Zurück' })); - expect(await screen.findByText('Schritt 1 von 8')).toBeInTheDocument(); - }); + expect(await screen.findByText('Schritt 5 von 8')).toBeInTheDocument(); + }, 20_000); it('a children’s bazaar preselects its categories and small labels', async () => { mockBackend({}); renderAt('/events/new'); - fireEvent.click(screen.getByRole('button', { name: /Kinderbasar \(Nummernbasar\)/ })); - fillBasics('2099-04-18T09:00', '2099-04-18T13:00'); - fireEvent.click(screen.getByRole('button', { name: 'Weiter' })); - expect(await screen.findByText('Schritt 3 von 8')).toBeInTheDocument(); - fireEvent.click(screen.getByRole('button', { name: 'Weiter' })); - fireEvent.change(await screen.findByLabelText('Kontaktdaten / Veranstalter-Info *'), { - target: { value: 'Elternbeirat' }, - }); - fireEvent.click(screen.getByRole('button', { name: 'Weiter' })); - + fireEvent.click(screen.getByRole('button', { name: /^Kinderbasar/ })); + next(); expect(await screen.findByText('Welche Artikel?')).toBeInTheDocument(); expect(screen.getByLabelText(/Etiketten/)).toHaveValue('small'); - for (let i = 0; i < 3; i++) { - fireEvent.click(screen.getByRole('button', { name: 'Weiter' })); - await screen.findByText(`Schritt ${6 + i} von 8`); + for (const step of [4, 5, 6]) { + next(); + await screen.findByText(`Schritt ${step} von 8`); } + fillBasics('2099-04-18T09:00', '2099-04-18T13:00'); + next(); + await screen.findByText('Schritt 7 von 8'); + next(); + // The last step shows the bazaar page + expect(await screen.findByText('So sieht dein Basar aus')).toBeInTheDocument(); + expect(screen.getByText('bazarpro.de/basar')).toBeInTheDocument(); fireEvent.click(screen.getByRole('button', { name: 'Veranstaltung erstellen' })); await waitFor(() => expect(createEvent).toHaveBeenCalledTimes(1)); expect(createEvent.mock.calls[0][0]).toMatchObject({ commission: 15, categories: ['toys'], + contactInfo: 'Elternbeirat', features: { labelFormat: 'small', photosOptional: true, maxItemsPerSeller: 50 }, }); }, 20_000); @@ -199,12 +214,12 @@ describe('creation wizard', () => { it('Enter in a field moves to the next step instead of creating the event', async () => { mockBackend({}); renderAt('/events/new'); - fireEvent.click(screen.getByRole('button', { name: 'Ohne Vorlage weiter' })); + await toDetails(); fillBasics('2099-04-18T09:00', '2099-04-18T13:00'); - fireEvent.submit(screen.getByLabelText('Ort *').closest('form')!); - expect(await screen.findByText('Schritt 3 von 8')).toBeInTheDocument(); + fireEvent.submit(screen.getByLabelText('Veranstaltungsort *').closest('form')!); + expect(await screen.findByText('Schritt 7 von 8')).toBeInTheDocument(); expect(createEvent).not.toHaveBeenCalled(); - }); + }, 20_000); it('shows that creating is switched off', () => { mockBackend({ flags: { is_event_creation_enabled: false } }); diff --git a/src/pages/organizer/events/EditEventForm.tsx b/src/pages/organizer/events/EditEventForm.tsx index 879f1e72..63125252 100644 --- a/src/pages/organizer/events/EditEventForm.tsx +++ b/src/pages/organizer/events/EditEventForm.tsx @@ -1,10 +1,11 @@ import { useEffect, useMemo, useRef, useState } from 'react'; -import { useForm, FormProvider, useFormContext } from 'react-hook-form'; -import { useNavigate, useParams } from 'react-router-dom'; +import { get, useForm, FormProvider, useFormContext } from 'react-hook-form'; +import { useNavigate, useParams, useSearchParams } from 'react-router-dom'; import { zodResolver } from '@hookform/resolvers/zod'; import { z } from 'zod'; +import { Eye } from 'lucide-react'; import { Button } from '../../../components/ui/button'; -import { useApiClient, useMutation, useQuery } from '../../../lib/api/react'; +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'; @@ -13,7 +14,7 @@ import { EditEventCategories } from './components/EditEventCategories'; import { EditEventContact } from './components/EditEventContact'; import { EditEventAccess } from './components/EditEventAccess'; import { EditEventMapSection } from './components/EditEventMapSection'; -import { EditEventFeatures } from './components/EditEventFeatures'; +import { DiscountStartField, EditEventFeatures } from './components/EditEventFeatures'; import { EditEventSellerInfo } from './components/EditEventSellerInfo'; import { logisticsFromForm } from '../../../lib/sellerLogistics'; import { @@ -22,8 +23,10 @@ import { type StoredEventFeatures, } from '../../../shared/eventFeatures'; import { + EVENT_COUNTRIES, EVENT_SERVICES, EVENT_VISIBILITY, + POSTAL_CODE_PATTERNS, type EventServices, type EventVisibility, } from '../../../shared/constants'; @@ -33,6 +36,12 @@ import { toast } from 'sonner'; import { getUserFacingErrorMessage } from '../../../lib/errors'; import { formatPriceDE } from '../../../lib/utils'; import { selectEvent } from '../../../lib/selectedEvent'; +import { + clearEventDraft, + CREATE_DRAFT_PATH, + loadEventDraft, + saveEventDraft, +} from '../../../lib/eventDraft'; /** Fees and item limit sellers registered with; they may only get better for sellers. */ interface RegisteredTerms { @@ -41,11 +50,27 @@ interface RegisteredTerms { maxItemsPerSeller?: number; } import { useTranslation } from 'react-i18next'; +import { coverFile, coverForKind, DEFAULT_COVER } from '../../../lib/eventCovers'; +import { WizardPictures } from './components/wizard/WizardPictures'; import { zodMessage } from '../../../i18n/zodMessage'; import i18n from '../../../i18n'; import { EventTypePicker } from './components/EventTypePicker'; -import { EVENT_TYPES, type EventTypeId } from '../../../lib/eventTypes'; -import { SellerConditions } from '../../../components/events/SellerConditions'; +import { formatEventPlace, placeFromLocation, type EventPlace } from '../../../shared/eventJsonLd'; +import { + EVENT_TYPES, + findEventType, + type EventType, + type EventTypeId, +} from '../../../lib/eventTypes'; +import { + EventPagePreview, + FeesPreview, + ItemsPreview, + ListingPreview, + LogisticsPreview, + PlacePreview, + SalePreview, +} from './components/wizard/WizardPreviews'; import { dateLocale } from '../../../i18n/format'; import { PageSkeleton } from '../../../components/ui/loading'; @@ -63,6 +88,22 @@ const buildEventSchema = ( title: z.string().min(3, zodMessage('form.titleShort', 'organizer')), description: z.string().min(10, zodMessage('form.descriptionShort', 'organizer')), location: z.string().min(1, zodMessage('form.locationRequired', 'organizer')), + address: z + .object({ + 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), + }) + .refine( + (address) => + !address.postalCode || POSTAL_CODE_PATTERNS[address.country].test(address.postalCode), + { ...zodMessage('form.postalCodeInvalid', 'organizer'), path: ['postalCode'] } + ) + .refine((address) => !address.postalCode || address.city.trim(), { + ...zodMessage('form.cityRequired', 'organizer'), + path: ['city'], + }), startDate: z .string() .refine( @@ -95,6 +136,7 @@ const buildEventSchema = ( vendorLimit: z.number().optional().or(z.nan()), coverImageFile: z.any().optional(), removeCoverImage: z.boolean().optional(), + coverTemplate: z.string().optional(), eventMapImageFile: z.any().optional(), removeEventMapImage: z.boolean().optional(), features: z.object({ @@ -146,10 +188,12 @@ const buildEventSchema = ( (data) => { const from = data.features.discountStartsAt; if (!data.features.discounts || !from) return true; + const start = new Date(data.startDate).getTime(); + const end = new Date(data.endDate).getTime(); + // Dates still open (or invalid): those fields report it, nothing to compare with yet + if (Number.isNaN(start) || Number.isNaN(end)) return true; const time = new Date(from).getTime(); - return ( - time >= new Date(data.startDate).getTime() && time <= new Date(data.endDate).getTime() - ); + return time >= start && time <= end; }, { ...zodMessage('form.discountInEvent', 'organizer'), @@ -196,6 +240,18 @@ const buildEventSchema = ( type EventFormData = z.infer>; 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' +>; + +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; +} function featuresToForm(stored: StoredEventFeatures | undefined): FeatureFormData { const features = resolveEventFeatures({ features: stored }); @@ -249,6 +305,32 @@ function featuresFromForm(features: FeatureFormData): StoredEventFeatures { }; } +type AddressFormData = EventFormData['address']; + +/** The address fields; older events only have the location, their address is read from it. */ +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'; + return { + street: event.street ?? '', + postalCode: event.postalCode ?? '', + city: event.city ?? '', + country, + }; + } + // Read only German addresses from the text: four digits could be any of the others + const { address } = placeFromLocation(event.location); + if (typeof address === 'string') return empty; + return { + street: address.streetAddress ?? '', + postalCode: address.postalCode ?? '', + city: address.addressLocality ?? '', + country: 'DE', + }; +} + type LogisticsFormData = EventFormData['sellerLogistics']; type StoredLogistics = NonNullable['sellerLogistics']>; @@ -272,31 +354,64 @@ function formatForDateTimeLocal(timestamp: number): string { return localtime.toISOString().slice(0, 16); } -/** Steps of the creation wizard and the form fields each one checks before moving on. */ +/** + * Steps of the creation wizard and the form fields each one checks before moving on. Only + * the fields shown in that step: an error elsewhere could not be seen, let alone fixed. + */ const WIZARD_STEPS = [ { id: 'type', fields: [] }, - { id: 'basics', fields: ['title', 'description', 'location', 'startDate', 'endDate'] }, - { id: 'sale', fields: ['features'] }, - { id: 'fees', fields: ['commission', 'contactInfo', 'features'] }, - { id: 'items', fields: ['categories', 'features'] }, - { id: 'registration', fields: ['visibility', 'accessCode', 'vendorLimit', 'features'] }, + // What makes the bazaar first, with a preview of each choice + { id: 'sale', fields: ['features.maxDiscountPercent'] }, + { id: 'items', fields: ['categories', 'features.maxItemsPerSeller'] }, + { id: 'fees', fields: ['commission', 'features.intakeFee'] }, + { id: 'registration', fields: ['visibility', 'accessCode', 'vendorLimit'] }, + // The exact details at the end + { + id: 'basics', + fields: [ + 'title', + 'description', + 'location', + 'address', + 'startDate', + 'endDate', + 'features.discountStartsAt', + 'contactInfo', + ], + }, { id: 'logistics', fields: ['sellerLogistics'] }, - { id: 'summary', fields: [] }, + { id: 'preview', fields: [] }, ] as const; +type WizardStepId = (typeof WIZARD_STEPS)[number]['id']; -function WizardHeader({ step }: { step: number }) { +function WizardHeader({ step, onGoTo }: { step: number; onGoTo: (step: number) => void }) { const { t } = useTranslation('organizer'); const id = WIZARD_STEPS[step].id; return (
-
+
    {WIZARD_STEPS.map((candidate, index) => ( -
    +
  1. + {/* Done steps can be opened again; later ones only with "next", which checks */} + +
  2. ))} -
    +

{t('wizard.progress', { step: step + 1, total: WIZARD_STEPS.length })}

@@ -306,14 +421,22 @@ function WizardHeader({ step }: { step: number }) { ); } -/** Last step: the key facts and the conditions exactly as sellers will see them. */ -function WizardSummary() { +/** Last step: the bazaar page as visitors will see it, and the key facts. */ +function WizardFinal({ type }: { type?: EventType }) { const { t } = useTranslation('organizer'); const { watch } = useFormContext(); const values = watch(); const start = values.startDate ? new Date(values.startDate) : undefined; return (
+
{t('wizard.summary.title')}
@@ -329,27 +452,41 @@ function WizardSummary() {
{t('wizard.summary.where')}
-
{values.location || '–'}
+
+ {values.location + ? formatEventPlace({ ...values.address, location: values.location }) + : '–'} +
{t('wizard.summary.categories')}
{values.categories.length}
-
-

{t('wizard.summary.sellersSee')}

- -
); } +/** The preview next to a step; the type and final steps show theirs full width. */ +function StepPreview({ id, type }: { id: WizardStepId; type?: EventType }) { + switch (id) { + case 'sale': + return ; + case 'items': + return ; + case 'fees': + return ; + case 'registration': + return ; + case 'basics': + return ; + case 'logistics': + return ; + default: + return null; + } +} + export function EditEventForm() { const { t } = useTranslation('organizer'); const navigate = useNavigate(); @@ -361,6 +498,10 @@ export function EditEventForm() { const params = useParams(); const eventId = params.eventId as Id<'events'> | undefined; const isEditing = !!eventId; + const [searchParams, setSearchParams] = useSearchParams(); + // Visitors try the wizard without an account; it is needed only to create the bazaar + const { isAuthenticated, isLoading: isAuthLoading } = useAuthState(); + const isGuest = !isEditing && !isAuthLoading && !isAuthenticated; const editEvent = useMutation(api.events.editEvent); const createLocationCategory = useMutation(api.eventLocationCategories.createCategory); @@ -368,7 +509,10 @@ export function EditEventForm() { const [pendingLocationCategories, setPendingLocationCategories] = useState([]); const categories = useQuery(api.categories.getAllCategories); - const pastEvents = useQuery(api.events.getMyEvents, !isEditing ? { includePast: true } : 'skip'); + const pastEvents = useQuery( + api.events.getMyEvents, + !isEditing && isAuthenticated ? { includePast: true } : 'skip' + ); const now = Date.now(); const isRunning = !!event && event.startDate <= now && now <= event.endDate; @@ -403,6 +547,7 @@ export function EditEventForm() { title: event ? event.title : '', description: event ? event.description : '', location: event ? event.location : '', + address: addressToForm(event), startDate: event ? formatForDateTimeLocal(event.startDate) : '', endDate: event ? formatForDateTimeLocal(event.endDate) : '', categories: event ? event.categories : [], @@ -414,6 +559,7 @@ export function EditEventForm() { vendorLimit: event ? event.vendorLimit : undefined, coverImageFile: undefined, removeCoverImage: false, + coverTemplate: eventId ? undefined : DEFAULT_COVER, eventMapImageFile: undefined, removeEventMapImage: false, features: featuresToForm(event?.features), @@ -435,6 +581,7 @@ export function EditEventForm() { title: event.title, description: event.description, location: event.location, + address: addressToForm(event), startDate: formatForDateTimeLocal(event.startDate), endDate: formatForDateTimeLocal(event.endDate), categories: event.categories, @@ -460,6 +607,7 @@ export function EditEventForm() { title: template.title, description: template.description, location: template.location, + address: addressToForm(template), startDate: '', endDate: '', categories: template.categories, @@ -471,6 +619,7 @@ export function EditEventForm() { vendorLimit: template.vendorLimit, coverImageFile: undefined, removeCoverImage: false, + coverTemplate: DEFAULT_COVER, // The discount start time belongs to the old date, so it is not copied features: { ...featuresToForm(template.features), discountStartsAt: '' }, // Times belong to the old date; the note for sellers is worth keeping @@ -484,7 +633,19 @@ export function EditEventForm() { // Creating goes through a wizard that explains each group of settings const [step, setStep] = useState(0); + // Every new step starts at the top: after it rendered, so a shorter step cannot stop + // the scrolling half way (on phones the buttons sit far below the start) + const shownStep = useRef(step); + useEffect(() => { + if (shownStep.current === step) return; + shownStep.current = step; + window.scrollTo({ top: 0, behavior: 'smooth' }); + }, [step]); const [eventType, setEventType] = useState(); + const chosenType = findEventType(eventType); + const stepId = WIZARD_STEPS[step].id; + // Settings and their preview side by side; the first and the last step are previews + const sideBySide = stepId !== 'type' && stepId !== 'preview'; const applyEventType = (id: EventTypeId) => { const type = EVENT_TYPES.find((candidate) => candidate.id === id); if (!type) return; @@ -494,6 +655,9 @@ export function EditEventForm() { .map((category) => category._id as string); reset({ ...current, + // A start for the title; the organizer adds town or year in "When and where?" + title: current.title.trim() ? current.title : t(`eventTypes.${type.id}.exampleTitle`), + coverTemplate: current.coverImageFile ? undefined : coverForKind(type.item), commission: type.commission, categories: matching.length > 0 ? matching : current.categories, features: featuresToForm(type.features), @@ -504,20 +668,75 @@ export function EditEventForm() { // An invalid field of an earlier step would stay hidden: go back to that step const showFirstInvalidStep = (errors: Record) => { const index = WIZARD_STEPS.findIndex((candidate) => - candidate.fields.some((field) => field in errors) + candidate.fields.some((field) => get(errors, field)) ); if (index >= 0) setStep(index); toast.error(t('wizard.fixErrors')); }; + const keepDraft = () => + saveEventDraft({ + values: draftValues(methods.getValues()), + pendingLocationCategories, + eventType, + }); 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(); setStep(next); - window.scrollTo({ top: 0, behavior: 'smooth' }); }; + // Own pictures need an account: back here after the login, the draft is still there + const loginForPictures = () => { + keepDraft(); + 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(); + 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); + useEffect(() => { + if (isEditing || isAuthLoading || !categories || draftHandled.current) return; + draftHandled.current = 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); + } + return; + } + reset({ ...methods.getValues(), ...draft.values }); + 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 }); + setCreatingDraft(true); + } else { + toast.info(t('wizard.draftRestored')); + } + // eslint-disable-next-line react-hooks/exhaustive-deps -- once, when auth and categories are known + }, [isEditing, isAuthLoading, categories, isAuthenticated]); + // Next render: onSubmit then sees the restored storage locations + useEffect(() => { + if (!creatingDraft) return; + void handleSubmit(onSubmit, showFirstInvalidStep)().finally(() => setCreatingDraft(false)); + // eslint-disable-next-line react-hooks/exhaustive-deps -- once per restored draft + }, [creatingDraft]); + const onSubmit = async (data: EventFormData) => { if (!isEventCreationEnabled && !isEditing) return; @@ -525,6 +744,16 @@ export function EditEventForm() { let coverImage: Id<'_storage'> | undefined = undefined; if (data.coverImageFile instanceof File) { coverImage = await client.upload(await generateUploadUrl(), data.coverImageFile); + } else if (!isEditing && data.coverTemplate) { + // Only a picture: the bazaar is created without it if it cannot be loaded + try { + coverImage = await client.upload( + await generateUploadUrl(), + await coverFile(data.coverTemplate) + ); + } catch (error) { + console.error('Failed to use the cover template:', error); + } } let eventMapImage: Id<'_storage'> | undefined = undefined; @@ -538,6 +767,7 @@ export function EditEventForm() { title: string; description: string; location: string; + address: AddressFormData; startDate: number; endDate: number; contactInfo: string; @@ -558,6 +788,7 @@ export function EditEventForm() { title: data.title, description: data.description, location: data.location, + address: data.address, startDate: new Date(data.startDate).getTime(), endDate: new Date(data.endDate).getTime(), contactInfo: data.contactInfo, @@ -596,6 +827,7 @@ export function EditEventForm() { title: data.title, description: data.description, location: data.location, + address: data.address, startDate: new Date(data.startDate).getTime(), endDate: new Date(data.endDate).getTime(), contactInfo: data.contactInfo, @@ -620,6 +852,7 @@ export function EditEventForm() { } } setPendingLocationCategories([]); + clearEventDraft(); toast.success(t('form.created')); // The new event becomes the chosen one right away, not only once its page renders: // whoever goes straight back to the overview finds it there @@ -637,14 +870,14 @@ export function EditEventForm() { if (isEditing && event === null) { return
{t('form.notFound')}
; } - if ((isEditing && event === undefined) || !categories) { + if ((isEditing && event === undefined) || !categories || isAuthLoading || creatingDraft) { return ; } return (
-
+

{isEditing ? t('form.editTitle') : t('form.newTitle')} @@ -716,53 +949,105 @@ export function EditEventForm() { void goToStep(step + 1); return; } - void handleSubmit(onSubmit, showFirstInvalidStep)(e); + void handleSubmit(isGuest ? onGuestSubmit : onSubmit, showFirstInvalidStep)(e); }} className="space-y-6" > - -
- {WIZARD_STEPS[step].id === 'type' && ( - - )} - {WIZARD_STEPS[step].id === 'basics' && ( - <> - - void goToStep(index)} /> +
+
+ {sideBySide && ( + + )} + {stepId === 'type' && ( + - - )} - {WIZARD_STEPS[step].id === 'sale' && ( - - )} - {WIZARD_STEPS[step].id === 'fees' && ( - <> - - - - )} - {WIZARD_STEPS[step].id === 'items' && ( - <> - - - - )} - {WIZARD_STEPS[step].id === 'registration' && ( - <> - - - + )} + {stepId === 'sale' && ( + + )} + {stepId === 'items' && ( + <> + + + + )} + {stepId === 'fees' && ( + <> + + + + )} + {stepId === 'registration' && ( + <> + + + + )} + {stepId === 'basics' && ( + <> + : undefined + } + /> + + + + )} + {stepId === 'logistics' && } + {stepId === 'preview' && ( +
+
+ +
+
+ +
+
+ )} +
+ {sideBySide && ( +
+ +
)} - {WIZARD_STEPS[step].id === 'logistics' && } - {WIZARD_STEPS[step].id === 'summary' && } -
+

{step > 0 && ( @@ -799,7 +1084,11 @@ export function EditEventForm() { className="flex-1" disabled={isSubmitting || !isEventCreationEnabled} > - {isSubmitting ? t('form.creating') : t('form.create')} + {isSubmitting + ? t('form.creating') + : isGuest + ? t('wizard.guestCreate') + : t('form.create')} )}
-
- - -

- {t('basic.imageHint', { width: IMAGE_UPLOAD_MAX_WIDTH, height: IMAGE_UPLOAD_MAX_HEIGHT })} -

-
+ {allowCoverImage && ( +
+ + +

+ {t('basic.imageHint', { + width: IMAGE_UPLOAD_MAX_WIDTH, + height: IMAGE_UPLOAD_MAX_HEIGHT, + })} +

+
+ )}
@@ -237,12 +252,72 @@ export function EditEventBasicInfo({
- + {errors.location && (

{errors.location.message as string}

)}
+
+ {t('basic.address')} +

{t('basic.addressHint')}

+
+ + +
+
+
+ + +
+
+ + +
+
+
+ + +
+ {addressErrors && ( +

+ { + (addressErrors.street?.message ?? + addressErrors.postalCode?.message ?? + addressErrors.city?.message) as string + } +

+ )} +
+
@@ -273,6 +348,7 @@ export function EditEventBasicInfo({ )}
+ {afterDates}
); } diff --git a/src/pages/organizer/events/components/EditEventContact.tsx b/src/pages/organizer/events/components/EditEventContact.tsx index 192ac6e0..71eeeb30 100644 --- a/src/pages/organizer/events/components/EditEventContact.tsx +++ b/src/pages/organizer/events/components/EditEventContact.tsx @@ -5,7 +5,16 @@ import { Input } from '../../../../components/ui/input'; import { feeLockHint, type FeeLock } from '../../../../lib/sellerFees'; import { useTranslation } from 'react-i18next'; -export function EditEventContact({ feeLock = null }: { feeLock?: FeeLock }) { +/** In the wizard the commission belongs to the fees, the contact to the details at the end. */ +export type ContactPart = 'contact' | 'commission'; + +export function EditEventContact({ + feeLock = null, + parts = ['contact', 'commission'], +}: { + feeLock?: FeeLock; + parts?: ContactPart[]; +}) { const { t } = useTranslation('organizer'); const lockCommission = feeLock === 'running'; const { @@ -15,39 +24,43 @@ export function EditEventContact({ feeLock = null }: { feeLock?: FeeLock }) { return (
-

{t('contact.title')}

+ {parts.includes('contact') &&

{t('contact.title')}

} -
- -