// 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 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 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 } = {}) { const res = await fetch(SUPABASE_URL + path, { method, headers: { apikey: SERVICE_ROLE_KEY, Authorization: `Bearer ${SERVICE_ROLE_KEY}`, 'Content-Type': 'application/json', }, 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). async function pretixFetch(path, { query } = {}) { const base = /^https?:\/\//.test(path) ? path : PRETIX_BASE + path; const qs = query ? '?' + new URLSearchParams(query).toString() : ''; const res = await fetch(base + qs, { headers: { Authorization: 'Token ' + PRETIX_API_KEY, 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) { 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); 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. async function fetchPretixItems(organizer, eventSlug) { 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); 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; } // 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. // Speakers are matched by email (the key); speakers without an email are // skipped and reported. Sessions carry their speakers as a list of emails. function transform(data) { const speakerByEmail = new Map(); const roomName = new Map(); for (const r of data.rooms || []) roomName.set(r.id, r.name); for (const s of data.speakers || []) { if (s.email) speakerByEmail.set(s.id, s.email); } const speakers = []; const skippedSpeakers = []; for (const s of data.speakers || []) { if (s.email && s.fullName) { speakers.push({ email: s.email, full_name: s.fullName, external_id: s.id }); } else { skippedSpeakers.push(s.fullName || s.id || ''); } } const sessions = []; for (const s of data.sessions || []) { if (!s.id || !s.title || !s.startsAt || !s.endsAt) continue; const speakerEmails = (s.speakers || []).map((id) => speakerByEmail.get(id)).filter(Boolean); sessions.push({ external_id: s.id, title: s.title, description: s.description || null, room: roomName.get(s.roomId) || null, date: s.startsAt.slice(0, 10), start_time: s.startsAt.slice(11, 19), end_time: s.endsAt.slice(11, 19), // A service session is a break/lunch/closing (isServiceSession) OR a // plenum (isPlenumSession) — plenums are full-hall items with no pick. is_service_session: Boolean(s.isServiceSession || s.isPlenumSession), speakers: speakerEmails, }); } return { payload: { speakers, sessions }, skippedSpeakers }; } // Excel serial date (days since 1899-12-30) -> { date, start_time, end_time }. // Sessionize exports "Scheduled At" as an Excel serial and "Scheduled Duration" // in minutes. The epoch is 1899-12-30 (the Excel 1900 system, incl. its // spurious 1900 leap day, which is irrelevant for modern dates). function excelSerialToTime(serial, durationMin) { const ms = Math.round((serial - 25569) * 86400 * 1000); const d = new Date(ms); const pad = (n) => String(n).padStart(2, '0'); const date = `${d.getUTCFullYear()}-${pad(d.getUTCMonth() + 1)}-${pad(d.getUTCDate())}`; const start = `${pad(d.getUTCHours())}:${pad(d.getUTCMinutes())}:${pad(d.getUTCSeconds())}`; const endMs = ms + (durationMin || 0) * 60 * 1000; const e = new Date(endMs); const end = `${pad(e.getUTCHours())}:${pad(e.getUTCMinutes())}:${pad(e.getUTCSeconds())}`; return { date, start_time: start, end_time: end }; } // Transform the Sessionize "Sessions and speakers (advanced)" .xlsx into the // sync_sessionize_excel payload. Two sheets: // "Accepted sessions" -> sessions (Speaker Ids -> emails via the speakers sheet) // "Accepted speakers" -> speakers (matched by email) function transformExcel(buffer) { const wb = XLSX.read(buffer, { type: 'buffer' }); const sheetName = (n) => wb.SheetNames.find((s) => s.toLowerCase().includes(n)) || null; const toRows = (name) => { const sn = sheetName(name); if (!sn) return []; return XLSX.utils.sheet_to_json(wb.Sheets[sn], { defval: '' }); }; const speakerRows = toRows('speaker'); const sessionRows = toRows('session'); // Speaker Id -> { email, full_name, linkedin_url }. const speakerById = new Map(); const speakers = []; for (const r of speakerRows) { const id = String(r['Speaker Id'] ?? '').trim(); const email = String(r['Email'] ?? '').trim(); const first = String(r['FirstName'] ?? '').trim(); const last = String(r['LastName'] ?? '').trim(); const full = [first, last].filter(Boolean).join(' ').trim(); if (!id || !email || !full) continue; const linkedin = String(r['LinkedIn'] ?? '').trim() || null; speakerById.set(id, { email, full_name: full, linkedin_url: linkedin }); speakers.push({ email, full_name: full, external_id: id, linkedin_url: linkedin }); } const sessions = []; for (const r of sessionRows) { const id = String(r['Session Id'] ?? '').trim(); const title = String(r['Title'] ?? '').trim(); const schedAt = Number(r['Scheduled At']); const dur = Number(r['Scheduled Duration']); if (!id || !title || !schedAt) continue; const { date, start_time, end_time } = excelSerialToTime(schedAt, dur); const speakerIds = String(r['Speaker Ids'] ?? '') .split(',') .map((s) => s.trim()) .filter(Boolean); const speakerEmails = speakerIds.map((sid) => speakerById.get(sid)?.email).filter(Boolean); sessions.push({ external_id: id, title, description: String(r['Description'] ?? '').trim() || null, room: String(r['Room'] ?? '').trim() || null, date, start_time, end_time, is_service_session: /service|break|lunch|closing|plenum/i.test(String(r['Session Format'] ?? '')), speakers: speakerEmails, }); } return { payload: { speakers, sessions } }; } 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`); } // 2. Fetch the Sessionize data. The public /view/ endpoint needs no key; // if a key is configured we send it (required for /api/ endpoints). const szUrl = event.sessionize_endpoint.trim(); log('run: fetching Sessionize', { szUrl, hasKey: Boolean(SESSIONIZE_API_KEY) }); const szHeaders = {}; if (SESSIONIZE_API_KEY) szHeaders['X-Sessionize-API-Key'] = SESSIONIZE_API_KEY; const szRes = await fetch(szUrl, { headers: szHeaders }); if (!szRes.ok) { const t = await szRes.text(); throw new Error(`Sessionize ${szRes.status}: ${t.slice(0, 200)}`); } const szData = await szRes.json(); // 3. Transform. const { payload, skippedSpeakers } = transform(szData); 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 }, }); const finishedAt = new Date().toISOString(); const result = { event_id: event.id, event_name: event.name, started_at: startedAt, finished_at: finishedAt, status: 'success', 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`, ); 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 orders = await fetchPretixOrders(event.pretix_organizer, event.pretix_event_slug); const itemNames = await fetchPretixItems(event.pretix_organizer, event.pretix_event_slug); 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 }, }); 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, 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', ); 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 }); } } } const server = http.createServer(async (req, res) => { const url = new URL(req.url, `http://${req.headers.host || 'localhost'}`); const path = url.pathname; try { 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, 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); } return json(res, 404, { error: 'not found' }); } catch (e) { return json(res, 500, { error: e.message }); } }); server.listen(PORT, () => { log('sidecar listening', { port: PORT, supabase: SUPABASE_URL, hasSessionizeKey: Boolean(SESSIONIZE_API_KEY), }); if (PRETIX_API_KEY) { log('pretix auto-sync scheduled', { intervalMs: PRETIX_SYNC_INTERVAL_MS }); setInterval(() => { runPretixLoop().catch((e) => log('pretix loop error', { error: e.message })); }, PRETIX_SYNC_INTERVAL_MS); } else { log('pretix auto-sync disabled (no PRETIX_API_KEY)'); } });