Files
Convivo/apps/sidecar/src/server.js
T
ec23da9bb9 feat(sessions): import language tag from Sessionize Language category
Sabrina's backlog: show a per-session delivery language in the sessions
overview. Sessionize has no native language field (verified live), so the
sidecar now resolves each session's categoryItems against a session
category titled "Language" (Sessionize's own demo-endpoint pattern) and
ships it as a plain string; a native session.language wins if it ever
appears.

- migration 20261021090000: sessions.language + re-created
  get_agenda / sync_sessionize_event / sync_sessionize_excel. Language
  upserts with the same coalesce(excluded, existing) rule as level/area,
  so a source without language never erases it. get_agenda is dropped +
  re-created (OUT shape change) and re-granted to anon/authenticated.
- sidecar: transform extracted to sessionize-transform.js (unit-tested);
  Excel import gains Language / Sprache / "Sprache / Language" headers.
- attendee app: third agenda filter dropdown ("All languages", only
  rendered when values exist) + language pill in SessionDetail.
- admin app: Sessions search + subtitle include language.
- seed: English for all talks, German for the two German-titled sessions.
- tests: session_language_tests.sql (8 assertions, all pass),
  sessionize-transform.test.js (7), transform-excel Language case; 43/43
  sidecar tests, date-guard/gridsmart/session-persistence suites green.
- docs: schema.md sessions columns + next-steps.md completion entry.

Organizer precondition (Sabrina): define the "Language" category AND
enable session custom fields on the event's API/Embed page, otherwise
live syncs keep language null (Excel import is the fallback).

Co-authored-by: Stephan Charles <[email protected]>
Co-authored-by: Amelia Hernandez <[email protected]>
Co-authored-by: Markus Franz <[email protected]>
Co-authored-by: Sabrina Hota <[email protected]>
Co-authored-by: Nilüfer Doğan <[email protected]>
2026-10-20 22:55:24 +02:00

890 lines
33 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Convivo sidecar — Sessionize sync (on-demand) + Pretix sync (every minute).
//
// A tiny Node HTTP service driven by the APPE Admin "Interfaces" menu.
// Endpoints:
// GET /health -> { ok: true }
// GET /status -> { ok, running, lastRun, pretixRunning, lastPretixRun,
// pretixIntervalMs, pretixConfigured }
// POST /run -> { event_id } (blocking) -> API sync result
// POST /import-excel -> { event_id, file_base64, filename? } (blocking)
// -> parses the Sessionize "Sessions and speakers
// (advanced)" .xlsx and imports it
// POST /run-pretix -> { event_id } (blocking) -> Pretix sync result
//
// Every-minute Pretix sync: when PRETIX_API_KEY is set, a loop polls each
// event's paid Pretix orders (status = 'p'), groups them by email, maps the
// ticket item name to a registration type, and calls the service-role-only
// sync_pretix_attendees RPC. The position `secret` is the QR token / login
// password.
//
// Flow for /run:
// 1. Read the event's sessionize_endpoint from Supabase (service role).
// 2. Fetch it as-is (the public /view/ endpoint needs no key).
// 3. If SESSIONIZE_API_KEY is set, send it as X-Sessionize-API-Key
// (harmless for /view/, required if the endpoint is an /api/ URL).
// 4. Transform the response into the sync_sessionize_event payload.
// 5. Call the service-role-only sync_sessionize_event RPC (blocking).
// 6. Return the RPC summary (and record it as lastRun).
//
// Note: the public /view/ payload does NOT include speaker emails, so a
// keyless sync imports sessions + agenda but skips speakers (reported in
// skipped_speakers). Set SESSIONIZE_API_KEY + an /api/ endpoint to get emails.
//
// Env:
// SUPABASE_URL (default http://supabase_kong_Convivo:8000)
// SUPABASE_SERVICE_ROLE_KEY (default = standard local service-role JWT)
// SESSIONIZE_API_KEY (optional — only needed for /api/ endpoints)
// PRETIX_API_KEY (optional — enables the every-minute Pretix sync)
// PRETIX_BASE (default https://pretix.eu/api/v1)
// PRETIX_SYNC_INTERVAL_MS (default 60000 = every minute)
// PORT (default 3002)
const http = require('http');
const XLSX = require('xlsx');
const { transformExcel } = require('./transform-excel');
const { transform } = require('./sessionize-transform');
const { readSessionizeSource } = require('./sessionize-source');
const { createSessionizePoller } = require('./sessionize-poller');
const { createFeedbackApi } = require('./feedback-api');
const PDFDocument = require('pdfkit');
const SUPABASE_URL = (process.env.SUPABASE_URL || 'http://supabase_kong_Convivo:8000').replace(/\/$/, '');
const SERVICE_ROLE_KEY =
process.env.SUPABASE_SERVICE_ROLE_KEY ||
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6InNlcnZpY2Vfcm9sZSIsImV4cCI6MTk4MzgxMjk5Nn0.EGIM96RAZx35lJzdJsyH-qQwv8Hdp7fsn3W0YpN81IU';
const SESSIONIZE_API_KEY = process.env.SESSIONIZE_API_KEY || '';
const PRETIX_API_KEY = process.env.PRETIX_API_KEY || '';
const PRETIX_BASE = (process.env.PRETIX_BASE || 'https://pretix.eu/api/v1').replace(/\/$/, '');
const PRETIX_SYNC_INTERVAL_MS = parseInt(process.env.PRETIX_SYNC_INTERVAL_MS || '60000', 10);
const configuredSessionizeInterval = Number(process.env.SESSIONIZE_SYNC_INTERVAL_MS || 900000);
const SESSIONIZE_SYNC_INTERVAL_MS = configuredSessionizeInterval === 0 ? 0
: Number.isFinite(configuredSessionizeInterval) ? Math.max(60000, configuredSessionizeInterval) : 900000;
const PORT = parseInt(process.env.PORT || '3002', 10);
// In-memory last-run state (the sidecar is otherwise stateless).
let running = false;
let lastRun = null;
let pretixRunning = false;
let lastPretixRun = null;
function log(...args) {
console.log(new Date().toISOString(), ...args);
}
function json(res, status, body) {
res.writeHead(status, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(body));
}
function readBody(req) {
return new Promise((resolve, reject) => {
let data = '';
req.on('data', (c) => {
data += c;
if (data.length > 10e6) req.destroy(); // 10 MB cap (base64 xlsx uploads)
});
req.on('end', () => {
try {
resolve(data ? JSON.parse(data) : {});
} catch {
reject(new Error('invalid JSON body'));
}
});
req.on('error', reject);
});
}
// Supabase (PostgREST) helper using the service-role key.
async function supabaseFetch(path, { method = 'GET', body, prefer } = {}) {
const res = await fetch(SUPABASE_URL + path, {
method,
headers: {
apikey: SERVICE_ROLE_KEY,
Authorization: `Bearer ${SERVICE_ROLE_KEY}`,
'Content-Type': 'application/json',
...(prefer ? { Prefer: prefer } : {}),
},
body: body ? JSON.stringify(body) : undefined,
});
const text = await res.text();
let parsed;
try {
parsed = text ? JSON.parse(text) : null;
} catch {
parsed = text;
}
if (!res.ok) {
const msg = (parsed && (parsed.message || parsed.error || parsed.hint)) || text || res.statusText;
throw new Error(`Supabase ${method} ${path} -> ${res.status}: ${msg}`);
}
return parsed;
}
// Pretix API helper (token auth). Mirrors supabaseFetch's error handling.
// `path` may be a relative path (built from PRETIX_BASE) or a full URL (e.g.
// a pagination `next` link, fetched as-is but still with the auth header).
// `apiKey` is the per-event token (falls back to the global PRETIX_API_KEY).
async function pretixFetch(path, { query, apiKey } = {}) {
const base = /^https?:\/\//.test(path) ? path : PRETIX_BASE + path;
const qs = query ? '?' + new URLSearchParams(query).toString() : '';
const token = apiKey || PRETIX_API_KEY;
const res = await fetch(base + qs, {
headers: { Authorization: 'Token ' + token, Accept: 'application/json' },
});
const text = await res.text();
let parsed;
try {
parsed = text ? JSON.parse(text) : null;
} catch {
parsed = text;
}
if (!res.ok) {
let msg = (parsed && (parsed.detail || parsed.message)) || text || res.statusText;
if (res.status === 429) {
const retryAfter = res.headers.get('Retry-After');
msg = `rate limited (429)${retryAfter ? ' — Retry-After: ' + retryAfter : ''}: ${String(msg).slice(0, 200)}`;
}
throw new Error(`Pretix GET ${path} -> ${res.status}: ${msg}`);
}
return parsed;
}
// Fetch all paid orders for an event (follow `next` until null).
async function fetchPretixOrders(organizer, eventSlug, apiKey) {
const orders = [];
let url = `/organizers/${encodeURIComponent(organizer)}/events/${encodeURIComponent(eventSlug)}/orders/?status=p`;
let pages = 0;
while (url && pages < 200) {
const page = await pretixFetch(url, { apiKey });
for (const o of page.results || []) orders.push(o);
url = page.next || null;
pages += 1;
}
return orders;
}
// Fetch the event's items (follow `next` until null) -> Map<itemId, name>.
async function fetchPretixItems(organizer, eventSlug, apiKey) {
const names = new Map();
let url = `/organizers/${encodeURIComponent(organizer)}/events/${encodeURIComponent(eventSlug)}/items/`;
let pages = 0;
while (url && pages < 200) {
const page = await pretixFetch(url, { apiKey });
for (const item of page.results || []) {
names.set(item.id, (item.name && (item.name.en || item.name.de)) || '');
}
url = page.next || null;
pages += 1;
}
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.
async function fetchPretixOptions(apiKey) {
const organizers = await pretixFetch('/organizers/', { apiKey });
const out = [];
for (const org of organizers.results || []) {
const events = await pretixFetch(
`/organizers/${encodeURIComponent(org.slug)}/events/?is_active=true`,
{ apiKey },
);
out.push({
slug: org.slug,
name: pickPretixName(org.name) || org.slug,
events: (events.results || []).map((e) => ({
slug: e.slug,
name: pickPretixName(e.name) || e.slug,
})),
});
}
return out;
}
// Map a Pretix ticket item name to a registration type (mirrors the SQL
// _map_ticket_type: case-insensitive substring match, default 'attendee').
function mapTicketType(name) {
const n = String(name || '').toLowerCase();
if (n.includes('speaker')) return 'speaker';
if (n.includes('staff')) return 'staff';
if (n.includes('sponsor')) return 'sponsor';
return 'attendee';
}
// Transform paid Pretix orders into the sync_pretix_attendees payload.
// Positions are grouped by email (one entry per unique email). For a given
// email we keep the FIRST position's qrToken + externalId, but prefer the
// highest-privilege ticket type among that person's positions.
const TICKET_PRIORITY = { attendee: 0, speaker: 1, sponsor: 2, staff: 3 };
function transformPretix(orders, itemNames) {
const byEmail = new Map();
let skipped = 0;
for (const order of orders) {
for (const position of order.positions || []) {
if (position.canceled) continue;
const email = (position.attendee_email || order.email || '').trim().toLowerCase();
const name = (position.attendee_name || (order.invoice_address && order.invoice_address.name) || '').trim();
if (!email || !name) {
skipped += 1;
continue;
}
const ticketType = mapTicketType(itemNames.get(position.item) || '');
const qrToken = position.secret || '';
const externalId = String(position.id);
const existing = byEmail.get(email);
if (!existing) {
byEmail.set(email, { email, full_name: name, ticket_type: ticketType, qr_token: qrToken, external_id: externalId });
} else if ((TICKET_PRIORITY[ticketType] || 0) > (TICKET_PRIORITY[existing.ticket_type] || 0)) {
existing.ticket_type = ticketType;
}
}
}
return { attendees: [...byEmail.values()], skipped };
}
// Transform the Sessionize API response into the sync_sessionize_event
// payload — lives in sessionize-transform.js (unit-tested); imported below.
async function runSync(eventId) {
if (running) throw new Error('a sync is already running');
running = true;
const startedAt = new Date().toISOString();
log('run: start', { eventId });
try {
// 1. Read the event's Sessionize endpoint.
const events = await supabaseFetch(
`/rest/v1/events?id=eq.${encodeURIComponent(eventId)}&select=id,name,sessionize_endpoint`,
);
const event = Array.isArray(events) ? events[0] : null;
if (!event) throw new Error('event not found');
if (!event.sessionize_endpoint) {
throw new Error(`event "${event.name}" has no sessionize_endpoint set`);
}
const source = await readSessionizeSource(event.sessionize_endpoint, { apiKey: SESSIONIZE_API_KEY });
const { payload, skippedSpeakers } = source.payload
? { payload: source.payload, skippedSpeakers: [] }
: transform(source.data);
if (!payload.sessions.length) throw new Error('Sessionize contains no scheduled sessions; existing agenda retained');
log('run: transformed', {
speakers: payload.speakers.length,
sessions: payload.sessions.length,
skippedSpeakers: skippedSpeakers.length,
});
// 4. Call the service-role RPC (blocking).
const summary = await supabaseFetch('/rest/v1/rpc/sync_sessionize_event', {
method: 'POST',
body: { p_event_id: event.id, p_payload: payload },
});
if (summary.errors?.length) throw new Error(`Sessionize import reported ${summary.errors.length} error(s)`);
const finishedAt = new Date().toISOString();
const result = {
event_id: event.id,
event_name: event.name,
started_at: startedAt,
finished_at: finishedAt,
status: 'success',
source_format: source.format,
summary,
skipped_speakers: skippedSpeakers,
};
lastRun = result;
log('run: done', { summary });
return result;
} catch (e) {
const finishedAt = new Date().toISOString();
lastRun = {
event_id: eventId,
started_at: startedAt,
finished_at: finishedAt,
status: 'error',
error: e.message,
};
log('run: error', { error: e.message });
throw e;
} finally {
running = false;
}
}
// Excel import: parse the uploaded .xlsx and call sync_sessionize_excel.
async function runExcelImport(eventId, fileBase64) {
if (running) throw new Error('a sync is already running');
running = true;
const startedAt = new Date().toISOString();
log('import-excel: start', { eventId });
try {
const events = await supabaseFetch(
`/rest/v1/events?id=eq.${encodeURIComponent(eventId)}&select=id,name`,
);
const event = Array.isArray(events) ? events[0] : null;
if (!event) throw new Error('event not found');
const buffer = Buffer.from(fileBase64, 'base64');
if (buffer.length === 0) throw new Error('empty file');
const { payload } = transformExcel(buffer);
log('import-excel: transformed', {
speakers: payload.speakers.length,
sessions: payload.sessions.length,
});
if (payload.sessions.length === 0) {
throw new Error('no sessions found in the file (expected an "Accepted sessions" sheet)');
}
const summary = await supabaseFetch('/rest/v1/rpc/sync_sessionize_excel', {
method: 'POST',
body: { p_event_id: event.id, p_payload: payload },
});
const finishedAt = new Date().toISOString();
const result = {
event_id: event.id,
event_name: event.name,
started_at: startedAt,
finished_at: finishedAt,
status: 'success',
summary,
};
lastRun = result;
log('import-excel: done', { summary });
return result;
} catch (e) {
const finishedAt = new Date().toISOString();
lastRun = {
event_id: eventId,
started_at: startedAt,
finished_at: finishedAt,
status: 'error',
error: e.message,
};
log('import-excel: error', { error: e.message });
throw e;
} finally {
running = false;
}
}
// Pretix sync: pull an event's paid orders, transform, and call the
// service-role-only sync_pretix_attendees RPC (blocking).
async function runPretixSync(eventId) {
if (pretixRunning) throw new Error('a pretix sync is already running');
pretixRunning = true;
const startedAt = new Date().toISOString();
log('pretix: start', { eventId });
try {
const events = await supabaseFetch(
`/rest/v1/events?id=eq.${encodeURIComponent(eventId)}&select=id,name,pretix_organizer,pretix_event_slug,pretix_api_key`,
);
const event = Array.isArray(events) ? events[0] : null;
if (!event) throw new Error('event not found');
if (!event.pretix_organizer || !event.pretix_event_slug) {
const finishedAt = new Date().toISOString();
lastPretixRun = {
event_id: event.id,
started_at: startedAt,
finished_at: finishedAt,
status: 'skipped',
reason: 'no pretix config',
};
log('pretix: skipped (no pretix config)', { eventId });
return lastPretixRun;
}
const apiKey = event.pretix_api_key || PRETIX_API_KEY;
if (!apiKey) {
const finishedAt = new Date().toISOString();
lastPretixRun = {
event_id: event.id,
started_at: startedAt,
finished_at: finishedAt,
status: 'skipped',
reason: 'no pretix api key',
};
log('pretix: skipped (no pretix api key)', { eventId });
return lastPretixRun;
}
const orders = await fetchPretixOrders(event.pretix_organizer, event.pretix_event_slug, apiKey);
const itemNames = await fetchPretixItems(event.pretix_organizer, event.pretix_event_slug, apiKey);
const { attendees, skipped } = transformPretix(orders, itemNames);
log('pretix: transformed', { orders: orders.length, attendees: attendees.length, skipped });
const summary = await supabaseFetch('/rest/v1/rpc/sync_pretix_attendees', {
method: 'POST',
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,
event_name: event.name,
started_at: startedAt,
finished_at: finishedAt,
status: 'success',
orders: orders.length,
attendees: attendees.length,
company,
skipped,
summary,
};
lastPretixRun = result;
log('pretix: done', { summary });
return result;
} catch (e) {
const finishedAt = new Date().toISOString();
lastPretixRun = {
event_id: eventId,
started_at: startedAt,
finished_at: finishedAt,
status: 'error',
error: e.message,
};
log('pretix: error', { error: e.message });
throw e;
} finally {
pretixRunning = false;
}
}
// Every-minute loop: sync every event that has a Pretix config. One event's
// failure must not stop the others.
async function runPretixLoop() {
if (pretixRunning) return;
const events = await supabaseFetch(
'/rest/v1/events?pretix_organizer=not.is.null&select=id,pretix_organizer,pretix_event_slug,pretix_api_key',
);
for (const e of Array.isArray(events) ? events : []) {
try {
await runPretixSync(e.id);
} catch (err) {
log('pretix loop: event failed', { eventId: e.id, error: err.message });
}
}
}
// =============================================================================
// POST /export — event reports (CSV / XLSX / PDF)
//
// Fetches an event's full dataset (service role) and renders it as:
// * csv — one combined CSV (a `table` column distinguishes the rows)
// * xlsx — one workbook, one sheet per table
// * pdf — a structured post-event report (summary + per-session + top points)
// Returns { filename, mime, content_base64 }.
// =============================================================================
// The tables an export can include (CSV/XLSX). The PDF always uses all of them.
const EXPORT_TABLES = [
'registrations',
'checkins',
'connections',
'session_feedback',
'event_feedback',
'leaderboard',
'points_log',
];
// Escape a single CSV cell (RFC 4180).
function csvCell(v) {
const s = v == null ? '' : String(v);
return /[",\n\r]/.test(s) ? '"' + s.replace(/"/g, '""') + '"' : s;
}
// Render an array of flat row objects as a single CSV string.
function rowsToCsv(rows) {
if (rows.length === 0) return '';
const headers = Object.keys(rows[0]);
const lines = [headers.map(csvCell).join(',')];
for (const r of rows) lines.push(headers.map((h) => csvCell(r[h])).join(','));
return lines.join('\n');
}
// Fetch the event's full dataset (service role), joined for readability.
async function fetchEventDataset(eventId) {
const events = await supabaseFetch(
`/rest/v1/events?id=eq.${encodeURIComponent(eventId)}&select=*`,
);
const event = Array.isArray(events) ? events[0] : null;
if (!event) throw new Error('event not found');
const [contacts, regs, checkins, connections, feedback, eventFeedback, leaderboard, pointsLog, sessions] =
await Promise.all([
supabaseFetch('/rest/v1/contacts?select=email,full_name'),
supabaseFetch(`/rest/v1/registrations?event_id=eq.${encodeURIComponent(eventId)}&select=*`),
supabaseFetch(`/rest/v1/checkins?event_id=eq.${encodeURIComponent(eventId)}&select=*`),
supabaseFetch(`/rest/v1/connections?event_id=eq.${encodeURIComponent(eventId)}&select=*`),
supabaseFetch(`/rest/v1/feedback?event_id=eq.${encodeURIComponent(eventId)}&select=*`),
supabaseFetch(`/rest/v1/event_feedback?event_id=eq.${encodeURIComponent(eventId)}&select=*`),
supabaseFetch(`/rest/v1/leaderboard?event_id=eq.${encodeURIComponent(eventId)}&select=*`),
supabaseFetch(`/rest/v1/points_log?event_id=eq.${encodeURIComponent(eventId)}&select=*`),
supabaseFetch(`/rest/v1/sessions?event_id=eq.${encodeURIComponent(eventId)}&select=*`),
]);
const nameOf = new Map((Array.isArray(contacts) ? contacts : []).map((c) => [c.email, c.full_name]));
const sessionTitle = new Map((Array.isArray(sessions) ? sessions : []).map((s) => [s.id, s.title]));
const titleOf = (id) => sessionTitle.get(id) ?? id ?? '';
const name = (email) => nameOf.get(email) ?? email ?? '';
return {
event,
registrations: (Array.isArray(regs) ? regs : []).map((r) => ({
email: r.contact_email,
name: name(r.contact_email),
type: r.type,
checked_in: r.checked_in,
points: r.points,
qr_token: r.qr_token,
})),
checkins: (Array.isArray(checkins) ? checkins : []).map((c) => ({
email: c.contact_email,
name: name(c.contact_email),
session: titleOf(c.session_id),
checked_in_by: name(c.staff_email),
when: c.created_at,
})),
connections: (Array.isArray(connections) ? connections : []).map((c) => ({
from: name(c.from_email),
to: name(c.to_email),
status: c.status,
when: c.created_at,
})),
sessionFeedback: (Array.isArray(feedback) ? feedback : []).map((f) => ({
email: f.contact_email,
name: name(f.contact_email),
session: titleOf(f.session_id),
rating: f.rating,
comment: f.comment,
when: f.created_at,
})),
eventFeedback: (Array.isArray(eventFeedback) ? eventFeedback : []).map((f) => ({
email: f.contact_email,
name: name(f.contact_email),
rating: f.rating,
comment: f.comment,
when: f.created_at,
})),
leaderboard: (Array.isArray(leaderboard) ? leaderboard : [])
.sort((a, b) => (b.points ?? 0) - (a.points ?? 0))
.map((l) => ({ name: l.full_name ?? name(l.contact_email), points: l.points })),
pointsLog: (Array.isArray(pointsLog) ? pointsLog : []).map((l) => ({
email: l.contact_email,
name: name(l.contact_email),
delta: l.delta,
category: l.category,
when: l.created_at,
})),
};
}
// Build the combined CSV (a `table` column distinguishes the rows).
function buildCsv(ds, tables) {
const source = {
registrations: ds.registrations,
checkins: ds.checkins,
connections: ds.connections,
session_feedback: ds.sessionFeedback,
event_feedback: ds.eventFeedback,
leaderboard: ds.leaderboard,
points_log: ds.pointsLog,
};
const chunks = [];
for (const t of tables) {
const rows = source[t] || [];
if (rows.length === 0) continue;
const withTable = rows.map((r) => ({ table: t, ...r }));
chunks.push(rowsToCsv(withTable));
}
return chunks.join('\n');
}
// Build the multi-sheet XLSX workbook (one sheet per table).
function buildXlsx(ds, tables) {
const source = {
registrations: ds.registrations,
checkins: ds.checkins,
connections: ds.connections,
session_feedback: ds.sessionFeedback,
event_feedback: ds.eventFeedback,
leaderboard: ds.leaderboard,
points_log: ds.pointsLog,
};
const wb = XLSX.utils.book_new();
for (const t of tables) {
const rows = source[t] || [];
const ws = XLSX.utils.json_to_sheet(rows.length > 0 ? rows : [{ note: 'no data' }]);
XLSX.utils.book_append_sheet(wb, ws, t.slice(0, 31));
}
const out = XLSX.write(wb, { bookType: 'xlsx', type: 'buffer' });
return out;
}
// Build the PDF post-event report.
function buildPdf(ds) {
return new Promise((resolve, reject) => {
const doc = new PDFDocument({ size: 'A4', margin: 48 });
const buf = [];
doc.on('data', (c) => buf.push(c));
doc.on('end', () => resolve(Buffer.concat(buf)));
doc.on('error', reject);
const ev = ds.event;
const h2 = (t) => {
doc.font('Helvetica-Bold').fontSize(13);
doc.text(t, { continued: false });
doc.moveDown(0.4);
};
const line = (label, value) => {
doc.font('Helvetica').fontSize(10);
doc.text(`${label}: `, { continued: true });
doc.font('Helvetica-Bold').text(String(value), { continued: false });
doc.moveDown(0.15);
};
// Header.
doc.font('Helvetica-Bold').fontSize(18).text(ev.name || 'Event report');
doc.font('Helvetica').fontSize(10).fillColor('#555');
const dates = `${ev.start_date} – ${ev.end_date}${ev.location ? ` · ${ev.location}` : ''}`;
doc.text(dates);
doc.moveDown(0.3);
doc.text(`Generated ${new Date().toISOString()}`);
doc.moveDown(0.8);
doc.fillColor('#000');
// Summary.
h2('Summary');
const byType = {};
for (const r of ds.registrations) byType[r.type] = (byType[r.type] || 0) + 1;
line('Registrations', ds.registrations.length);
line('By type', Object.keys(byType).length ? Object.entries(byType).map(([t, n]) => `${t} ${n}`).join(', ') : '—');
line('Check-ins', ds.checkins.length);
const accepted = ds.connections.filter((c) => c.status === 'accepted').length;
line('Connections', `${ds.connections.length} (${accepted} accepted)`);
const sf = ds.sessionFeedback;
line('Session feedback', sf.length ? `${sf.length} (avg ${(sf.reduce((s, f) => s + f.rating, 0) / sf.length).toFixed(2)}★)` : '—');
const ef = ds.eventFeedback;
line('Event feedback', ef.length ? `${ef.length} (avg ${(ef.reduce((s, f) => s + f.rating, 0) / ef.length).toFixed(2)}★)` : '—');
const catTotals = {};
for (const l of ds.pointsLog) catTotals[l.category] = (catTotals[l.category] || 0) + l.delta;
line('Points by category', Object.keys(catTotals).length ? Object.entries(catTotals).map(([c, n]) => `${c} +${n}`).join(', ') : '—');
doc.moveDown(0.6);
// Per-session feedback.
h2('Session feedback');
if (sf.length === 0) {
doc.font('Helvetica').fontSize(10).text('No session feedback.');
} else {
const bySession = {};
for (const f of sf) {
const e = (bySession[f.session] ||= { count: 0, sum: 0 });
e.count += 1;
e.sum += f.rating;
}
const rows = Object.entries(bySession)
.map(([title, e]) => ({ title, avg: e.sum / e.count, count: e.count }))
.sort((a, b) => b.avg - a.avg);
doc.font('Helvetica-Bold').fontSize(9).text('Session', { continued: true }).text(' ', { continued: true });
doc.text('Avg', { continued: true }).text(' ', { continued: true }).text('Responses');
doc.moveDown(0.2);
doc.font('Helvetica').fontSize(9);
for (const r of rows) {
doc.text(`${r.title} · ${r.avg.toFixed(2)}★ · ${r.count}`, { lineBreak: true });
}
}
doc.moveDown(0.6);
// Top points.
h2('Top points');
if (ds.leaderboard.length === 0) {
doc.font('Helvetica').fontSize(10).text('No points yet.');
} else {
doc.font('Helvetica').fontSize(9);
ds.leaderboard.slice(0, 10).forEach((l, i) => {
doc.text(`${i + 1}. ${l.name} · ${l.points} pts`, { lineBreak: true });
});
}
doc.moveDown(0.6);
// Event-level feedback comments.
h2('Event-level feedback');
const comments = ef.filter((f) => f.comment).slice(0, 50);
if (comments.length === 0) {
doc.font('Helvetica').fontSize(10).text('No event-level comments.');
} else {
doc.font('Helvetica').fontSize(9);
for (const c of comments) {
const body = (c.comment || '').replace(/\s+/g, ' ').trim().slice(0, 200);
doc.text(`• [${c.rating}★] ${c.name}: ${body}`, { lineBreak: true });
doc.moveDown(0.15);
}
}
doc.end();
});
}
// The POST /export handler.
async function handleExport(body) {
const { event_id: eventId, format, tables } = body || {};
if (!eventId) throw new Error('event_id is required');
if (!['csv', 'xlsx', 'pdf'].includes(format)) throw new Error('format must be csv, xlsx, or pdf');
const ds = await fetchEventDataset(eventId);
const slug = (ds.event.name || eventId).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') || 'event';
if (format === 'pdf') {
const buf = await buildPdf(ds);
return { filename: `${slug}-report.pdf`, mime: 'application/pdf', content_base64: buf.toString('base64') };
}
const selected = (Array.isArray(tables) && tables.length > 0 ? tables : EXPORT_TABLES).filter((t) =>
EXPORT_TABLES.includes(t),
);
if (selected.length === 0) throw new Error('no valid tables selected');
if (format === 'csv') {
const csv = buildCsv(ds, selected);
return {
filename: `${slug}-report.csv`,
mime: 'text/csv;charset=utf-8',
content_base64: Buffer.from(csv, 'utf8').toString('base64'),
};
}
// xlsx
const buf = buildXlsx(ds, selected);
return {
filename: `${slug}-report.xlsx`,
mime: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
content_base64: Buffer.from(buf).toString('base64'),
};
}
const pollSessionize = createSessionizePoller({
listEvents: () => supabaseFetch('/rest/v1/events?is_active=eq.true&sessionize_endpoint=not.is.null&select=id'),
syncEvent: runSync,
isBusy: () => running,
onError: (error, eventId) => log('sessionize poll error', { eventId, error: error.message }),
});
const feedbackApi = createFeedbackApi({ supabaseFetch, supabaseUrl: SUPABASE_URL, serviceRoleKey: SERVICE_ROLE_KEY });
const server = http.createServer(async (req, res) => {
const url = new URL(req.url, `http://${req.headers.host || 'localhost'}`);
const path = url.pathname;
try {
if (path === '/llm-settings' || path === '/feedback-summary' || path === '/llm-test') {
res.setHeader('Cache-Control', 'no-store');
const body = req.method === 'GET' ? {} : await readBody(req);
const result = await feedbackApi.handle(req, path, body);
return json(res, 200, result);
}
if (req.method === 'GET' && path === '/health') {
return json(res, 200, { ok: true });
}
if (req.method === 'GET' && path === '/status') {
return json(res, 200, {
ok: true,
running,
lastRun,
sessionizeIntervalMs: SESSIONIZE_SYNC_INTERVAL_MS,
pretixRunning,
lastPretixRun,
pretixIntervalMs: PRETIX_SYNC_INTERVAL_MS,
pretixConfigured: Boolean(PRETIX_API_KEY),
});
}
if (req.method === 'POST' && path === '/run') {
const body = await readBody(req);
const eventId = body && body.event_id;
if (!eventId) return json(res, 400, { error: 'event_id is required' });
const result = await runSync(eventId);
return json(res, 200, result);
}
if (req.method === 'POST' && path === '/import-excel') {
const body = await readBody(req);
const eventId = body && body.event_id;
const fileBase64 = body && body.file_base64;
if (!eventId) return json(res, 400, { error: 'event_id is required' });
if (!fileBase64) return json(res, 400, { error: 'file_base64 is required' });
const result = await runExcelImport(eventId, fileBase64);
return json(res, 200, result);
}
if (req.method === 'POST' && path === '/run-pretix') {
const body = await readBody(req);
const eventId = body && body.event_id;
if (!eventId) return json(res, 400, { error: 'event_id is required' });
const result = await runPretixSync(eventId);
return json(res, 200, result);
}
if (req.method === 'POST' && path === '/pretix-options') {
const body = await readBody(req);
const apiKey = body && body.api_key;
if (!apiKey) return json(res, 400, { error: 'api_key is required' });
const organizers = await fetchPretixOptions(apiKey);
return json(res, 200, { organizers });
}
if (req.method === 'POST' && path === '/export') {
const body = await readBody(req);
const result = await handleExport(body);
return json(res, 200, result);
}
return json(res, 404, { error: 'not found' });
} catch (e) {
const feedbackRoute = path === '/llm-settings' || path === '/feedback-summary' || path === '/llm-test';
return json(res, e.status || 500, { error: feedbackRoute && !e.status ? 'Feedback service unavailable' : e.message });
}
});
server.listen(PORT, () => {
if (SESSIONIZE_SYNC_INTERVAL_MS > 0) {
log('sessionize auto-sync scheduled', { intervalMs: SESSIONIZE_SYNC_INTERVAL_MS });
setInterval(pollSessionize, SESSIONIZE_SYNC_INTERVAL_MS);
void pollSessionize();
}
log('sidecar listening', {
port: PORT,
supabase: SUPABASE_URL,
hasSessionizeKey: Boolean(SESSIONIZE_API_KEY),
});
// The every-minute loop always runs; it only syncs events that have a
// Pretix config (organizer + slug) and an API key (per-event column, or the
// global PRETIX_API_KEY fallback). Events without a key are skipped.
log('pretix auto-sync scheduled', {
intervalMs: PRETIX_SYNC_INTERVAL_MS,
globalKeySet: Boolean(PRETIX_API_KEY),
});
setInterval(() => {
runPretixLoop().catch((e) => log('pretix loop error', { error: e.message }));
}, PRETIX_SYNC_INTERVAL_MS);
});