feat: add sidecar service for Sessionize sync
- Introduced a new Node HTTP service (sidecar) to sync event agendas from Sessionize into Convivo. - Implemented two import paths: API sync and Excel import for session and speaker data. - Added necessary database migrations for sessionize integration, including new columns and audit tables. - Created functions for handling speaker and session imports, ensuring proper error handling and logging. - Established row-level security and grants for new functions to restrict access to service-role only.
This commit is contained in:
1 parent
8054d0ace2
commit
f7aea663d8
31 files changed
+2729
-390
No files matched your search
@@ -9,11 +9,14 @@
|
||||
set -eu
|
||||
|
||||
TARGET="${SUPABASE_PROXY_TARGET:-supabase_kong_Convivo:8000}"
|
||||
SIDECAR="${SIDECAR_TARGET:-convivo-sidecar:3002}"
|
||||
TEMPLATE=/etc/nginx/conf.d/default.conf.template
|
||||
CONF=/etc/nginx/conf.d/default.conf
|
||||
|
||||
echo "[convivo-admin] Proxying Supabase paths to: ${TARGET}"
|
||||
sed "s|__SUPABASE_PROXY_TARGET__|${TARGET}|g" "${TEMPLATE}" > "${CONF}"
|
||||
echo "[convivo-admin] Proxying /sidecar/ to: ${SIDECAR}"
|
||||
sed -e "s|__SUPABASE_PROXY_TARGET__|${TARGET}|g" \
|
||||
-e "s|__SIDECAR_TARGET__|${SIDECAR}|g" "${TEMPLATE}" > "${CONF}"
|
||||
|
||||
# Run nginx in the foreground.
|
||||
exec nginx -g "daemon off;"
|
||||
@@ -83,4 +83,18 @@ server {
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
# ---- Sessionize sync sidecar -----------------------------------------
|
||||
# The sidecar exposes /health, /status, /run. The /sidecar prefix is
|
||||
# stripped (trailing slash on proxy_pass) so /sidecar/run -> /run.
|
||||
location /sidecar/ {
|
||||
proxy_pass http://__SIDECAR_TARGET__/;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
# A sync is a blocking call (fetch + RPC) and can take a while.
|
||||
proxy_read_timeout 120s;
|
||||
proxy_send_timeout 120s;
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import { Sponsors } from './views/Sponsors';
|
||||
import { Schedule } from './views/Schedule';
|
||||
import { Activity } from './views/Activity';
|
||||
import { Events } from './views/Events';
|
||||
import { Interfaces } from './views/Interfaces';
|
||||
import { Spinner } from './components/ui';
|
||||
|
||||
export type View =
|
||||
@@ -18,7 +19,8 @@ export type View =
|
||||
| 'sponsors'
|
||||
| 'schedule'
|
||||
| 'activity'
|
||||
| 'events';
|
||||
| 'events'
|
||||
| 'interfaces';
|
||||
|
||||
const NAV: { id: View; label: string; ico: string }[] = [
|
||||
{ id: 'dashboard', label: 'Dashboard', ico: '📊' },
|
||||
@@ -28,6 +30,7 @@ const NAV: { id: View; label: string; ico: string }[] = [
|
||||
{ id: 'schedule', label: 'Schedule', ico: '🗓️' },
|
||||
{ id: 'activity', label: 'Activity', ico: '⚡' },
|
||||
{ id: 'events', label: 'Events', ico: '📅' },
|
||||
{ id: 'interfaces', label: 'Interfaces', ico: '🔌' },
|
||||
];
|
||||
|
||||
function Shell() {
|
||||
@@ -95,6 +98,7 @@ function Shell() {
|
||||
{view === 'schedule' && <Schedule />}
|
||||
{view === 'activity' && <Activity />}
|
||||
{view === 'events' && <Events />}
|
||||
{view === 'interfaces' && <Interfaces />}
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -4,6 +4,7 @@ import type {
|
||||
Connection,
|
||||
Contact,
|
||||
Event,
|
||||
ExcelSyncResult,
|
||||
Feedback,
|
||||
LeaderboardRow,
|
||||
PointsLogRow,
|
||||
@@ -11,8 +12,11 @@ import type {
|
||||
ResetQrResult,
|
||||
Session,
|
||||
SessionSpeaker,
|
||||
SidecarStatus,
|
||||
Slot,
|
||||
Sponsor,
|
||||
SyncResult,
|
||||
SyncRun,
|
||||
} from './types';
|
||||
|
||||
export class ApiError extends Error {}
|
||||
@@ -142,7 +146,13 @@ export async function deleteSponsor(id: string): Promise<void> {
|
||||
|
||||
export async function upsertEvent(
|
||||
id: string | null,
|
||||
input: { name: string; start_date: string; end_date: string; location?: string | null },
|
||||
input: {
|
||||
name: string;
|
||||
start_date: string;
|
||||
end_date: string;
|
||||
location?: string | null;
|
||||
sessionize_endpoint?: string | null;
|
||||
},
|
||||
): Promise<void> {
|
||||
if (id) {
|
||||
const { error } = await supabase.from('events').update(input).eq('id', id);
|
||||
@@ -153,6 +163,58 @@ export async function upsertEvent(
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Sessionize sync (sidecar) ---------------------------------------------
|
||||
// The sidecar is a separate Docker service (not Supabase), so these use raw
|
||||
// fetch against the same-origin /sidecar proxy (see nginx.conf.template).
|
||||
|
||||
async function sidecarFetch<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
let res: Response;
|
||||
try {
|
||||
res = await fetch(`/sidecar${path}`, {
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
...init,
|
||||
});
|
||||
} catch {
|
||||
throw new ApiError('Could not reach the sync sidecar (is it running?)');
|
||||
}
|
||||
const body = (await res.json().catch(() => ({}))) as T & { error?: string };
|
||||
if (!res.ok) throw new ApiError(body.error || `sidecar error (${res.status})`);
|
||||
return body;
|
||||
}
|
||||
|
||||
export const getSidecarStatus = () => sidecarFetch<SidecarStatus>('/status');
|
||||
|
||||
/** Trigger a (blocking) Sessionize sync for an event. Resolves with the result. */
|
||||
export const runSessionizeSync = (eventId: string) =>
|
||||
sidecarFetch<SyncResult>('/run', { method: 'POST', body: JSON.stringify({ event_id: eventId }) });
|
||||
|
||||
/**
|
||||
* Upload the Sessionize "Sessions and speakers (advanced)" .xlsx for an event.
|
||||
* The sidecar parses it and imports speakers/sessions/agenda + speaker
|
||||
* registrations. Resolves with the result (blocking).
|
||||
*/
|
||||
export async function importSessionizeExcel(eventId: string, file: File): Promise<ExcelSyncResult> {
|
||||
const base64 = await new Promise<string>((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => {
|
||||
const url = reader.result as string;
|
||||
resolve(url.slice(url.indexOf(',') + 1));
|
||||
};
|
||||
reader.onerror = () => reject(new Error('Could not read the file'));
|
||||
reader.readAsDataURL(file);
|
||||
});
|
||||
return sidecarFetch<ExcelSyncResult>('/import-excel', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ event_id: eventId, file_base64: base64, filename: file.name }),
|
||||
});
|
||||
}
|
||||
|
||||
/** Recent sync_runs rows for an event (newest first). */
|
||||
export const getSyncRuns = (eventId: string) =>
|
||||
all<SyncRun>('sync_runs', { col: 'started_at', asc: false }).then((rows) =>
|
||||
rows.filter((r) => r.event_id === eventId),
|
||||
);
|
||||
|
||||
/** Set an event active (deactivates all others via trigger). */
|
||||
export async function activateEvent(id: string): Promise<void> {
|
||||
const { error } = await supabase.from('events').update({ is_active: true }).eq('id', id);
|
||||
|
||||
@@ -10,7 +10,7 @@ export type SponsorType =
|
||||
| 'catering'
|
||||
| 'diversity';
|
||||
|
||||
export type SlotType = 'session' | 'lunch_break' | 'coffee_break' | 'keynote' | 'close_up';
|
||||
export type SlotType = 'session' | 'service_session';
|
||||
|
||||
export interface Contact {
|
||||
email: string;
|
||||
@@ -31,6 +31,10 @@ export interface Event {
|
||||
end_date: string;
|
||||
location: string | null;
|
||||
is_active: boolean;
|
||||
/** Sessionize API URL for this event (e.g. .../api/v2/<id>/view/All). */
|
||||
sessionize_endpoint: string | null;
|
||||
/** When the Sessionize sync last ran for this event. */
|
||||
last_synced_at: string | null;
|
||||
avg_feedback: number | null;
|
||||
num_sessions: number;
|
||||
num_speakers: number;
|
||||
@@ -39,6 +43,76 @@ export interface Event {
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
// ---- Sessionize sync (sidecar) ---------------------------------------------
|
||||
|
||||
/** A row in the sync_runs audit table (event-scoped). */
|
||||
export interface SyncRun {
|
||||
id: string;
|
||||
event_id: string;
|
||||
source: string;
|
||||
started_at: string;
|
||||
finished_at: string | null;
|
||||
created: number;
|
||||
updated: number;
|
||||
skipped: number;
|
||||
error: string | null;
|
||||
triggered_by: string;
|
||||
}
|
||||
|
||||
/** The summary returned by the sync_sessionize_event RPC. */
|
||||
export interface SyncSummary {
|
||||
speakers_created: number;
|
||||
speakers_updated: number;
|
||||
sessions_created: number;
|
||||
sessions_updated: number;
|
||||
slots_created: number;
|
||||
speakers_linked: number;
|
||||
errors: string[];
|
||||
}
|
||||
|
||||
/** The result of a (blocking) sidecar sync run. */
|
||||
export interface SyncResult {
|
||||
event_id: string;
|
||||
event_name?: string;
|
||||
started_at: string;
|
||||
finished_at: string;
|
||||
status: 'success' | 'error';
|
||||
summary?: SyncSummary;
|
||||
skipped_speakers?: string[];
|
||||
error?: string;
|
||||
}
|
||||
|
||||
/** The summary returned by the sync_sessionize_excel RPC. */
|
||||
export interface ExcelSyncSummary {
|
||||
speakers_created: number;
|
||||
speakers_updated: number;
|
||||
sessions_created: number;
|
||||
sessions_updated: number;
|
||||
slots_created: number;
|
||||
speakers_linked: number;
|
||||
registrations_created: number;
|
||||
registrations_updated: number;
|
||||
errors: string[];
|
||||
}
|
||||
|
||||
/** The result of a (blocking) sidecar Excel import. */
|
||||
export interface ExcelSyncResult {
|
||||
event_id: string;
|
||||
event_name?: string;
|
||||
started_at: string;
|
||||
finished_at: string;
|
||||
status: 'success' | 'error';
|
||||
summary?: ExcelSyncSummary;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
/** The sidecar's /status response. */
|
||||
export interface SidecarStatus {
|
||||
ok: boolean;
|
||||
running: boolean;
|
||||
lastRun: SyncResult | null;
|
||||
}
|
||||
|
||||
export interface Registration {
|
||||
id: string;
|
||||
event_id: string;
|
||||
|
||||
@@ -99,12 +99,49 @@ body {
|
||||
/* registration types */
|
||||
.pill.speaker { background: rgba(124,58,237,.12); border-color: rgba(124,58,237,.4); color: #6d28d9; }
|
||||
.pill.sponsor { background: rgba(234,88,12,.13); border-color: rgba(234,88,12,.4); color: #c2410c; }
|
||||
/* slot types */
|
||||
/* slot types (optionset: session | service_session) */
|
||||
.pill.session { background: rgba(14,165,233,.12); border-color: rgba(14,165,233,.4); color: #0369a1; }
|
||||
.pill.lunch_break { background: rgba(245,158,11,.14); border-color: rgba(245,158,11,.4); color: #b45309; }
|
||||
.pill.coffee_break { background: rgba(120,113,108,.14); border-color: rgba(120,113,108,.4); color: #57534e; }
|
||||
.pill.keynote { background: var(--accent-soft); border-color: rgba(213,0,0,.35); color: var(--accent); }
|
||||
.pill.close_up { background: rgba(5,150,105,.12); border-color: rgba(5,150,105,.35); color: var(--green); }
|
||||
.pill.service_session { background: rgba(245,158,11,.14); border-color: rgba(245,158,11,.4); color: #b45309; }
|
||||
|
||||
/* Uiverse tooltip (themrsami / ordinary-lion-95) — adapted to the admin theme.
|
||||
A purple/indigo "info" button that reveals a dark card on hover. */
|
||||
.uiverse-tooltip { position: relative; display: inline-block; }
|
||||
.uiverse-tooltip .uiverse-btn {
|
||||
position: relative; display: inline-flex; align-items: center; gap: 8px;
|
||||
padding: 10px 20px; font-size: 13px; font-weight: 600; color: #fff;
|
||||
background: rgba(79,70,229,.9); border: none; border-radius: 12px; cursor: pointer;
|
||||
overflow: hidden; transition: all .3s ease;
|
||||
}
|
||||
.uiverse-tooltip .uiverse-btn:hover { background: rgba(67,56,202,.9); }
|
||||
.uiverse-tooltip .uiverse-btn:focus { outline: none; box-shadow: 0 0 0 2px #6366f1; }
|
||||
.uiverse-tooltip .uiverse-btn::before {
|
||||
content: ''; position: absolute; inset: 0;
|
||||
background: linear-gradient(90deg, rgba(168,85,247,.2), rgba(236,72,153,.2));
|
||||
filter: blur(12px); opacity: 0; transition: opacity .3s ease;
|
||||
}
|
||||
.uiverse-tooltip .uiverse-btn:hover::before { opacity: .75; }
|
||||
.uiverse-tooltip .uiverse-btn > span { position: relative; display: inline-flex; align-items: center; gap: 8px; }
|
||||
.uiverse-tooltip .uiverse-card {
|
||||
position: absolute; bottom: calc(100% + 12px); left: 50%; transform: translate(-50%, 8px);
|
||||
width: 288px; padding: 16px; visibility: hidden; opacity: 0;
|
||||
background: linear-gradient(135deg, rgba(17,24,39,.96), rgba(31,41,55,.96));
|
||||
backdrop-filter: blur(8px); border: 1px solid rgba(255,255,255,.1); border-radius: 16px;
|
||||
box-shadow: 0 0 30px rgba(79,70,229,.15); transition: all .3s ease; z-index: 50;
|
||||
}
|
||||
.uiverse-tooltip:hover .uiverse-card { visibility: visible; opacity: 1; transform: translate(-50%, 0); }
|
||||
.uiverse-tooltip .uiverse-card::after {
|
||||
content: ''; position: absolute; bottom: -6px; left: 50%; transform: translateX(-50%) rotate(45deg);
|
||||
width: 12px; height: 12px; background: rgba(31,41,55,.96);
|
||||
border-right: 1px solid rgba(255,255,255,.1); border-bottom: 1px solid rgba(255,255,255,.1);
|
||||
}
|
||||
.uiverse-tooltip .uiverse-card .uiverse-head { display: flex; align-items: center; gap: 10px; margin-bottom: 8px; }
|
||||
.uiverse-tooltip .uiverse-card .uiverse-ico {
|
||||
display: flex; align-items: center; justify-content: center; width: 32px; height: 32px;
|
||||
border-radius: 50%; background: rgba(99,102,241,.2); color: #818cf8; flex-shrink: 0;
|
||||
}
|
||||
.uiverse-tooltip .uiverse-card h3 { margin: 0; font-size: 13px; font-weight: 600; color: #fff; }
|
||||
.uiverse-tooltip .uiverse-card p { margin: 0; font-size: 13px; line-height: 1.5; color: #d1d5db; }
|
||||
.uiverse-tooltip .uiverse-card .uiverse-foot { display: flex; align-items: center; gap: 8px; margin-top: 10px; font-size: 11px; color: #9ca3af; }
|
||||
/* sponsor tiers */
|
||||
.pill.headline { background: rgba(213,0,0,.1); border-color: rgba(213,0,0,.35); color: var(--red); }
|
||||
.pill.platinum { background: rgba(148,163,184,.16); border-color: rgba(148,163,184,.45); color: #475569; }
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { activateEvent, deactivateEvent, getAllEvents, upsertEvent } from '../lib/api';
|
||||
import type { Event } from '../lib/types';
|
||||
import { activateEvent, deactivateEvent, getAllEvents, runSessionizeSync, upsertEvent } from '../lib/api';
|
||||
import type { Event, SyncResult } from '../lib/types';
|
||||
import { useToast } from '../context/ToastContext';
|
||||
import { Empty, Modal, Spinner, Toggle } from '../components/ui';
|
||||
|
||||
@@ -10,6 +10,8 @@ export function Events() {
|
||||
const [loaded, setLoaded] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [modal, setModal] = useState<{ event: Event | null } | null>(null);
|
||||
const [syncingId, setSyncingId] = useState<string | null>(null);
|
||||
const [syncResult, setSyncResult] = useState<SyncResult | null>(null);
|
||||
|
||||
async function load() {
|
||||
try {
|
||||
@@ -36,6 +38,24 @@ export function Events() {
|
||||
}
|
||||
}
|
||||
|
||||
async function runSync(ev: Event) {
|
||||
if (!ev.sessionize_endpoint) {
|
||||
push('error', `Set a Sessionize endpoint for ${ev.name} first (Edit)`);
|
||||
return;
|
||||
}
|
||||
setSyncingId(ev.id);
|
||||
try {
|
||||
const result = await runSessionizeSync(ev.id);
|
||||
setSyncResult(result);
|
||||
await load();
|
||||
push('success', `Synced ${ev.name}`);
|
||||
} catch (e) {
|
||||
push('error', e instanceof Error ? e.message : 'Sync failed');
|
||||
} finally {
|
||||
setSyncingId(null);
|
||||
}
|
||||
}
|
||||
|
||||
if (error) return <Empty icon="⚠️" text={error} />;
|
||||
if (!loaded)
|
||||
return (
|
||||
@@ -97,9 +117,23 @@ export function Events() {
|
||||
/>
|
||||
</td>
|
||||
<td>
|
||||
<button className="btn small" onClick={() => setModal({ event: ev })}>
|
||||
Edit
|
||||
</button>
|
||||
<div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
|
||||
<button
|
||||
className="btn small"
|
||||
disabled={syncingId === ev.id}
|
||||
onClick={() => runSync(ev)}
|
||||
title={
|
||||
ev.sessionize_endpoint
|
||||
? 'Sync with Sessionize'
|
||||
: 'Set a Sessionize endpoint first (Edit)'
|
||||
}
|
||||
>
|
||||
{syncingId === ev.id ? 'Syncing…' : 'Sync'}
|
||||
</button>
|
||||
<button className="btn small" onClick={() => setModal({ event: ev })}>
|
||||
Edit
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
@@ -120,6 +154,8 @@ export function Events() {
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
{syncResult && <SyncResultModal result={syncResult} onClose={() => setSyncResult(null)} />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -137,6 +173,7 @@ function EventModal({
|
||||
const [startDate, setStartDate] = useState(event ? event.start_date.slice(0, 10) : '');
|
||||
const [endDate, setEndDate] = useState(event ? event.end_date.slice(0, 10) : '');
|
||||
const [location, setLocation] = useState(event?.location ?? '');
|
||||
const [endpoint, setEndpoint] = useState(event?.sessionize_endpoint ?? '');
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
async function save() {
|
||||
@@ -148,6 +185,7 @@ function EventModal({
|
||||
start_date: startDate,
|
||||
end_date: endDate,
|
||||
location: location.trim() || null,
|
||||
sessionize_endpoint: endpoint.trim() || null,
|
||||
});
|
||||
onSaved(event ? 'Event updated' : 'Event created');
|
||||
} catch (e) {
|
||||
@@ -191,6 +229,89 @@ function EventModal({
|
||||
<label>Location</label>
|
||||
<input className="input" value={location} onChange={(e) => setLocation(e.target.value)} placeholder="—" />
|
||||
</div>
|
||||
<div className="field">
|
||||
<label>Sessionize endpoint</label>
|
||||
<input
|
||||
className="input"
|
||||
value={endpoint}
|
||||
onChange={(e) => setEndpoint(e.target.value)}
|
||||
placeholder="https://sessionize.com/api/v2/<id>/view/All"
|
||||
/>
|
||||
<div className="muted small" style={{ marginTop: 4 }}>
|
||||
The Sessionize API URL (e.g. <code>…/api/v2/<id>/view/All</code>). Used by the
|
||||
“Run sync” button. You can also import the .xlsx export in the Interfaces menu.
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
function SyncResultModal({ result, onClose }: { result: SyncResult; onClose: () => void }) {
|
||||
const s = result.summary;
|
||||
return (
|
||||
<Modal
|
||||
open
|
||||
title={`Sessionize sync — ${result.event_name ?? result.event_id}`}
|
||||
onClose={onClose}
|
||||
footer={
|
||||
<button className="btn primary" onClick={onClose}>
|
||||
Close
|
||||
</button>
|
||||
}
|
||||
>
|
||||
{result.status === 'error' || !s ? (
|
||||
<div className="pill red" style={{ display: 'inline-block', padding: '8px 12px' }}>
|
||||
{result.error ?? 'Sync failed'}
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="stat-grid">
|
||||
<div className="stat">
|
||||
<div className="val">{s.speakers_created}</div>
|
||||
<div className="lbl">Speakers created</div>
|
||||
</div>
|
||||
<div className="stat">
|
||||
<div className="val">{s.speakers_updated}</div>
|
||||
<div className="lbl">Speakers updated</div>
|
||||
</div>
|
||||
<div className="stat">
|
||||
<div className="val">{s.sessions_created}</div>
|
||||
<div className="lbl">Sessions created</div>
|
||||
</div>
|
||||
<div className="stat">
|
||||
<div className="val">{s.sessions_updated}</div>
|
||||
<div className="lbl">Sessions updated</div>
|
||||
</div>
|
||||
<div className="stat">
|
||||
<div className="val">{s.slots_created}</div>
|
||||
<div className="lbl">Slots created</div>
|
||||
</div>
|
||||
<div className="stat">
|
||||
<div className="val">{s.speakers_linked}</div>
|
||||
<div className="lbl">Speaker links</div>
|
||||
</div>
|
||||
</div>
|
||||
{result.skipped_speakers && result.skipped_speakers.length > 0 && (
|
||||
<div className="muted small">
|
||||
Skipped {result.skipped_speakers.length} speaker(s) without an email: {result.skipped_speakers.join(', ')}
|
||||
</div>
|
||||
)}
|
||||
{s.errors.length > 0 && (
|
||||
<div style={{ marginTop: 12 }}>
|
||||
<div className="pill red" style={{ display: 'inline-block', marginBottom: 8 }}>
|
||||
{s.errors.length} error(s)
|
||||
</div>
|
||||
<ul style={{ margin: 0, paddingLeft: 18 }}>
|
||||
{s.errors.map((e, i) => (
|
||||
<li key={i} className="small">
|
||||
{e}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,431 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { getAllEvents, getSidecarStatus, getSyncRuns, importSessionizeExcel, runSessionizeSync } from '../lib/api';
|
||||
import type { Event, ExcelSyncResult, SidecarStatus, SyncResult, SyncRun } from '../lib/types';
|
||||
import { useToast } from '../context/ToastContext';
|
||||
import { Empty, Modal, Spinner } from '../components/ui';
|
||||
|
||||
export function Interfaces() {
|
||||
const { push } = useToast();
|
||||
const [events, setEvents] = useState<Event[]>([]);
|
||||
const [loaded, setLoaded] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [status, setStatus] = useState<SidecarStatus | null>(null);
|
||||
const [sidecarError, setSidecarError] = useState<string | null>(null);
|
||||
const [selectedId, setSelectedId] = useState<string>('');
|
||||
const [runs, setRuns] = useState<SyncRun[]>([]);
|
||||
const [running, setRunning] = useState(false);
|
||||
const [result, setResult] = useState<SyncResult | null>(null);
|
||||
const [excelFile, setExcelFile] = useState<File | null>(null);
|
||||
const [excelBusy, setExcelBusy] = useState(false);
|
||||
const [excelResult, setExcelResult] = useState<ExcelSyncResult | null>(null);
|
||||
const fileRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const loadableEvents = events.filter((e) => e.sessionize_endpoint);
|
||||
|
||||
async function load() {
|
||||
try {
|
||||
const evs = await getAllEvents();
|
||||
setEvents(evs);
|
||||
const first = evs.find((e) => e.sessionize_endpoint);
|
||||
if (first) setSelectedId((cur) => cur || first.id);
|
||||
setLoaded(true);
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : 'Failed to load');
|
||||
}
|
||||
}
|
||||
|
||||
async function loadStatus() {
|
||||
try {
|
||||
setStatus(await getSidecarStatus());
|
||||
setSidecarError(null);
|
||||
} catch (e) {
|
||||
setStatus(null);
|
||||
setSidecarError(e instanceof Error ? e.message : 'Sidecar unreachable');
|
||||
}
|
||||
}
|
||||
|
||||
async function loadRuns(eventId: string) {
|
||||
try {
|
||||
setRuns(await getSyncRuns(eventId));
|
||||
} catch {
|
||||
setRuns([]);
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
load();
|
||||
loadStatus();
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (selectedId) loadRuns(selectedId);
|
||||
}, [selectedId]);
|
||||
|
||||
// Poll the sidecar status while a sync is running (the run call is blocking,
|
||||
// so this mainly refreshes the "running" indicator + last run).
|
||||
const pollStatus = useCallback(() => {
|
||||
loadStatus();
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
if (!running) return;
|
||||
const t = setInterval(pollStatus, 3000);
|
||||
return () => clearInterval(t);
|
||||
}, [running, pollStatus]);
|
||||
|
||||
async function runSync() {
|
||||
if (!selectedId) return;
|
||||
setRunning(true);
|
||||
try {
|
||||
const res = await runSessionizeSync(selectedId);
|
||||
setResult(res);
|
||||
await Promise.all([load(), loadStatus(), loadRuns(selectedId)]);
|
||||
push('success', 'Sessionize sync finished');
|
||||
} catch (e) {
|
||||
push('error', e instanceof Error ? e.message : 'Sync failed');
|
||||
} finally {
|
||||
setRunning(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function importExcel() {
|
||||
if (!selectedId || !excelFile) return;
|
||||
setExcelBusy(true);
|
||||
try {
|
||||
const res = await importSessionizeExcel(selectedId, excelFile);
|
||||
setExcelResult(res);
|
||||
await Promise.all([load(), loadStatus(), loadRuns(selectedId)]);
|
||||
push('success', 'Excel import finished');
|
||||
} catch (e) {
|
||||
push('error', e instanceof Error ? e.message : 'Excel import failed');
|
||||
} finally {
|
||||
setExcelBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (error) return <Empty icon="⚠️" text={error} />;
|
||||
if (!loaded)
|
||||
return (
|
||||
<div className="loading-screen">
|
||||
<Spinner />
|
||||
</div>
|
||||
);
|
||||
|
||||
const selected = events.find((e) => e.id === selectedId);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="page-head">
|
||||
<div>
|
||||
<h1>Interfaces</h1>
|
||||
<div className="sub">External data sources. The Sessionize sidecar runs on demand only.</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Sidecar status */}
|
||||
<div className="card" style={{ marginBottom: 18 }}>
|
||||
<h2 className="h2">🔌 Sidecar status</h2>
|
||||
{sidecarError ? (
|
||||
<div className="pill red" style={{ display: 'inline-block', padding: '8px 12px' }}>
|
||||
{sidecarError}
|
||||
</div>
|
||||
) : status ? (
|
||||
<div style={{ display: 'flex', gap: 10, alignItems: 'center', flexWrap: 'wrap' }}>
|
||||
<span className={`pill ${status.ok ? 'green' : 'red'}`}>{status.ok ? 'online' : 'offline'}</span>
|
||||
{status.running && <span className="pill amber">sync running…</span>}
|
||||
{status.lastRun && (
|
||||
<span className="muted small">
|
||||
last run {fmtTime(status.lastRun.finished_at)} —{' '}
|
||||
<span className={status.lastRun.status === 'success' ? 'pill green' : 'pill red'}>
|
||||
{status.lastRun.status}
|
||||
</span>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<Spinner />
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Run control */}
|
||||
<div className="card" style={{ marginBottom: 18 }}>
|
||||
<h2 className="h2">▶ Run a sync</h2>
|
||||
{loadableEvents.length === 0 ? (
|
||||
<Empty icon="🔌" text="No events have a Sessionize endpoint yet. Set one in the Events menu." />
|
||||
) : (
|
||||
<div style={{ display: 'flex', gap: 12, alignItems: 'center', flexWrap: 'wrap' }}>
|
||||
<select
|
||||
className="input"
|
||||
style={{ maxWidth: 320 }}
|
||||
value={selectedId}
|
||||
onChange={(e) => setSelectedId(e.target.value)}
|
||||
>
|
||||
{loadableEvents.map((e) => (
|
||||
<option key={e.id} value={e.id}>
|
||||
{e.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<button className="btn primary" disabled={running || !selectedId} onClick={runSync}>
|
||||
{running ? 'Syncing…' : 'Run sync'}
|
||||
</button>
|
||||
{selected?.last_synced_at && (
|
||||
<span className="muted small">last synced {fmtTime(selected.last_synced_at)}</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Excel import (Sessions & speakers advanced) */}
|
||||
<div className="card" style={{ marginBottom: 18 }}>
|
||||
<h2 className="h2">📄 Import from Sessionize export</h2>
|
||||
<div className="muted small" style={{ marginBottom: 12, maxWidth: 640 }}>
|
||||
Upload the <strong>“Sessions and speakers (advanced)”</strong> .xlsx export from your
|
||||
Sessionize event. It imports speakers (by email), sessions, the agenda, and creates the
|
||||
speaker registrations — no API key needed.
|
||||
</div>
|
||||
<div style={{ display: 'flex', gap: 12, alignItems: 'center', flexWrap: 'wrap' }}>
|
||||
<select
|
||||
className="input"
|
||||
style={{ maxWidth: 320 }}
|
||||
value={selectedId}
|
||||
onChange={(e) => setSelectedId(e.target.value)}
|
||||
>
|
||||
{events.map((e) => (
|
||||
<option key={e.id} value={e.id}>
|
||||
{e.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<input
|
||||
ref={fileRef}
|
||||
type="file"
|
||||
accept=".xlsx,.xls"
|
||||
style={{ display: 'none' }}
|
||||
onChange={(e) => setExcelFile(e.target.files?.[0] ?? null)}
|
||||
/>
|
||||
<button className="btn" disabled={excelBusy} onClick={() => fileRef.current?.click()}>
|
||||
{excelFile ? `📎 ${excelFile.name}` : 'Choose .xlsx…'}
|
||||
</button>
|
||||
<button className="btn primary" disabled={excelBusy || !excelFile || !selectedId} onClick={importExcel}>
|
||||
{excelBusy ? 'Importing…' : 'Import'}
|
||||
</button>
|
||||
<div className="uiverse-tooltip">
|
||||
<button type="button" className="uiverse-btn">
|
||||
<span>
|
||||
<svg viewBox="0 0 24 24" stroke="currentColor" fill="none" width="16" height="16">
|
||||
<path d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" strokeWidth="2" strokeLinejoin="round" strokeLinecap="round" />
|
||||
</svg>
|
||||
How to get this file
|
||||
</span>
|
||||
</button>
|
||||
<div className="uiverse-card">
|
||||
<div className="uiverse-head">
|
||||
<div className="uiverse-ico">
|
||||
<svg viewBox="0 0 20 20" fill="currentColor" width="16" height="16">
|
||||
<path clipRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z" fillRule="evenodd" />
|
||||
</svg>
|
||||
</div>
|
||||
<h3>Export from Sessionize</h3>
|
||||
</div>
|
||||
<p>
|
||||
In your Sessionize event, open <strong>Export</strong> → <strong>“Sessions and
|
||||
speakers (advanced)”</strong> and download the .xlsx. Any organizer with access to
|
||||
the event can generate it. Upload it here to import speakers, sessions, the agenda
|
||||
and speaker registrations.
|
||||
</p>
|
||||
<div className="uiverse-foot">No API key required</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Recent runs (audit) */}
|
||||
<div className="card">
|
||||
<h2 className="h2">📜 Recent runs {selected ? `— ${selected.name}` : ''}</h2>
|
||||
{runs.length === 0 ? (
|
||||
<Empty icon="📜" text="No sync runs recorded for this event yet." />
|
||||
) : (
|
||||
<div className="table-wrap">
|
||||
<table className="data">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Started</th>
|
||||
<th>Finished</th>
|
||||
<th>Created</th>
|
||||
<th>Updated</th>
|
||||
<th>Status</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{runs.map((r) => (
|
||||
<tr key={r.id}>
|
||||
<td className="muted">{fmtTime(r.started_at)}</td>
|
||||
<td className="muted">{r.finished_at ? fmtTime(r.finished_at) : '—'}</td>
|
||||
<td className="muted">{r.created}</td>
|
||||
<td className="muted">{r.updated}</td>
|
||||
<td>
|
||||
{r.error ? (
|
||||
<span className="pill red" title={r.error}>
|
||||
error
|
||||
</span>
|
||||
) : (
|
||||
<span className="pill green">ok</span>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{result && <SyncResultModal result={result} onClose={() => setResult(null)} />}
|
||||
{excelResult && <ExcelResultModal result={excelResult} onClose={() => setExcelResult(null)} />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ExcelResultModal({ result, onClose }: { result: ExcelSyncResult; onClose: () => void }) {
|
||||
const s = result.summary;
|
||||
return (
|
||||
<Modal
|
||||
open
|
||||
title={`Excel import — ${result.event_name ?? result.event_id}`}
|
||||
onClose={onClose}
|
||||
footer={
|
||||
<button className="btn primary" onClick={onClose}>
|
||||
Close
|
||||
</button>
|
||||
}
|
||||
>
|
||||
{result.status === 'error' || !s ? (
|
||||
<div className="pill red" style={{ display: 'inline-block', padding: '8px 12px' }}>
|
||||
{result.error ?? 'Import failed'}
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="stat-grid">
|
||||
<div className="stat">
|
||||
<div className="val">{s.speakers_created}</div>
|
||||
<div className="lbl">Speakers created</div>
|
||||
</div>
|
||||
<div className="stat">
|
||||
<div className="val">{s.sessions_created}</div>
|
||||
<div className="lbl">Sessions created</div>
|
||||
</div>
|
||||
<div className="stat">
|
||||
<div className="val">{s.slots_created}</div>
|
||||
<div className="lbl">Slots created</div>
|
||||
</div>
|
||||
<div className="stat">
|
||||
<div className="val">{s.speakers_linked}</div>
|
||||
<div className="lbl">Speaker links</div>
|
||||
</div>
|
||||
<div className="stat">
|
||||
<div className="val">{s.registrations_created}</div>
|
||||
<div className="lbl">Speaker regs created</div>
|
||||
</div>
|
||||
<div className="stat">
|
||||
<div className="val">{s.registrations_updated}</div>
|
||||
<div className="lbl">Speaker regs updated</div>
|
||||
</div>
|
||||
</div>
|
||||
{s.errors.length > 0 && (
|
||||
<div style={{ marginTop: 12 }}>
|
||||
<div className="pill red" style={{ display: 'inline-block', marginBottom: 8 }}>
|
||||
{s.errors.length} error(s)
|
||||
</div>
|
||||
<ul style={{ margin: 0, paddingLeft: 18 }}>
|
||||
{s.errors.map((e, i) => (
|
||||
<li key={i} className="small">
|
||||
{e}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
function SyncResultModal({ result, onClose }: { result: SyncResult; onClose: () => void }) {
|
||||
const s = result.summary;
|
||||
return (
|
||||
<Modal
|
||||
open
|
||||
title={`Sessionize sync — ${result.event_name ?? result.event_id}`}
|
||||
onClose={onClose}
|
||||
footer={
|
||||
<button className="btn primary" onClick={onClose}>
|
||||
Close
|
||||
</button>
|
||||
}
|
||||
>
|
||||
{result.status === 'error' || !s ? (
|
||||
<div className="pill red" style={{ display: 'inline-block', padding: '8px 12px' }}>
|
||||
{result.error ?? 'Sync failed'}
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="stat-grid">
|
||||
<div className="stat">
|
||||
<div className="val">{s.speakers_created}</div>
|
||||
<div className="lbl">Speakers created</div>
|
||||
</div>
|
||||
<div className="stat">
|
||||
<div className="val">{s.speakers_updated}</div>
|
||||
<div className="lbl">Speakers updated</div>
|
||||
</div>
|
||||
<div className="stat">
|
||||
<div className="val">{s.sessions_created}</div>
|
||||
<div className="lbl">Sessions created</div>
|
||||
</div>
|
||||
<div className="stat">
|
||||
<div className="val">{s.sessions_updated}</div>
|
||||
<div className="lbl">Sessions updated</div>
|
||||
</div>
|
||||
<div className="stat">
|
||||
<div className="val">{s.slots_created}</div>
|
||||
<div className="lbl">Slots created</div>
|
||||
</div>
|
||||
<div className="stat">
|
||||
<div className="val">{s.speakers_linked}</div>
|
||||
<div className="lbl">Speaker links</div>
|
||||
</div>
|
||||
</div>
|
||||
{result.skipped_speakers && result.skipped_speakers.length > 0 && (
|
||||
<div className="muted small">
|
||||
Skipped {result.skipped_speakers.length} speaker(s) without an email: {result.skipped_speakers.join(', ')}
|
||||
</div>
|
||||
)}
|
||||
{s.errors.length > 0 && (
|
||||
<div style={{ marginTop: 12 }}>
|
||||
<div className="pill red" style={{ display: 'inline-block', marginBottom: 8 }}>
|
||||
{s.errors.length} error(s)
|
||||
</div>
|
||||
<ul style={{ margin: 0, paddingLeft: 18 }}>
|
||||
{s.errors.map((e, i) => (
|
||||
<li key={i} className="small">
|
||||
{e}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
function fmtTime(iso: string): string {
|
||||
return new Date(iso).toLocaleString([], {
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
});
|
||||
}
|
||||
@@ -16,7 +16,7 @@ import type { Contact, Event, Session, SessionSpeaker, Slot, SlotType } from '..
|
||||
import { useToast } from '../context/ToastContext';
|
||||
import { Empty, Modal, Spinner, TypeBadge } from '../components/ui';
|
||||
|
||||
const SLOT_TYPES: SlotType[] = ['session', 'lunch_break', 'coffee_break', 'keynote', 'close_up'];
|
||||
const SLOT_TYPES: SlotType[] = ['session', 'service_session'];
|
||||
|
||||
export function Schedule() {
|
||||
const { push } = useToast();
|
||||
|
||||
@@ -16,6 +16,14 @@ export default defineConfig({
|
||||
'/realtime': { target: SUPABASE_TARGET, changeOrigin: true, ws: true },
|
||||
'/storage': { target: SUPABASE_TARGET, changeOrigin: true },
|
||||
'/functions': { target: SUPABASE_TARGET, changeOrigin: true },
|
||||
// Sessionize sync sidecar (run `npm run sidecar:dev` to start it).
|
||||
// Strip the /sidecar prefix so /sidecar/run -> http://127.0.0.1:3002/run
|
||||
// (mirrors the nginx `location /sidecar/ { proxy_pass .../; }` rewrite).
|
||||
'/sidecar': {
|
||||
target: 'http://127.0.0.1:3002',
|
||||
changeOrigin: true,
|
||||
rewrite: (path) => path.replace(/^\/sidecar/, ''),
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
@@ -160,7 +160,7 @@ export function Scanner({ onResult, label = 'Scan a lanyard QR' }: { onResult: (
|
||||
<div className="row" style={{ gap: 8 }}>
|
||||
<input
|
||||
className="input mono"
|
||||
placeholder="…or type the code (e.g. CVV-ANA-4821)"
|
||||
placeholder="…or type the code (e.g. CVV-XXX-NNNN)"
|
||||
value={manual}
|
||||
onChange={(e) => setManual(e.target.value)}
|
||||
/>
|
||||
|
||||
@@ -83,9 +83,6 @@ export function Login() {
|
||||
<div className="h1">Welcome back 👋</div>
|
||||
<div className="muted small">Scan the QR code on your lanyard to log in.</div>
|
||||
<Scanner onResult={handleScan} label="Point your camera at your lanyard QR" />
|
||||
<div className="muted small" style={{ textAlign: 'center', opacity: 0.6 }}>
|
||||
Demo: type <b>CVV-ANA-4821</b> (Ana) or <b>CVV-BRU-1177</b> (Bruno, staff)
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -151,13 +148,11 @@ export function Login() {
|
||||
<button className="btn ghost small" style={{ alignSelf: 'flex-start' }} onClick={() => setStep('scan')}>
|
||||
← Different lanyard
|
||||
</button>
|
||||
<div className="muted small" style={{ textAlign: 'center', opacity: 0.6 }}>
|
||||
{isStaff ? (
|
||||
'Staff: QR + your admin password'
|
||||
) : (
|
||||
<>Demo: <b>ana.silva@nubank.com</b> · <b>bruno.costa@acme.com</b></>
|
||||
)}
|
||||
</div>
|
||||
{isStaff && (
|
||||
<div className="muted small" style={{ textAlign: 'center', opacity: 0.6 }}>
|
||||
Staff: QR + your admin password
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
# Convivo sidecar — Sessionize sync (on-demand).
|
||||
#
|
||||
# A small Node HTTP service driven by the APPE Admin "Interfaces" menu. It
|
||||
# fetches an event's Sessionize data (authenticated API) and writes it to
|
||||
# Supabase via the service-role-only sync_sessionize_event RPC.
|
||||
#
|
||||
# It joins the shared Supabase network and reaches PostgREST at
|
||||
# supabase_kong_Convivo:8000 (Kong's internal port). It is the first
|
||||
# server-side holder of the service-role key (see docs/backend/sidecar.md).
|
||||
#
|
||||
# One runtime dependency (xlsx, for parsing the Sessionize .xlsx export).
|
||||
FROM node:20-alpine
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY package.json ./
|
||||
RUN npm install --omit=dev
|
||||
COPY src/ ./src/
|
||||
|
||||
ENV NODE_ENV=production
|
||||
EXPOSE 3002
|
||||
|
||||
CMD ["node", "src/server.js"]
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"name": "convivo-sidecar",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"description": "Convivo Sessionize sync sidecar (on-demand, driven by APPE Admin).",
|
||||
"main": "src/server.js",
|
||||
"scripts": {
|
||||
"start": "node src/server.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"xlsx": "^0.18.5"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,382 @@
|
||||
// Convivo sidecar — Sessionize sync (on-demand).
|
||||
//
|
||||
// A tiny Node HTTP service driven by the APPE Admin "Interfaces" menu.
|
||||
// Endpoints:
|
||||
// GET /health -> { ok: true }
|
||||
// GET /status -> { ok, running, lastRun }
|
||||
// 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
|
||||
//
|
||||
// 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)
|
||||
// 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 PORT = parseInt(process.env.PORT || '3002', 10);
|
||||
|
||||
// In-memory last-run state (the sidecar is otherwise stateless).
|
||||
let running = false;
|
||||
let lastRun = 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;
|
||||
}
|
||||
|
||||
// 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 || '<unknown>');
|
||||
}
|
||||
}
|
||||
|
||||
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),
|
||||
is_service_session: Boolean(s.isServiceSession),
|
||||
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/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;
|
||||
}
|
||||
}
|
||||
|
||||
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 });
|
||||
}
|
||||
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);
|
||||
}
|
||||
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),
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user