fix: import localized topics and flattened Sessionize speakers
This commit is contained in:
1 parent
5c93d4a0cb
commit
648daa0794
6 files changed
+226
-88
No files matched your search
@@ -5,7 +5,8 @@
|
||||
"description": "Convivo Sessionize sync sidecar (on-demand, driven by APPE Admin).",
|
||||
"main": "src/server.js",
|
||||
"scripts": {
|
||||
"start": "node src/server.js"
|
||||
"start": "node src/server.js",
|
||||
"test": "node --test tests/transform-excel.test.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"pdfkit": "^0.15.0",
|
||||
|
||||
@@ -41,6 +41,7 @@
|
||||
|
||||
const http = require('http');
|
||||
const XLSX = require('xlsx');
|
||||
const { transformExcel } = require('./transform-excel');
|
||||
const PDFDocument = require('pdfkit');
|
||||
|
||||
const SUPABASE_URL = (process.env.SUPABASE_URL || 'http://supabase_kong_Convivo:8000').replace(/\/$/, '');
|
||||
@@ -288,87 +289,6 @@ function transform(data) {
|
||||
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'] ?? '')),
|
||||
// Level + area (free-text classification for agenda filtering).
|
||||
// The Sessionize "Sessions and speakers (advanced)" .xlsx may include
|
||||
// "Level" and "Area"/"Topic" columns; we read them if present.
|
||||
level: String(r['Level'] ?? '').trim() || null,
|
||||
area: String(r['Area'] ?? r['Topic'] ?? '').trim() || null,
|
||||
speakers: speakerEmails,
|
||||
});
|
||||
}
|
||||
|
||||
return { payload: { speakers, sessions } };
|
||||
}
|
||||
|
||||
async function runSync(eventId) {
|
||||
if (running) throw new Error('a sync is already running');
|
||||
running = true;
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
const XLSX = require('xlsx');
|
||||
|
||||
function excelSerialToTime(serial, durationMin) {
|
||||
const ms = Math.round((serial - 25569) * 86400 * 1000);
|
||||
const date = new Date(ms);
|
||||
const end = new Date(ms + (durationMin || 0) * 60 * 1000);
|
||||
return {
|
||||
date: date.toISOString().slice(0, 10),
|
||||
start_time: date.toISOString().slice(11, 19),
|
||||
end_time: end.toISOString().slice(11, 19),
|
||||
};
|
||||
}
|
||||
|
||||
function firstNonempty(row, headers) {
|
||||
for (const header of headers) {
|
||||
const value = String(row[header.toLowerCase()] ?? '').trim();
|
||||
if (value) return value;
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
function transformExcel(buffer) {
|
||||
const workbook = XLSX.read(buffer, { type: 'buffer' });
|
||||
const toRows = (kind, otherKind) => {
|
||||
const sheetName = workbook.SheetNames.find((name) =>
|
||||
name.toLowerCase().includes(kind) && !name.toLowerCase().includes(otherKind))
|
||||
|| workbook.SheetNames.find((name) => name.toLowerCase().includes(kind));
|
||||
if (!sheetName) return [];
|
||||
return XLSX.utils.sheet_to_json(workbook.Sheets[sheetName], { defval: '' }).map((row) =>
|
||||
Object.fromEntries(Object.entries(row).map(([header, value]) => [header.trim().toLowerCase(), value])));
|
||||
};
|
||||
|
||||
const speakerById = new Map();
|
||||
const speakersByEmail = new Map();
|
||||
for (const row of toRows('speaker', 'session')) {
|
||||
const id = firstNonempty(row, ['Speaker Id']);
|
||||
const email = firstNonempty(row, ['Email']);
|
||||
const fullName = [firstNonempty(row, ['FirstName']), firstNonempty(row, ['LastName'])]
|
||||
.filter(Boolean).join(' ');
|
||||
if (!id || !email || !fullName) continue;
|
||||
speakerById.set(id, email);
|
||||
if (!speakersByEmail.has(email)) {
|
||||
speakersByEmail.set(email, {
|
||||
email,
|
||||
full_name: fullName,
|
||||
external_id: id,
|
||||
linkedin_url: firstNonempty(row, ['LinkedIn']) || null,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const sessionsById = new Map();
|
||||
for (const row of toRows('session', 'speaker')) {
|
||||
const id = firstNonempty(row, ['Session Id']);
|
||||
const title = firstNonempty(row, ['Title']);
|
||||
const scheduledAt = Number(row['scheduled at']);
|
||||
const duration = Number(row['scheduled duration']);
|
||||
if (!id || !title || !scheduledAt) continue;
|
||||
const area = firstNonempty(row, ['Themenfeld / Area of Topic', 'Area', 'Topic']) || null;
|
||||
if (!sessionsById.has(id)) {
|
||||
sessionsById.set(id, {
|
||||
external_id: id,
|
||||
title,
|
||||
description: firstNonempty(row, ['Description']) || null,
|
||||
room: firstNonempty(row, ['Room']) || null,
|
||||
...excelSerialToTime(scheduledAt, duration),
|
||||
is_service_session: /service|break|lunch|closing|plenum/i.test(firstNonempty(row, ['Session Format'])),
|
||||
level: firstNonempty(row, ['Level']) || null,
|
||||
area,
|
||||
speakers: [],
|
||||
});
|
||||
}
|
||||
const session = sessionsById.get(id);
|
||||
if (!session.area && area) session.area = area;
|
||||
const speakerIds = firstNonempty(row, ['Speaker Ids', 'Speaker Id'])
|
||||
.split(',').map((speakerId) => speakerId.trim()).filter(Boolean);
|
||||
for (const speakerId of speakerIds) {
|
||||
const email = speakerById.get(speakerId);
|
||||
if (email && !session.speakers.includes(email)) session.speakers.push(email);
|
||||
}
|
||||
}
|
||||
|
||||
return { payload: { speakers: [...speakersByEmail.values()], sessions: [...sessionsById.values()] } };
|
||||
}
|
||||
|
||||
module.exports = { transformExcel };
|
||||
@@ -0,0 +1,92 @@
|
||||
const { test } = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const XLSX = require('xlsx');
|
||||
const { transformExcel } = require('../src/transform-excel');
|
||||
|
||||
function transformSheets(sheets) {
|
||||
const workbook = XLSX.utils.book_new();
|
||||
for (const [name, rows] of Object.entries(sheets)) {
|
||||
XLSX.utils.book_append_sheet(workbook, XLSX.utils.json_to_sheet(rows), name);
|
||||
}
|
||||
return transformExcel(XLSX.write(workbook, { type: 'buffer', bookType: 'xlsx' })).payload;
|
||||
}
|
||||
|
||||
const sessionRow = {
|
||||
'Session Id': 'session-1', Title: 'Synthetic session', Description: 'Test description',
|
||||
Room: 'Test room', 'Scheduled At': 46305.375, 'Scheduled Duration': 45,
|
||||
'Session Format': 'Talk', Level: 'Intermediate',
|
||||
};
|
||||
const speakerRow = {
|
||||
'Speaker Id': 'speaker-1', Email: '[email protected]', FirstName: 'Test', LastName: 'One',
|
||||
LinkedIn: 'https://example.test/one',
|
||||
};
|
||||
|
||||
test('localized topic preserves the complete comma-separated string with normalized headers', () => {
|
||||
const payload = transformSheets({ 'Accepted sessions and speakers': [{
|
||||
...sessionRow, ...speakerRow, ' themenfeld / area OF topic ': ' Copilot Studio, Power Automate ',
|
||||
Area: 'Ignored area', Topic: 'Ignored topic',
|
||||
}] });
|
||||
assert.equal(payload.sessions[0].area, 'Copilot Studio, Power Automate');
|
||||
assert.deepEqual(payload.sessions[0].speakers, ['[email protected]']);
|
||||
});
|
||||
|
||||
test('empty recognized headers fall back to nonempty Area then Topic without fuzzy categories', () => {
|
||||
for (const [columns, expected] of [
|
||||
[{ 'Themenfeld / Area of Topic': '', Area: ' Area value ', Topic: 'Topic value' }, 'Area value'],
|
||||
[{ 'Themenfeld / Area of Topic': ' ', Area: '', Topic: ' Topic value ' }, 'Topic value'],
|
||||
[{ Area: '', Topic: '', Category: 'Unrelated value' }, null],
|
||||
]) {
|
||||
const payload = transformSheets({ 'Accepted sessions': [{ ...sessionRow, ...columns }] });
|
||||
assert.equal(payload.sessions[0].area, expected);
|
||||
}
|
||||
});
|
||||
|
||||
test('flattened repeated rows merge all speaker emails and deduplicate sessions and speakers', () => {
|
||||
const first = { ...sessionRow, ...speakerRow, 'Themenfeld / Area of Topic': 'Copilot Studio, Power Automate' };
|
||||
const second = { ...first, 'Speaker Id': 'speaker-2', Email: '[email protected]', LastName: 'Two' };
|
||||
const payload = transformSheets({ 'Accepted sessions and speakers': [first, second, first, second] });
|
||||
assert.equal(payload.sessions.length, 1);
|
||||
assert.equal(payload.speakers.length, 2);
|
||||
assert.deepEqual(payload.speakers.map((speaker) => speaker.external_id), ['speaker-1', 'speaker-2']);
|
||||
assert.deepEqual(payload.sessions[0].speakers, ['[email protected]', '[email protected]']);
|
||||
assert.equal(payload.sessions[0].area, first['Themenfeld / Area of Topic']);
|
||||
});
|
||||
|
||||
test('legacy advanced two-sheet export retains plural speaker IDs and session metadata', () => {
|
||||
const payload = transformSheets({
|
||||
'Accepted sessions': [{ ...sessionRow, 'Speaker Ids': 'speaker-2, speaker-1, speaker-2, unknown', Area: 'Power Apps' }],
|
||||
'Accepted speakers': [speakerRow, { ...speakerRow, 'Speaker Id': 'speaker-2', Email: '[email protected]' }],
|
||||
});
|
||||
assert.equal(payload.speakers.length, 2);
|
||||
assert.deepEqual(payload.sessions[0], {
|
||||
external_id: 'session-1', title: 'Synthetic session', description: 'Test description',
|
||||
room: 'Test room', date: '2026-10-10', start_time: '09:00:00', end_time: '09:45:00',
|
||||
is_service_session: false, level: 'Intermediate', area: 'Power Apps',
|
||||
speakers: ['[email protected]', '[email protected]'],
|
||||
});
|
||||
assert.equal(payload.speakers[0].linkedin_url, 'https://example.test/one');
|
||||
});
|
||||
|
||||
test('empty plural speaker IDs fall back to singular and shared speakers are emitted once', () => {
|
||||
const first = { ...sessionRow, ...speakerRow, 'Speaker Ids': '' };
|
||||
const payload = transformSheets({ 'Accepted sessions and speakers': [
|
||||
first, { ...first, 'Session Id': 'session-2' },
|
||||
] });
|
||||
assert.equal(payload.speakers.length, 1);
|
||||
assert.equal(payload.sessions.length, 2);
|
||||
for (const session of payload.sessions) {
|
||||
assert.deepEqual(session.speakers, ['[email protected]']);
|
||||
}
|
||||
});
|
||||
|
||||
test('service session classification and unscheduled-row filtering remain unchanged', () => {
|
||||
const formats = ['Service', 'Coffee break', 'Lunch', 'Closing', 'Plenum', 'Talk'];
|
||||
const payload = transformSheets({ 'Accepted sessions and speakers': [
|
||||
...formats.map((format, index) => ({ ...sessionRow, 'Session Id': `session-${index}`, 'Session Format': format })),
|
||||
{ ...sessionRow, 'Session Id': 'unscheduled', 'Scheduled At': '' },
|
||||
{ ...sessionRow, 'Session Id': 'untitled', Title: '' },
|
||||
] });
|
||||
assert.equal(payload.sessions.length, formats.length);
|
||||
assert.deepEqual(payload.sessions.map((session) => session.is_service_session), [true, true, true, true, true, false]);
|
||||
assert.ok(payload.sessions.every((session) => session.speakers.length === 0));
|
||||
});
|
||||
+25
-6
@@ -5,8 +5,9 @@ The **sidecar** is a small Node HTTP service that syncs an event's agenda from
|
||||
component that holds the **service-role key**, and it is driven entirely by the
|
||||
APPE Admin **Interfaces** menu — it runs **on demand only** (no scheduling).
|
||||
|
||||
- Code: [`apps/sidecar/`](../../apps/sidecar/) (single file:
|
||||
[`src/server.js`](../../apps/sidecar/src/server.js))
|
||||
- Code: [`apps/sidecar/`](../../apps/sidecar/), HTTP service in
|
||||
[`src/server.js`](../../apps/sidecar/src/server.js), pure Excel transform in
|
||||
[`src/transform-excel.js`](../../apps/sidecar/src/transform-excel.js)
|
||||
- Image: [`apps/sidecar/Dockerfile`](../../apps/sidecar/Dockerfile)
|
||||
(`node:20-alpine`; runtime dependencies **`xlsx`** (parse the Sessionize Excel
|
||||
export) and **`pdfkit`** (render the PDF report) — everything else is built-in
|
||||
@@ -34,9 +35,12 @@ speaker emails, so this path imports sessions + agenda but **skips speakers**
|
||||
> registered **staff** member as a speaker.
|
||||
|
||||
**B. Excel import** (`POST /import-excel`) — the admin uploads the Sessionize
|
||||
**"Sessions and speakers (advanced)"** `.xlsx` export (generated on the fly by
|
||||
any organizer with admin access to the event). The sidecar parses it (two sheets:
|
||||
*Accepted sessions* + *Accepted speakers*) and calls the
|
||||
`.xlsx` export (generated on the fly by any organizer with admin access to the
|
||||
event). Supported formats are the legacy **"Sessions and speakers (advanced)"**
|
||||
export (two sheets: *Accepted sessions* + *Accepted speakers*, with plural
|
||||
**Speaker Ids**) and the flattened **Accepted sessions and speakers** sheet
|
||||
(one session/speaker pair per row, with singular **Speaker Id**). The sidecar
|
||||
parses it and calls the
|
||||
`sync_sessionize_excel` RPC, which imports, in order: (1) speakers as contacts
|
||||
(matched by **email** — the Excel carries emails, so this is reliable), (2)
|
||||
sessions + agenda (slots typed `session` / `service_session` from the
|
||||
@@ -47,6 +51,21 @@ registration for every speaker** (create, or update `attendee`→`speaker`; neve
|
||||
overrides `staff`/`sponsor`). This is the path that creates the missing speaker
|
||||
contacts + registrations.
|
||||
|
||||
Excel rows are grouped by **Session Id** into one session with all distinct
|
||||
speaker emails; repeated speakers are emitted once by email. Separate session
|
||||
and speaker sheets take precedence over a combined sheet if both are present.
|
||||
Sessions without a title, ID, or scheduled time are skipped as before.
|
||||
|
||||
Topic classification uses the first nonempty value of **Themenfeld / Area of
|
||||
Topic**, **Area**, then **Topic**. Headers are trimmed and matched
|
||||
case-insensitively; unrelated category headers are not inferred. Values are
|
||||
trimmed but otherwise preserved as a single string, including comma-separated
|
||||
topics in their original order. **Level** remains an optional free-text value.
|
||||
For repeated session rows, the first row supplies session metadata; a later
|
||||
nonempty topic can fill an initially empty topic, and speaker links are merged.
|
||||
See [Excel transform tests](./tests.md#sessionize-excel-transform) for the
|
||||
database-free regression command.
|
||||
|
||||
Linking a speaker to a session fires the `session_speakers_speaker_promote`
|
||||
trigger, which promotes an existing registration to `speaker`.
|
||||
|
||||
@@ -104,7 +123,7 @@ transforms, calls the RPC, and returns the summary. The admin's "Sync" button an
|
||||
the Interfaces "Run sync" both call it and show the result inline.
|
||||
|
||||
`/import-excel` is **blocking** too: it reads the uploaded `.xlsx` (parsed with
|
||||
`xlsx`), transforms the two sheets into the `sync_sessionize_excel` payload, and
|
||||
`xlsx`), transforms either supported format into the `sync_sessionize_excel` payload, and
|
||||
calls that RPC. The admin's Interfaces **"Import Excel"** control posts the file
|
||||
here and shows the result inline.
|
||||
|
||||
|
||||
@@ -131,6 +131,26 @@ cross-event slot/dependent mismatches fail atomically instead of cascading
|
||||
foreign-event rows. This is local validation only; it does not write migration
|
||||
history or deploy anything.
|
||||
|
||||
## Sessionize Excel Transform
|
||||
|
||||
The sidecar's [Excel transform tests](../../apps/sidecar/tests/transform-excel.test.js)
|
||||
use Node's built-in test runner and the installed `xlsx` dependency. They
|
||||
generate synthetic workbooks in memory, without real personal data, server
|
||||
startup, HTTP calls, or database access:
|
||||
|
||||
```bash
|
||||
npm test --prefix apps/sidecar
|
||||
node --check apps/sidecar/src/transform-excel.js
|
||||
node --check apps/sidecar/src/server.js
|
||||
```
|
||||
|
||||
Coverage includes the localized topic header, trimmed/case-insensitive header
|
||||
matching, nonempty Area/Topic fallback, complete comma-separated topic strings,
|
||||
flattened multi-speaker session grouping, duplicate speaker IDs/emails, singular
|
||||
Speaker Id fallback, legacy two-sheet plural Speaker Ids, scheduled time and
|
||||
metadata preservation, service-session classification, and unscheduled-row
|
||||
filtering. See [supported Excel formats](./sidecar.md#what-it-does).
|
||||
|
||||
## Files
|
||||
|
||||
- [`supabase/tests/rpc_tests.sql`](../../supabase/tests/rpc_tests.sql) — the test
|
||||
|
||||
Reference in new issue
Block a user