π
diff --git a/apps/sidecar/src/server.js b/apps/sidecar/src/server.js
index 7ad6df0..2416a31 100644
--- a/apps/sidecar/src/server.js
+++ b/apps/sidecar/src/server.js
@@ -178,6 +178,19 @@ async function fetchPretixItems(organizer, eventSlug, apiKey) {
return names;
}
+// Pretix `name` fields are localized objects ({ en, de, ... }) or plain strings.
+function pickPretixName(n) {
+ if (!n) return '';
+ if (typeof n === 'string') return n;
+ return n.en || n.de || n['*'] || Object.values(n)[0] || '';
+}
+
+// Fetch the organizer's display name (the owning company / organisation).
+async function fetchPretixOrganizerName(organizer, apiKey) {
+ const org = await pretixFetch(`/organizers/${encodeURIComponent(organizer)}/`, { apiKey });
+ return pickPretixName(org && org.name) || '';
+}
+
// List the key's organizers, and for each organizer its events (active only).
// Used by the admin "paste the API key" flow to populate the organizer +
// event-slug dropdowns from real data.
@@ -189,18 +202,12 @@ async function fetchPretixOptions(apiKey) {
`/organizers/${encodeURIComponent(org.slug)}/events/?is_active=true`,
{ apiKey },
);
- // Pretix `name` fields are localized objects ({ en, de, ... }) or strings.
- const pickName = (n) => {
- if (!n) return '';
- if (typeof n === 'string') return n;
- return n.en || n.de || n['*'] || Object.values(n)[0] || '';
- };
out.push({
slug: org.slug,
- name: pickName(org.name) || org.slug,
+ name: pickPretixName(org.name) || org.slug,
events: (events.results || []).map((e) => ({
slug: e.slug,
- name: pickName(e.name) || e.slug,
+ name: pickPretixName(e.name) || e.slug,
})),
});
}
@@ -467,6 +474,22 @@ async function runPretixSync(eventId) {
body: { p_event_id: event.id, p_attendees: attendees },
});
+ // Pull the organizer's display name (the owning company) and store it on the
+ // event so badges can bind a "Company / organizer" field. Best-effort: a
+ // failure here must not fail the attendee sync that already succeeded.
+ let company = null;
+ try {
+ company = await fetchPretixOrganizerName(event.pretix_organizer, apiKey);
+ if (company) {
+ await supabaseFetch(`/rest/v1/events?id=eq.${encodeURIComponent(event.id)}`, {
+ method: 'PATCH',
+ body: { company },
+ });
+ }
+ } catch (err) {
+ log('pretix: company fetch failed', { eventId: event.id, error: err.message });
+ }
+
const finishedAt = new Date().toISOString();
const result = {
event_id: event.id,
@@ -476,6 +499,7 @@ async function runPretixSync(eventId) {
status: 'success',
orders: orders.length,
attendees: attendees.length,
+ company,
skipped,
summary,
};
diff --git a/docs/architecture.md b/docs/architecture.md
index 022b6e1..fba91a1 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -95,13 +95,16 @@ A separate desktop-first React app for organizers, guarded to existing contacts
with **`is_admin`** or an **`@appe.at`** email. See [frontend/admin-app.md](./frontend/admin-app.md):
- **Views** β Dashboard (active event + aggregates), Contacts, Registrations,
Sponsors, Schedule (slots/sessions/speakers/material), Activity (manual event
- and session AI summaries), Raffle (attendee prize draws), Events, Interfaces,
+ and session AI summaries), Raffle (attendee prize draws), Badges (per-event
+ WYSIWYG badge layout editor), Events, Interfaces,
Reports and Settings.
- **Auth guard** β email-only magic links; non-admin sessions are rejected.
- **Key RPCs** β `reset_registration_qr_token` (regenerate a registration's
lanyard token + sync the Auth password), `adjust_points`, `upsert_contact`,
`create_registration`, `set_registration_type`, `set_session_material`, and the
raffle functions `get_raffle_pool` / `draw_raffle_winner` / `reset_raffle`
+ and the badge-layout functions `save_badge_layout` / `set_default_badge_layout`
+ / `delete_badge_layout`
(see [backend/rpcs.md](./backend/rpcs.md)). The deprecated AI stub is no longer
client-callable; generation uses authenticated [sidecar routes](./backend/feedback-ai.md).
diff --git a/docs/backend/rpcs.md b/docs/backend/rpcs.md
index 87fe9b6..f90a614 100644
--- a/docs/backend/rpcs.md
+++ b/docs/backend/rpcs.md
@@ -419,6 +419,37 @@ admin-readable via RLS. All three functions are `security definer` with an empty
`search_path`, revoke execution from `PUBLIC` / `anon`, and grant it back only to
`authenticated` (the admin check is enforced inside each function).
+## Badge editor
+
+Source: [20261015194531_badge_editor.sql](../../supabase/migrations/20261015194531_badge_editor.sql).
+
+The admin **Badges** view is a per-event WYSIWYG badge / PDF layout editor
+(modelled on pretix's "PDF Editor / Badge layout"). Each event owns one or more
+named **layouts** in `badge_layouts`: a page size in millimetres plus an ordered
+`elements` JSON array (text boxes, QR codes, images) with mm-based geometry, so
+the on-screen canvas maps 1:1 to print. Text/QR elements bind to attendee fields
+(`attendee_name`, `email`, `ticket_type`, `qr_token`, `event_name`, `company`, β¦)
+and are previewed against a real sample registration. The `company` field reads
+`events.company` (the Pretix organizer name β see
+[sidecar.md](./sidecar.md#pretix-sync)).
+
+- `save_badge_layout(p_event_id, p_name, p_page_width_mm, p_page_height_mm, p_elements, p_is_default)`
+ β `badge_layouts` row β **admin-only.** Upserts the layout matched on
+ `(event_id, name)`. When `p_is_default` is true, every other layout for the
+ event is demoted first, so the "one default per event" invariant holds
+ transactionally. Rejects blank names and non-array `elements`.
+- `set_default_badge_layout(p_id)` β `void` β **admin-only.** Promotes one layout
+ to the event's default and demotes the previous one.
+- `delete_badge_layout(p_id)` β `void` β **admin-only.** Removes a layout; the
+ default may not be deleted while other layouts exist (a usable default must
+ remain).
+
+`badge_layouts` cascades on event deletion, is admin-readable via RLS
+(`badge_layouts_admin_read`), and has a partial unique index enforcing a single
+default per event. All three functions are `security definer` with an empty
+`search_path`, revoke execution from `PUBLIC` / `anon`, and grant it back only to
+`authenticated` (the admin check is enforced inside each function).
+
## Error handling
RPCs raise Postgres exceptions with human-readable messages (e.g. `you cannot
diff --git a/docs/backend/schema.md b/docs/backend/schema.md
index 46c8fbc..364423d 100644
--- a/docs/backend/schema.md
+++ b/docs/backend/schema.md
@@ -71,6 +71,7 @@ queries everything for the active event and handles "no active event" gracefully
| `name` | `text` | e.g. "APPE 2026" |
| `start_date` / `end_date` | `date` | |
| `location` | `text` | nullable |
+| `company` | `text` | nullable β the owning organisation / company (e.g. the **Pretix organizer name**). Auto-filled by the Pretix sync; bindable on badges (see [sidecar.md](./sidecar.md)) |
| `is_active` | `boolean` | default `false` |
| `avg_feedback` | `numeric` | maintained aggregate |
| `num_sessions` | `integer` | maintained aggregate |
diff --git a/docs/backend/tests.md b/docs/backend/tests.md
index d1c5884..7f1b0fd 100644
--- a/docs/backend/tests.md
+++ b/docs/backend/tests.md
@@ -1,3 +1,29 @@
+# Badge Editor Regression
+
+After applying `20261015194531_badge_editor`, run:
+
+```sh
+docker exec -i supabase_db_Convivo psql -X -U postgres -d postgres \
+ -v ON_ERROR_STOP=1 < supabase/tests/badge_layout_tests.sql
+CONVIVO_ADMIN_URL=http://127.0.0.1:3001 npm test --prefix e2e -- badge-editor.spec.ts --project=chromium
+```
+
+The SQL fixture is rollback-only: fifteen assertions cover creating a default
+layout, upserting the same `(event_id, name)` in place, the one-default-per-event
+invariant when a new default is saved, per-event scoping, `set_default`
+promote/demote, refusing to delete the default while other layouts exist,
+deleting a non-default layout, rejecting blank names, and admin/non-admin/anon
+authorization (the non-admin read check runs as the real `authenticated` role so
+RLS is enforced). The browser suite is API-mocked and covers loading the default
+layout onto the millimetre canvas with a bound attendee name, adding/selecting a
+text element and its handles, editing `x` to move an element, saving via
+`save_badge_layout`, preview mode hiding the handles, the JSON view, a failed
+save, the mobile layout, the **Delete key** removing the selection, binding the
+**company / organizer** field, **align-centre** on the page, and **Shift-click
+multi-select** for group alignment. No real attendee data changes.
+
+See [RPC rules](./rpcs.md#badge-editor) and the [Badges view](../frontend/admin-app.md).
+
# Raffle Regression
After applying `20261015180640_raffle`, run:
diff --git a/docs/frontend/admin-app.md b/docs/frontend/admin-app.md
index b9ad4ed..a217427 100644
--- a/docs/frontend/admin-app.md
+++ b/docs/frontend/admin-app.md
@@ -21,6 +21,7 @@ It runs on **port 3001** (Vite dev) or as the `convivo-admin` Docker container
| **Schedule** | Slots (with a **type optionset** β `Session` / `Service Session`) + sessions (with speakers 1:N via a **multi-select search dropdown**, material upload with a **submitted / not submitted** state and `average_feedback`), plus an admin-only **Delete current schedule** action for the active event. |
| **Activity** | Tables of check-ins, connections, and feedback (per active event), with manual **Generate AI Summary** controls for the event and individual sessions. |
| **Raffle** | Draws eligible attendees one at a time for the active event. Configure the number of picks (default 5), then **Spin** a roulette that decelerates onto a server-chosen winner; repeat until the pick count is reached. Excludes staff/Admin and the leaderboard top 3, and no one can win twice in a run. **New run** clears the current winners. See [../backend/rpcs.md#raffle](../backend/rpcs.md#raffle). |
+| **Badges** | A **per-event WYSIWYG badge / PDF layout editor** (modelled on pretix's PDF Editor). Pick the event, then design one or more named **layouts** (a **Default** per event, switchable / creatable / deletable). Add **text boxes**, **QR codes** and **images** to a millimetre canvas; drag to move, use the 8 resize handles + rotation handle, **Shift-click to multi-select**, and **press `Del`** to remove. While dragging, **PowerPoint-style smart guides** appear β dashed alignment lines (edges / centres, page and neighbouring items) plus equal-spacing lines β and the element **snaps** to them. A **Word-style align** toolbar (left / center / right, top / middle / bottom) plus **PowerPoint-style** object alignment β align to the **page** or to the **selection**, and **distribute** horizontally / vertically β with the same controls in the properties panel. Text binds to attendee fields (name, email, ticket type, QR token, event name, **company / organizer**, or static) with font, size, line-height, colour, bold/italic, alignment and case transform; QR binds to the token / check-in URL / email / name / static. **Undo/redo**, a **Preview** mode (no handles), a **JSON** view of the layout, and **Save**. Previewed against a real sample registration. See [../backend/rpcs.md#badge-editor](../backend/rpcs.md#badge-editor). |
| **Settings** | Global LLM endpoint, model and optional API key for feedback summaries. |
| **Events** | Create event, toggle active/inactive (a switch; only one can be active at a time β activating one deactivates the rest), edit dates/location + the **Sessionize endpoint** + the **Real-time clock** toggle (on = the attendee app uses the real system clock for Live/Next/Done; off = the simulated mid-event clock, the default). Each row has a **Sync** button that runs a (blocking) Sessionize sync and shows a result modal. |
| **Interfaces** | Manages the Sessionize sync **sidecar**: status (online / running / last run), a **Run sync** control (event picker + blocking run + result modal), an **Import Excel** control (upload the Sessionize "Sessions and speakers (advanced)" `.xlsx` + a "How to get this file" tooltip), and a **Recent runs** table from `sync_runs`. See [../backend/sidecar.md](../backend/sidecar.md). |
diff --git a/e2e/tests/badge-editor.spec.ts b/e2e/tests/badge-editor.spec.ts
new file mode 100644
index 0000000..bff7708
--- /dev/null
+++ b/e2e/tests/badge-editor.spec.ts
@@ -0,0 +1,183 @@
+import { test, expect, type Page } from '@playwright/test';
+
+const adminUrl = process.env.CONVIVO_ADMIN_URL || 'http://localhost:3001';
+const eventId = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';
+const user = { id: '99999999-9999-4999-8999-999999999999', email: 'admin@appe.at', aud: 'authenticated', role: 'authenticated', app_metadata: {}, user_metadata: {} };
+
+interface Options { layouts?: Record[]; failSave?: boolean; }
+
+async function openBadgeEditor(page: Page, options: Options = {}) {
+ const payload = Buffer.from(JSON.stringify({ sub: user.id, exp: Math.floor(Date.now() / 1000) + 3600 })).toString('base64url');
+ const session = { user, access_token: `eyJhbGciOiJIUzI1NiJ9.${payload}.test`, refresh_token: 'mock-refresh-token', expires_in: 3600, token_type: 'bearer' };
+ const event = { id: eventId, name: 'Badge Conference', company: 'Austrian Power Platform Enthusiasts', is_active: true, start_date: '2026-10-23', end_date: '2026-10-23', num_registrations: 3, num_sessions: 0, num_speakers: 0 };
+ const contact = { email: user.email, full_name: 'Admin', is_admin: true };
+ const attendee = { email: 'jane@example.com', full_name: 'Jane Attendee', is_admin: false };
+ const layouts = options.layouts ?? [
+ {
+ id: 'l-default', event_id: eventId, name: 'Default', is_default: true,
+ page_width_mm: 100, page_height_mm: 70, created_at: '2026-10-23T10:00:00Z', updated_at: '2026-10-23T10:00:00Z',
+ elements: [
+ { id: 'e-text', type: 'text', x: 10, y: 10, width: 60, height: 10, rotation: 0, content: 'attendee_name', text: '', font: 'Open Sans', font_size: 13, line_height: 1, color: '#000000', bold: false, italic: false, align_h: 'left', align_v: 'middle', transform: 'none' },
+ { id: 'e-qr', type: 'qr', x: 70, y: 40, width: 22, height: 22, rotation: 0, value: 'qr_token', static_value: '' },
+ ],
+ },
+ ];
+ const saves: Record[] = [];
+ let deletes = 0;
+ let setDefaults = 0;
+
+ await page.route('**/auth/v1/**', route => route.fulfill({ json: new URL(route.request().url()).pathname.endsWith('/user') ? user : session }));
+ await page.route('**/rest/v1/**', route => {
+ const url = new URL(route.request().url());
+ if (url.pathname.endsWith('/rpc/save_badge_layout')) {
+ if (options.failSave) return route.fulfill({ status: 400, json: { code: 'P0001', message: 'admin only' } });
+ const body = JSON.parse(route.request().postData() || '{}');
+ saves.push(body);
+ return route.fulfill({ json: { id: 'l-default', event_id: eventId, name: body.p_name, is_default: body.p_is_default, page_width_mm: body.p_page_width_mm, page_height_mm: body.p_page_height_mm, elements: body.p_elements, created_at: '2026-10-23T10:00:00Z', updated_at: '2026-10-23T11:00:00Z' } });
+ }
+ if (url.pathname.endsWith('/rpc/set_default_badge_layout')) { setDefaults += 1; return route.fulfill({ json: null }); }
+ if (url.pathname.endsWith('/rpc/delete_badge_layout')) { deletes += 1; return route.fulfill({ json: null }); }
+ if (url.pathname.endsWith('/badge_layouts')) return route.fulfill({ json: layouts });
+ if (url.pathname.endsWith('/registrations')) return route.fulfill({ json: [{ id: 'r1', event_id: eventId, contact_email: 'jane@example.com', type: 'attendee', qr_token: 'CV-JANE-01', points: 0 }] });
+ if (url.pathname.endsWith('/events')) return route.fulfill({ json: url.searchParams.has('is_active') ? event : [event] });
+ if (url.pathname.endsWith('/contacts')) return route.fulfill({ json: url.searchParams.has('email') ? contact : [contact, attendee] });
+ return route.fulfill({ json: [] });
+ });
+
+ await page.goto(`${adminUrl}/auth/callback#access_token=${session.access_token}&refresh_token=${session.refresh_token}&type=magiclink`);
+ await expect(page.locator('.nav').getByRole('button', { name: /Dashboard/ })).toBeVisible();
+ await page.locator('.nav').getByRole('button', { name: /Badges/ }).click();
+ return { saves, deleteCount: () => deletes, setDefaultCount: () => setDefaults };
+}
+
+test('badge editor loads the default layout onto a millimetre canvas', async ({ page }, testInfo) => {
+ await page.setViewportSize({ width: 1280, height: 900 });
+ await openBadgeEditor(page);
+ await expect(page.getByRole('heading', { name: 'Badge Editor' })).toBeVisible();
+ await expect(page.getByLabel('Badge layout')).toHaveValue('Default');
+ await expect(page.locator('.badge-page')).toBeVisible();
+ await expect(page.locator('.badge-el')).toHaveCount(2);
+ // The bound attendee name resolves against the real sample registration.
+ await expect(page.locator('.badge-el-text')).toContainText('Jane Attendee');
+ await page.screenshot({ path: testInfo.outputPath('badge-editor.png'), fullPage: true });
+});
+
+test('adding a text element selects it and opens its properties', async ({ page }) => {
+ await page.setViewportSize({ width: 1280, height: 900 });
+ await openBadgeEditor(page);
+ await page.getByRole('button', { name: 'Text', exact: true }).click();
+ await expect(page.locator('.badge-el')).toHaveCount(3);
+ await expect(page.getByText('Text box', { exact: true })).toBeVisible();
+ await expect(page.getByLabel('Content')).toBeVisible();
+ // A selected element shows its resize + rotate handles.
+ await expect(page.locator('.badge-handle')).toHaveCount(9);
+});
+
+test('editing the x position moves the element on the canvas', async ({ page }) => {
+ await page.setViewportSize({ width: 1280, height: 900 });
+ await openBadgeEditor(page);
+ await page.locator('.badge-el').first().click();
+ await expect(page.getByText('Text box', { exact: true })).toBeVisible();
+ const before = await page.locator('.badge-el').first().evaluate((n) => (n as HTMLElement).style.left);
+ await page.getByLabel('x (mm)').fill('50');
+ const after = await page.locator('.badge-el').first().evaluate((n) => (n as HTMLElement).style.left);
+ expect(parseFloat(after)).toBeGreaterThan(parseFloat(before));
+});
+
+test('saving posts the layout to save_badge_layout', async ({ page }) => {
+ await page.setViewportSize({ width: 1280, height: 900 });
+ const { saves } = await openBadgeEditor(page);
+ await page.getByRole('button', { name: 'Text', exact: true }).click();
+ await page.getByRole('button', { name: 'Save' }).click();
+ await expect.poll(() => saves.length).toBe(1);
+ expect(saves[0]).toMatchObject({ p_event_id: eventId, p_name: 'Default', p_is_default: true });
+ expect((saves[0].p_elements as unknown[]).length).toBe(3);
+});
+
+test('preview mode hides the editing handles', async ({ page }) => {
+ await page.setViewportSize({ width: 1280, height: 900 });
+ await openBadgeEditor(page);
+ await page.locator('.badge-el').first().click();
+ await expect(page.locator('.badge-handle')).toHaveCount(9);
+ await page.getByRole('button', { name: 'Preview' }).click();
+ await expect(page.locator('.badge-handle')).toHaveCount(0);
+});
+
+test('the JSON view shows the current layout', async ({ page }) => {
+ await page.setViewportSize({ width: 1280, height: 900 });
+ await openBadgeEditor(page);
+ await page.getByRole('button', { name: 'Layout JSON' }).click();
+ await expect(page.locator('.badge-json')).toBeVisible();
+ await expect(page.locator('.badge-json')).toContainText('"attendee_name"');
+});
+
+test('a failed save keeps the editor usable and reports the error', async ({ page }) => {
+ await page.setViewportSize({ width: 1280, height: 900 });
+ await openBadgeEditor(page, { failSave: true });
+ await page.getByRole('button', { name: 'Text', exact: true }).click();
+ await page.getByRole('button', { name: 'Save' }).click();
+ await expect(page.getByText('admin only')).toBeVisible();
+ await expect(page.locator('.badge-el')).toHaveCount(3);
+});
+
+test('badge controls fit a mobile viewport', async ({ page }) => {
+ await page.setViewportSize({ width: 390, height: 844 });
+ await openBadgeEditor(page);
+ await expect(page.getByRole('heading', { name: 'Badge Editor' })).toBeVisible();
+ await expect(page.getByRole('button', { name: 'Save' })).toBeVisible();
+});
+
+test('the Delete key removes the selected element', async ({ page }) => {
+ await page.setViewportSize({ width: 1280, height: 900 });
+ await openBadgeEditor(page);
+ await page.locator('.badge-el').first().click();
+ await expect(page.locator('.badge-handle')).toHaveCount(9);
+ await page.keyboard.press('Delete');
+ await expect(page.locator('.badge-el')).toHaveCount(1);
+});
+
+test('a text box can bind the company / organizer field', async ({ page }) => {
+ await page.setViewportSize({ width: 1280, height: 900 });
+ await openBadgeEditor(page);
+ await page.getByRole('button', { name: 'Text', exact: true }).click();
+ await page.getByLabel('Content').selectOption('company');
+ await expect(page.locator('.badge-text-body', { hasText: 'Austrian Power Platform Enthusiasts' })).toBeVisible();
+});
+
+test('align-centers horizontally centers the element on the page', async ({ page }) => {
+ await page.setViewportSize({ width: 1280, height: 900 });
+ await openBadgeEditor(page);
+ // The default text box is x=10, width=60 on a 100mm page β centered x = 20.
+ await page.locator('.badge-el').first().click();
+ await page.getByTitle('Align centers horizontally').first().click();
+ await expect(page.getByLabel('x (mm)')).toHaveValue('20');
+});
+
+test('shift-click selects multiple elements for group alignment', async ({ page }) => {
+ await page.setViewportSize({ width: 1280, height: 900 });
+ await openBadgeEditor(page);
+ await page.locator('.badge-el').first().click();
+ await page.locator('.badge-el').nth(1).click({ modifiers: ['Shift'] });
+ await expect(page.getByText('2 selected')).toBeVisible();
+ // Both selected elements show their own handles (9 each).
+ await expect(page.locator('.badge-handle')).toHaveCount(18);
+});
+
+test('dragging near the page centre shows a smart guide and snaps', async ({ page }) => {
+ await page.setViewportSize({ width: 1280, height: 900 });
+ await openBadgeEditor(page);
+ const pageBox = await page.locator('.badge-page').boundingBox();
+ const qr = page.locator('.badge-el').nth(1); // the QR element
+ const qrBox = await qr.boundingBox();
+ if (!pageBox || !qrBox) throw new Error('missing boxes');
+ const startX = qrBox.x + qrBox.width / 2;
+ const startY = qrBox.y + qrBox.height / 2;
+ const targetX = pageBox.x + pageBox.width / 2; // drag the QR centre to the page centre
+ await page.mouse.move(startX, startY);
+ await page.mouse.down();
+ await page.mouse.move(targetX - 2, startY, { steps: 8 }); // just short of centre β within snap threshold
+ await expect(page.locator('.badge-guide')).toBeVisible();
+ await page.mouse.up();
+ // After snapping, the QR centre sits on the page centre (x = 50 - w/2 = 39mm).
+ await expect(page.getByLabel('x (mm)')).toHaveValue('39');
+});
diff --git a/supabase/migrations/20261015194531_badge_editor.sql b/supabase/migrations/20261015194531_badge_editor.sql
new file mode 100644
index 0000000..8f29d28
--- /dev/null
+++ b/supabase/migrations/20261015194531_badge_editor.sql
@@ -0,0 +1,162 @@
+-- -----------------------------------------------------------------------------
+-- Badge editor (per-event WYSIWYG badge / PDF layout, modelled on pretix's
+-- "PDF Editor / Badge layout").
+--
+-- Each event owns one or more named badge layouts. A layout is a page size
+-- (millimetres) plus an ordered list of elements stored as JSON. The Admin app
+-- renders/edits the layout on a canvas and previews it against a real sample
+-- attendee; the element geometry is millimetre-based so it maps 1:1 to print.
+--
+-- `elements` is a JSON array; each element is an object:
+-- {
+-- "id": string, -- stable client id (uuid-ish)
+-- "type": "text" | "qr" | "image",
+-- "x": mm, "y": mm, "width": mm, "height": mm, "rotation": deg,
+-- -- type = "text":
+-- "content": "attendee_name" | "full_name" | "email" | "ticket_type"
+-- | "event_name" | "qr_token" | "static",
+-- "text": string, -- literal text when content = "static"
+-- "font": string, "font_size": pt, "line_height": number,
+-- "color": "#rrggbb", "bold": bool, "italic": bool,
+-- "align_h": "left" | "center" | "right",
+-- "align_v": "top" | "middle" | "bottom",
+-- "transform": "none" | "uppercase" | "lowercase" | "capitalize",
+-- -- type = "qr":
+-- "value": "qr_token" | "checkin_url" | "email" | "attendee_name" | "static",
+-- "static_value": string, -- literal payload when value = "static"
+-- -- type = "image":
+-- "src": string, -- absolute URL or data: URI
+-- "fit": "contain" | "cover" | "fill"
+-- }
+-- -----------------------------------------------------------------------------
+
+create table public.badge_layouts (
+ id uuid primary key default gen_random_uuid(),
+ event_id uuid not null references public.events (id) on delete cascade,
+ name text not null check (btrim(name) <> ''),
+ is_default boolean not null default false,
+ page_width_mm numeric not null default 100 check (page_width_mm > 0 and page_width_mm <= 1000),
+ page_height_mm numeric not null default 70 check (page_height_mm > 0 and page_height_mm <= 1000),
+ elements jsonb not null default '[]'::jsonb check (jsonb_typeof(elements) = 'array'),
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now(),
+ unique (event_id, name)
+);
+
+create index badge_layouts_event_id_idx on public.badge_layouts (event_id);
+-- At most one default layout per event.
+create unique index badge_layouts_one_default on public.badge_layouts (event_id) where is_default;
+
+alter table public.badge_layouts enable row level security;
+revoke all on public.badge_layouts from public, anon, authenticated;
+grant select on public.badge_layouts to authenticated;
+grant select, insert, update, delete on public.badge_layouts to service_role;
+
+create policy badge_layouts_admin_read on public.badge_layouts
+ for select to authenticated using (public.is_admin());
+
+-- -----------------------------------------------------------------------------
+-- Write RPCs. All are admin-only (checked inside, mirroring the raffle RPCs) so
+-- the exclusive-default invariant is enforced transactionally rather than by
+-- racing client writes.
+-- -----------------------------------------------------------------------------
+
+-- Insert or update a layout (matched on event_id + name). When p_is_default is
+-- true, every other layout for the event is demoted first.
+create or replace function public.save_badge_layout(
+ p_event_id uuid,
+ p_name text,
+ p_page_width_mm numeric,
+ p_page_height_mm numeric,
+ p_elements jsonb,
+ p_is_default boolean default false
+) returns public.badge_layouts
+language plpgsql security definer set search_path = '' as $$
+declare
+ v_row public.badge_layouts;
+begin
+ if not public.is_admin() then
+ raise exception 'admin only' using errcode = '42501';
+ end if;
+ if p_name is null or btrim(p_name) = '' then
+ raise exception 'layout name is required';
+ end if;
+ if jsonb_typeof(p_elements) <> 'array' then
+ raise exception 'elements must be a JSON array';
+ end if;
+
+ if p_is_default then
+ update public.badge_layouts
+ set is_default = false
+ where event_id = p_event_id and name <> btrim(p_name);
+ end if;
+
+ insert into public.badge_layouts
+ (event_id, name, is_default, page_width_mm, page_height_mm, elements, updated_at)
+ values
+ (p_event_id, btrim(p_name), p_is_default, p_page_width_mm, p_page_height_mm, p_elements, now())
+ on conflict (event_id, name) do update
+ set is_default = excluded.is_default,
+ page_width_mm = excluded.page_width_mm,
+ page_height_mm = excluded.page_height_mm,
+ elements = excluded.elements,
+ updated_at = now()
+ returning * into v_row;
+ return v_row;
+end;
+$$;
+
+-- Promote a layout to the event's default (demoting the previous one).
+create or replace function public.set_default_badge_layout(p_id uuid)
+returns void
+language plpgsql security definer set search_path = '' as $$
+declare
+ v_event uuid;
+begin
+ if not public.is_admin() then
+ raise exception 'admin only' using errcode = '42501';
+ end if;
+ select event_id into v_event from public.badge_layouts where id = p_id;
+ if v_event is null then
+ raise exception 'badge layout not found';
+ end if;
+ update public.badge_layouts set is_default = false where event_id = v_event and id <> p_id;
+ update public.badge_layouts set is_default = true, updated_at = now() where id = p_id;
+end;
+$$;
+
+-- Delete a layout. The default layout may not be removed while other layouts
+-- exist (there must always be a usable default).
+create or replace function public.delete_badge_layout(p_id uuid)
+returns void
+language plpgsql security definer set search_path = '' as $$
+declare
+ v_event uuid;
+ v_is_default boolean;
+ v_count integer;
+begin
+ if not public.is_admin() then
+ raise exception 'admin only' using errcode = '42501';
+ end if;
+ select event_id, is_default into v_event, v_is_default
+ from public.badge_layouts where id = p_id;
+ if v_event is null then
+ raise exception 'badge layout not found';
+ end if;
+ if v_is_default then
+ select count(*) into v_count from public.badge_layouts where event_id = v_event;
+ if v_count > 1 then
+ raise exception 'cannot delete the default layout while other layouts exist; set another as default first';
+ end if;
+ end if;
+ delete from public.badge_layouts where id = p_id;
+end;
+$$;
+
+revoke all on function public.save_badge_layout(uuid, text, numeric, numeric, jsonb, boolean)
+ from public, anon, authenticated;
+revoke all on function public.set_default_badge_layout(uuid) from public, anon, authenticated;
+revoke all on function public.delete_badge_layout(uuid) from public, anon, authenticated;
+grant execute on function public.save_badge_layout(uuid, text, numeric, numeric, jsonb, boolean) to authenticated;
+grant execute on function public.set_default_badge_layout(uuid) to authenticated;
+grant execute on function public.delete_badge_layout(uuid) to authenticated;
diff --git a/supabase/migrations/20261015200719_events_company.sql b/supabase/migrations/20261015200719_events_company.sql
new file mode 100644
index 0000000..5a66173
--- /dev/null
+++ b/supabase/migrations/20261015200719_events_company.sql
@@ -0,0 +1,12 @@
+-- -----------------------------------------------------------------------------
+-- Organizer / company name for an event.
+--
+-- The Pretix organizer resource carries the owning organisation's display name
+-- (e.g. "Austrian Power Platform Enthusiasts"). The sidecar now pulls it during
+-- the Pretix sync and stores it here so badges (and other print material) can
+-- bind a "Company / organizer" field, independent of the event's own name.
+-- -----------------------------------------------------------------------------
+
+alter table public.events add column if not exists company text;
+comment on column public.events.company is
+ 'The owning organisation / company (e.g. the Pretix organizer name). Synced from Pretix; also bindable on badges.';
diff --git a/supabase/tests/badge_layout_tests.sql b/supabase/tests/badge_layout_tests.sql
new file mode 100644
index 0000000..c68f355
--- /dev/null
+++ b/supabase/tests/badge_layout_tests.sql
@@ -0,0 +1,144 @@
+\set ON_ERROR_STOP on
+begin;
+
+create temporary table badge_results (name text);
+grant insert on badge_results to authenticated, anon;
+create function pg_temp.assert_badge(p_condition boolean, p_name text) returns void
+language plpgsql as $$
+begin
+ if p_condition is distinct from true then raise exception 'FAIL: %', p_name; end if;
+ insert into badge_results values (p_name);
+end;
+$$;
+
+-- Two isolated events so per-event scoping can be checked.
+update public.events set is_active = false where is_active;
+insert into public.events (id, name, start_date, end_date, is_active) values
+ ('b0de0001-0000-0000-0000-000000000001', 'Badge event A', current_date, current_date, true),
+ ('b0de0002-0000-0000-0000-000000000002', 'Badge event B', current_date, current_date, false);
+
+insert into public.contacts (email, full_name, is_admin) values
+ ('bd-admin@example.test', 'Badge Admin', true),
+ ('bd-viewer@example.test', 'Plain Viewer', false);
+
+-- Act as the badge admin.
+select set_config('request.jwt.claims', '{"email":"bd-admin@example.test","role":"authenticated"}', true);
+
+-- Save a default layout for event A.
+select pg_temp.assert_badge(
+ (select is_default from public.save_badge_layout(
+ 'b0de0001-0000-0000-0000-000000000001'::uuid, 'Default', 100, 70,
+ '[{"id":"a","type":"text","x":10,"y":10,"width":60,"height":10,"rotation":0,"content":"attendee_name","text":"","font":"Open Sans","font_size":13,"line_height":1,"color":"#000000","bold":false,"italic":false,"align_h":"left","align_v":"middle","transform":"none"}]'::jsonb, true)),
+ 'save creates a default layout');
+
+-- Upsert the same (event, name) updates in place rather than duplicating.
+select public.save_badge_layout('b0de0001-0000-0000-0000-000000000001'::uuid, 'Default', 105, 75, '[]'::jsonb, true);
+select pg_temp.assert_badge(
+ (select count(*) = 1 from public.badge_layouts where event_id = 'b0de0001-0000-0000-0000-000000000001' and name = 'Default'),
+ 're-saving the same name upserts');
+select pg_temp.assert_badge(
+ (select page_width_mm = 105 from public.badge_layouts where event_id = 'b0de0001-0000-0000-0000-000000000001' and name = 'Default'),
+ 'upsert updates page size');
+
+-- A second default layout demotes the first (only one default per event).
+select public.save_badge_layout('b0de0001-0000-0000-0000-000000000001'::uuid, 'VIP', 90, 50, '[]'::jsonb, true);
+select pg_temp.assert_badge(
+ (select count(*) = 1 from public.badge_layouts where event_id = 'b0de0001-0000-0000-0000-000000000001' and is_default),
+ 'only one default per event after saving a new default');
+select pg_temp.assert_badge(
+ (select is_default from public.badge_layouts where event_id = 'b0de0001-0000-0000-0000-000000000001' and name = 'VIP'),
+ 'newest default is the VIP layout');
+
+-- Layouts are scoped per event: event B has none of its own.
+select public.save_badge_layout('b0de0002-0000-0000-0000-000000000002'::uuid, 'Default', 100, 70, '[]'::jsonb, true);
+select pg_temp.assert_badge(
+ (select count(*) = 1 from public.badge_layouts where event_id = 'b0de0002-0000-0000-0000-000000000002'),
+ 'event B has its own layout');
+select pg_temp.assert_badge(
+ (select count(*) = 2 from public.badge_layouts where event_id = 'b0de0001-0000-0000-0000-000000000001'),
+ 'event A still has two layouts');
+
+-- set_default_badge_layout promotes the target and demotes the rest.
+select public.set_default_badge_layout(
+ (select id from public.badge_layouts where event_id = 'b0de0001-0000-0000-0000-000000000001' and name = 'Default'));
+select pg_temp.assert_badge(
+ (select is_default from public.badge_layouts where event_id = 'b0de0001-0000-0000-0000-000000000001' and name = 'Default'),
+ 'set_default promotes the chosen layout');
+select pg_temp.assert_badge(
+ (select not is_default from public.badge_layouts where event_id = 'b0de0001-0000-0000-0000-000000000001' and name = 'VIP'),
+ 'set_default demotes the previous default');
+
+-- The default layout cannot be deleted while other layouts exist.
+do $$ begin
+ begin
+ perform public.delete_badge_layout(
+ (select id from public.badge_layouts where event_id = 'b0de0001-0000-0000-0000-000000000001' and name = 'Default'));
+ raise exception 'default layout delete allowed';
+ exception when raise_exception then
+ if sqlerrm not like 'cannot delete the default layout%' then raise; end if;
+ end;
+ perform pg_temp.assert_badge(true, 'cannot delete default while others exist');
+end; $$;
+
+-- A non-default layout deletes cleanly.
+select public.delete_badge_layout(
+ (select id from public.badge_layouts where event_id = 'b0de0001-0000-0000-0000-000000000001' and name = 'VIP'));
+select pg_temp.assert_badge(
+ (select count(*) = 1 from public.badge_layouts where event_id = 'b0de0001-0000-0000-0000-000000000001'),
+ 'non-default layout deletes');
+
+-- Empty / blank names are rejected.
+do $$ begin
+ begin
+ perform public.save_badge_layout('b0de0001-0000-0000-0000-000000000001'::uuid, ' ', 100, 70, '[]'::jsonb, false);
+ raise exception 'blank name allowed';
+ exception when raise_exception then
+ if sqlerrm <> 'layout name is required' then raise; end if;
+ end;
+ perform pg_temp.assert_badge(true, 'blank layout name rejected');
+end; $$;
+
+-- Non-admins cannot write.
+select set_config('request.jwt.claims', '{"email":"bd-viewer@example.test","role":"authenticated"}', true);
+do $$ begin
+ begin
+ perform public.save_badge_layout('b0de0001-0000-0000-0000-000000000001'::uuid, 'Hacked', 100, 70, '[]'::jsonb, false);
+ raise exception 'non-admin save allowed';
+ exception when insufficient_privilege then
+ if sqlerrm <> 'admin only' then raise; end if;
+ end;
+ begin
+ perform public.delete_badge_layout(
+ (select id from public.badge_layouts limit 1));
+ raise exception 'non-admin delete allowed';
+ exception when insufficient_privilege then
+ if sqlerrm <> 'admin only' then raise; end if;
+ end;
+ perform pg_temp.assert_badge(true, 'non-admin cannot save or delete');
+end; $$;
+
+-- Non-admins cannot read layouts either (admin-read RLS). Run as the real
+-- `authenticated` role so RLS is enforced (the superuser would bypass it).
+set local role authenticated;
+select set_config('request.jwt.claims', '{"email":"bd-viewer@example.test","role":"authenticated"}', true);
+select pg_temp.assert_badge(
+ (select count(*) = 0 from public.badge_layouts),
+ 'non-admin sees no layouts via RLS');
+reset role;
+
+-- The anonymous API role has no execute grant at all.
+reset role;
+select set_config('request.jwt.claims', '{"role":"anon"}', true);
+set local role anon;
+do $$ begin
+ begin
+ perform public.save_badge_layout('b0de0001-0000-0000-0000-000000000001'::uuid, 'Anon', 100, 70, '[]'::jsonb, false);
+ raise exception 'anon save allowed';
+ exception when insufficient_privilege then null;
+ end;
+ perform pg_temp.assert_badge(true, 'anon cannot execute badge functions');
+end; $$;
+reset role;
+
+select count(*) as passed_assertions from badge_results;
+rollback;