diff --git a/backend/src/calendar/cardInvite.ts b/backend/src/calendar/cardInvite.ts index 3cfdb79a..fbe691fe 100644 --- a/backend/src/calendar/cardInvite.ts +++ b/backend/src/calendar/cardInvite.ts @@ -20,7 +20,7 @@ import { confirmedTitle, isPodcastInviteTitle, parseHoldDocumentUrl, podcastInvi import { listPodcastEpisodes, type PodcastEpisode } from '../db/podcastEpisodes'; import { recordTemplateTypes } from '../cards/cardTitlePattern'; import { deleteHoldGoogleEvents, fetchGoogleEvent, findGoneGoogleEvents, mergeHoldGoogleResults, syncLumaCalendarEvents, syncSilentGoogleCopies, type HoldGoogleDeps, type HoldGoogleResult } from './holdGoogleSync'; -import { lumaUrlForEventCard } from './lumaEvents'; +import { lumaEventSubtitle, lumaUrlForEventCard } from './lumaEvents'; import { PUBLIC_DTC_EVENTS_CALENDAR, resolveHoldGoogleCalendars } from './dapierBroker'; import { decryptSponsorDocAccessCode, getSponsorDocWithAuthMaterial } from '../db/sponsorDocs'; @@ -293,10 +293,14 @@ export async function syncCardInvite( linkedHold = active[0] || null; } const eventKey = card.eventTime?.eventKey || linkedHold?.id || `card:${card.id}`; - const eventIds = { + const recordedEventIds = { ...(card.eventTime?.googleEventIds || {}), ...(linkedHold?.googleEventIds || {}), }; + // The standalone public entry is recorded on the Card only, so a rerun or a + // move updates that same entry instead of leaving the old one behind. + const publicCopyIds: Record = Object.fromEntries(Object.entries(recordedEventIds).filter(([calendar]) => calendar === PUBLIC_DTC_EVENTS_CALENDAR)); + const eventIds = { ...recordedEventIds }; // A legacy public-calendar attendee copy is never part of the guest invite. delete eventIds[PUBLIC_DTC_EVENTS_CALENDAR]; // Podcast SOP: the confirmed invite is named for the guest, not the topic. @@ -336,59 +340,68 @@ export async function syncCardInvite( expectedVersion: card.version, patch: { eventTime: pending, guestEmails: silentLumaEvent ? [] : guests }, }); - // A silent Luma event (a course cohort Q&A or Launch and every other - // Luma-linked Card) gets the full SOP calendar set: the standalone public - // entry on the DTC events calendar plus the same content as silent - // organizer + personal hold copies (attendee-free, no email). Each leg is - // idempotent and recovers its partial writes on retry. - const publicCopyIds = { ...(eventIds[PUBLIC_DTC_EVENTS_CALENDAR] ? { [PUBLIC_DTC_EVENTS_CALENDAR]: eventIds[PUBLIC_DTC_EVENTS_CALENDAR] } : {}) }; + // Every Luma-linked Card owns one standalone public entry on the DTC events + // calendar beside its guest invite or silent copies (SOP + // `sop.events.luma.creating-events-on-google-calendar`): attendee-free, + // Zoom-free, at the real event time. A silent Luma event (a course cohort + // Q&A or Launch) adds the same content as silent organizer + personal hold + // copies. Each leg is idempotent and recovers its partial writes on retry; + // the hold itself carries the invitation only, never the public entry. const personalCopyIds = Object.fromEntries(Object.entries(eventIds).filter(([calendar]) => calendar !== PUBLIC_DTC_EVENTS_CALENDAR)); const lumaEvent = { eventKey, summary: card.title || 'DataTalks.Club event', - subtitle: card.description || undefined, startIso: interval.startIso, endIso: interval.endIso, timeZone: interval.timeZone, lumaUrl: lumaUrl!, }; - let sync: HoldGoogleResult; + /** The standalone public entry; a guest invite waits while Luma gives no subtitle. */ + const syncPublicEntry = async (): Promise => { + // A silent Card's description is its public subtitle. A guest invite + // Card's description holds internal scheduling notes and never goes + // public: its subtitle is the Luma event's own. + const subtitle = silentLumaEvent ? card.description || undefined : await lumaEventSubtitle(lumaUrl!, deps.fetchImpl); + return subtitle === undefined && !silentLumaEvent + ? { state: 'deferred', reason: 'The public DTC events entry needs the event subtitle, and the Luma page did not provide one. Check that the Luma event is public, then rerun.', eventIds: { ...publicCopyIds } } + : syncLumaCalendarEvents({ ...lumaEvent, subtitle }, deps, publicCopyIds); + }; + // One result per Google leg: the public entry first (when the Card has a + // Luma link), then the invitation or the silent copies. + const legs: HoldGoogleResult[] = []; try { - sync = silentLumaEvent - ? mergeHoldGoogleResults( - await syncLumaCalendarEvents(lumaEvent, deps, publicCopyIds), - await syncSilentGoogleCopies(lumaEvent, deps, personalCopyIds), - ) - : await writeGuestInvite(invite!, eventIds, deps); + if (lumaUrl) legs.push(await syncPublicEntry()); + legs.push(await (silentLumaEvent ? syncSilentGoogleCopies(lumaEvent, deps, personalCopyIds) : writeGuestInvite(invite!, eventIds, deps))); } catch (error) { if (error instanceof GuestInviteValidationError) await reportGuestInviteFailure(client, error, { cardId: card.id, actorId }); throw error; } + const sync = mergeHoldGoogleResults(...legs); + // Each leg links the entries it wrote and read back, so a partial sync shows + // exactly what is live. The Card is synced, and its invite Tasks close, only + // when every leg is. + const linkedEventIds = legs.filter((leg) => leg.state === 'synced').flatMap((leg) => Object.entries(leg.eventIds)); + const publicEntryLive = Boolean(lumaUrl) && legs[0].state === 'synced'; const updated = await updateCardAdditive(client, reserved, current => { const invites = [...(current.calendarInvites || [])]; - if (sync.state === 'synced') { - // Silent Luma events link every calendar copy they own (public entry, - // organizer and personal copies); guest invites never link the public - // calendar — its standalone entries are never invite copies. - const linkedEventIds = Object.entries(sync.eventIds).filter(([calendar]) => - silentLumaEvent || calendar !== PUBLIC_DTC_EVENTS_CALENDAR); - if (silentLumaEvent && sync.state === 'synced') { - for (let index = invites.length - 1; index >= 0; index--) { - if (invites[index].calendar === PUBLIC_DTC_EVENTS_CALENDAR) invites.splice(index, 1); - } + if (publicEntryLive) { + // Exactly one DTC events row: the standalone entry the public leg owns. + for (let index = invites.length - 1; index >= 0; index--) { + if (invites[index].calendar === PUBLIC_DTC_EVENTS_CALENDAR) invites.splice(index, 1); } - for (const [calendar, eventId] of linkedEventIds) { - const index = invites.findIndex(entry => entry.calendar === calendar && entry.eventId === eventId); - const entry = { - calendar, eventId, url: calendarInviteUrl(calendar, eventId), createdAt: new Date().toISOString(), createdBy: actorId, - ...(silentLumaEvent ? { label: card.title || 'Luma event' } : {}), - }; - if (index < 0) invites.push(entry); - else { - const refreshed = { ...invites[index] }; - delete refreshed.staleAt; - invites[index] = { ...refreshed, ...entry }; - } + } + for (const [calendar, eventId] of linkedEventIds) { + const index = invites.findIndex(entry => entry.calendar === calendar && entry.eventId === eventId); + const entry = { + calendar, eventId, url: calendarInviteUrl(calendar, eventId), createdAt: new Date().toISOString(), createdBy: actorId, + // Silent copies and the public entry are named for the event. + ...(silentLumaEvent || calendar === PUBLIC_DTC_EVENTS_CALENDAR ? { label: card.title || 'Luma event' } : {}), + }; + if (index < 0) invites.push(entry); + else { + const refreshed = { ...invites[index] }; + delete refreshed.staleAt; + invites[index] = { ...refreshed, ...entry }; } } return { @@ -399,11 +412,13 @@ export async function syncCardInvite( let storedHold: CalendarHold | undefined; if (linkedHold) { const preservedTopic = linkedHold.topic || (podcastTitle && linkedHold.title && !isPodcastInviteTitle(linkedHold.title) ? confirmedTitle(linkedHold.title) : undefined); + // The public entry belongs to the Card, so releasing the hold never has to touch it. + const inviteEventIds = Object.fromEntries(Object.entries(sync.eventIds).filter(([calendar]) => calendar !== PUBLIC_DTC_EVENTS_CALENDAR)); storedHold = { ...linkedHold, ...interval, cardId: card.id, title: confirmedTitle(inviteTitle), ...(preservedTopic ? { topic: preservedTopic } : {}), date: todayIn(interval.timeZone, new Date(interval.startIso)), googleTitle: confirmedTitle(inviteTitle), guestRef: guests[0], ...(documentUrl ? { documentUrl } : {}), status: 'confirmed', confirmedAt: linkedHold.confirmedAt || new Date().toISOString(), - googleEventIds: sync.eventIds, googleSync: { state: sync.state, ...(sync.state === 'deferred' ? { reason: sync.reason } : {}) }, + googleEventIds: inviteEventIds, googleSync: { state: sync.state, ...(sync.state === 'deferred' ? { reason: sync.reason } : {}) }, updatedAt: new Date().toISOString(), version: linkedHold.version + 1, }; await putCalendarHold(client, storedHold); diff --git a/backend/src/calendar/holdGoogleSync.ts b/backend/src/calendar/holdGoogleSync.ts index ae67a3e3..236bcf09 100644 --- a/backend/src/calendar/holdGoogleSync.ts +++ b/backend/src/calendar/holdGoogleSync.ts @@ -348,6 +348,8 @@ export function mergeHoldGoogleResults(...results: HoldGoogleResult[]): HoldGoog * Public event copy rules. This path writes one standalone event owned by the * public calendar, without attendees or conference data. Existing manual SOP * entries are adopted by matching title, time and Luma URL before insertion. + * A recorded entry id is updated in place, so a rerun or a move never leaves + * the previous entry behind. */ export async function syncLumaCalendarEvents( event: LumaCalendarEvent, @@ -397,6 +399,9 @@ export async function syncLumaCalendarEvents( if (PRIVATE_DETAIL_PATTERN.test(body.description)) { return deferred('Public calendar entry contains private meeting or document details.'); } + // Attendees or private meeting details never belong on a public entry. + const unsafe = (event: any) => Boolean(event && (event.attendees?.length || event.conferenceData + || /zoom\.us|ops\.dtcdev\.click/i.test(`${event.description || ''}\n${event.location || ''}`))); try { let current: any; if (eventIds[PUBLIC_DTC_EVENTS_CALENDAR]) { @@ -404,7 +409,10 @@ export async function syncLumaCalendarEvents( catch (error) { if (!(error instanceof Error) || !/HTTP (404|410)/.test(error.message)) throw error; } - if (current?.status === 'cancelled') current = undefined; + // Gone, cancelled, or not a standalone entry: a recorded id may point at + // a legacy attendee copy of the guest invite, which is never reused or + // edited, so the entry below is matched or created as if none was recorded. + if (current?.status === 'cancelled' || unsafe(current)) current = undefined; } if (!current) { const found = await request(`${url}?timeMin=${encodeURIComponent(event.startIso)}&timeMax=${encodeURIComponent(event.endIso)}&singleEvents=true&maxResults=250`); @@ -417,7 +425,7 @@ export async function syncLumaCalendarEvents( if (matches.length > 1) return deferred('Multiple matching public Luma entries exist; reconcile them before syncing.'); current = matches[0]; } - if (current?.attendees?.length || current?.conferenceData || /zoom\.us|ops\.dtcdev\.click/i.test(`${current?.description || ''}\n${current?.location || ''}`)) { + if (unsafe(current)) { return deferred('The public calendar event has attendees or private meeting details; it was left untouched.'); } const saved = current?.id diff --git a/backend/src/calendar/lumaEvents.ts b/backend/src/calendar/lumaEvents.ts index b738e191..b576282d 100644 --- a/backend/src/calendar/lumaEvents.ts +++ b/backend/src/calendar/lumaEvents.ts @@ -50,3 +50,51 @@ export async function lumaUrlForEventCard( } return null; } + +const LUMA_PAGE_LIMIT = 1024 * 1024; +const LUMA_SUBTITLE_LIMIT = 300; +const LUMA_FETCH_USER_AGENT = 'DataOps/1.0 (DataTalks.Club operations portal)'; + +const NAMED_ENTITIES: Record = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: ' ' }; + +/** Luma HTML-escapes its meta content (`'`, `"`, `&`). */ +function decodeHtmlEntities(text: string): string { + return text.replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi, (entity, body: string) => { + if (!body.startsWith('#')) return NAMED_ENTITIES[body.toLowerCase()] ?? entity; + const code = body[1].toLowerCase() === 'x' ? parseInt(body.slice(2), 16) : Number(body.slice(1)); + return code > 0 && code <= 0x10ffff ? String.fromCodePoint(code) : entity; + }); +} + +/** The decoded `content` of the first `` tag, in either attribute order. */ +function metaContent(html: string, name: string): string | undefined { + for (const [tag] of html.matchAll(/]*>/gi)) { + if (/\b(?:property|name)\s*=\s*["']([^"']+)["']/i.exec(tag)?.[1] !== name) continue; + const content = /\bcontent\s*=\s*"([^"]*)"/i.exec(tag)?.[1]; + if (content !== undefined) return decodeHtmlEntities(content); + } + return undefined; +} + +/** + * The Luma event's own subtitle: the first line of its public `og:description` + * (` - `). Undefined when Luma gives none (a missing, + * non-public or changed page); the caller decides what a missing subtitle means. + * Never throws. + */ +export async function lumaEventSubtitle(lumaUrl: string, fetchImpl?: typeof fetch): Promise { + try { + const response = await (fetchImpl || fetch)(lumaUrl, { + headers: { 'User-Agent': LUMA_FETCH_USER_AGENT, Accept: 'text/html' }, + signal: AbortSignal.timeout(10000), + }); + if (!response.ok) return undefined; + const declared = Number(response.headers.get('content-length') || 0); + if (declared > LUMA_PAGE_LIMIT) return undefined; + const raw = metaContent((await response.text()).slice(0, LUMA_PAGE_LIMIT), 'og:description')?.split(/\r?\n/)[0]; + const subtitle = raw?.replace(/\s+/g, ' ').trim().slice(0, LUMA_SUBTITLE_LIMIT); + return subtitle || undefined; + } catch { + return undefined; + } +} diff --git a/backend/tests/card-public-entry.test.ts b/backend/tests/card-public-entry.test.ts new file mode 100644 index 00000000..77bcf547 --- /dev/null +++ b/backend/tests/card-public-entry.test.ts @@ -0,0 +1,316 @@ +import { after, before, describe, it } from 'node:test'; +import assert from 'node:assert/strict'; +import type { DynamoDBDocumentClient } from '@aws-sdk/lib-dynamodb'; +import { DEFAULT_HOLD_GOOGLE_CALENDARS, PUBLIC_DTC_EVENTS_CALENDAR } from '../src/calendar/dapierBroker'; +import { HOLD_ORGANIZER } from '../src/calendar/holdGoogleSync'; +import { HOLD_ZOOM_LOCATION } from '../src/calendar/holds'; +import { lumaEventSubtitle } from '../src/calendar/lumaEvents'; +import { cardEventInterval } from '../src/calendar/cardEventTime'; +import { getClient } from '../src/db/client'; +import { getCalendarHold, putCalendarHold } from '../src/db/calendarHolds'; +import { getCardConsistent, updateCard } from '../src/db/cards'; +import { createTemplate } from '../src/db/templates'; +import { setCalendarHoldGoogleDepsForTests } from '../src/routes/calendarHolds'; +import { configureTaskChecklistStore } from '../src/taskChecklist'; +import { createTables, startLocal, stopLocal } from '../scripts/local-dynamodb'; +import { invokeHistoricalHoldFixture as handler } from './helpers/historical-card-hold'; +import { LUMA_SUBTITLE, holdGoogleProvider } from './helpers/hold-google'; +import { createTaskChecklistFixture } from './helpers/task-checklist-fixture'; + +const LUMA = 'https://luma.com/public-entry-podcast'; +const STREAM = 'https://www.youtube.com/datatalksclub'; +const PUBLIC_DESCRIPTION = `${LUMA_SUBTITLE}\nStream: ${STREAM}\nLuma: ${LUMA}`; +/** The scheduling notes a podcast Card's description holds; never public. */ +const INTERNAL_NOTES = 'Date confirmed: guest agreed by email (Gmail 1a1bd4f6d74ebe79); guest thread 1a1b1fdaaab1a625; Amazon email gurramk@amazon.com'; + +async function invoke(method: string, path: string, body?: unknown, queryStringParameters = {}) { + const res = await handler({ httpMethod: method, path, body: body ? JSON.stringify(body) : null, queryStringParameters }, {}); + return { code: res.statusCode, data: JSON.parse(res.body), raw: res.body }; +} + +describe('public DTC events entry beside a guest invitation', () => { + let db: DynamoDBDocumentClient; + let checklistFixture: ReturnType; + before(async () => { + checklistFixture = createTaskChecklistFixture(); + configureTaskChecklistStore(checklistFixture.store); + db = await getClient(await startLocal()); + await createTables(db); + }); + after(async () => { + setCalendarHoldGoogleDepsForTests({}); + configureTaskChecklistStore(null); + checklistFixture.cleanup(); + await stopLocal(); + }); + + function google() { + const provider = holdGoogleProvider(); + setCalendarHoldGoogleDepsForTests({ fetchImpl: provider.fetchImpl, credential: 'test', connectionId: 'orin' }); + return provider; + } + /** A podcast Card with a Luma link, a proposed hold and an internal description, as Orin schedules one. */ + async function podcastCard(label: string) { + const template = await createTemplate(db, { name: label, type: 'podcast', origin: 'git', triggerType: 'manual', taskDefinitions: [ + { refId: 'create-calendar-invite', description: 'Create a calendar invite for the guests', offsetDays: 0 }, + ] }); + const created = await invoke('POST', '/api/cards', { templateId: template.id, title: `${label} at DataTalks.Club`, anchorDate: '2026-12-01' }); + assert.equal(created.code, 201, created.raw); + const { card } = created.data; + await updateCard(db, card.id, { + expectedVersion: card.version, + patch: { description: INTERNAL_NOTES, cardLinks: [{ name: 'Luma', url: LUMA }] }, + }); + const proposed = await invoke('POST', '/api/calendar-holds', { date: '2026-12-01', title: label, topic: 'Test', cardId: card.id, guestRef: 'guest@example.test' }); + assert.equal(proposed.code, 201, proposed.raw); + return { card: (await getCardConsistent(db, card.id))!, hold: proposed.data.hold }; + } + const time = (cardId: string, at: string, body: Record = {}) => + invoke('POST', `/api/cards/${cardId}/time`, { at, duration: 60, tz: 'Europe/Berlin', guestEmails: ['guest@example.test'], ...body }); + const publicEvents = (provider: ReturnType) => [...(provider.events.get(PUBLIC_DTC_EVENTS_CALENDAR)?.values() || [])]; + const publicRows = (card: { calendarInvites?: Array<{ calendar: string }> }) => + (card.calendarInvites || []).filter((invite) => invite.calendar === PUBLIC_DTC_EVENTS_CALENDAR); + const inviteTasks = async (cardId: string) => (await invoke('GET', '/api/tasks', undefined, { cardId })).data.tasks; + /** Organizer PATCHes that notify guests: one per real invitation or move, never per rerun. */ + const guestNotifications = (provider: ReturnType) => provider.calls.filter((call) => + call.method === 'PATCH' && call.url.searchParams.get('sendUpdates') === 'all' + && decodeURIComponent(call.url.pathname).includes(HOLD_ORGANIZER)).length; + + it('cards time adds exactly one SOP-format public entry beside the private invitation and links it as the DTC events row', async () => { + const provider = google(); + const { card } = await podcastCard('Public entry'); + const timed = await time(card.id, '2026-12-01 17:00'); + assert.equal(timed.code, 200, timed.raw); + assert.equal(timed.data.invite.outcome, 'sent'); + + assert.equal(publicEvents(provider).length, 1, 'exactly one public entry'); + const [entry] = publicEvents(provider); + assert.equal(entry.summary, card.title, 'the public entry carries the event title, not the guest invitation title'); + assert.equal(entry.start.dateTime, '2026-12-01T16:00:00.000Z', 'real event time: 17:00 Berlin, not the T-5 invitation window'); + assert.equal(entry.end.dateTime, '2026-12-01T17:00:00.000Z'); + assert.equal(entry.start.timeZone, 'Europe/Berlin'); + assert.equal(entry.location, STREAM); + assert.equal(entry.description, PUBLIC_DESCRIPTION); + assert.deepEqual(entry.attendees || [], [], 'a public entry has no guests'); + assert.ok(!('conferenceData' in entry), 'a public entry has no meeting'); + assert.ok(!JSON.stringify(entry).includes('amazon.com'), 'the Card description is internal and never published'); + assert.equal(provider.calls.find((call) => call.method === 'POST' && decodeURIComponent(call.url.pathname).includes(PUBLIC_DTC_EVENTS_CALENDAR) + && !call.url.pathname.endsWith('/import'))!.url.searchParams.get('sendUpdates'), 'none'); + + // Separate from the invitation: that keeps Zoom and the guest, and never invites the public calendar. + const ids = timed.data.card.eventTime.googleEventIds; + assert.equal(entry.id, ids[PUBLIC_DTC_EVENTS_CALENDAR]); + assert.notEqual(ids[PUBLIC_DTC_EVENTS_CALENDAR], ids[HOLD_ORGANIZER]); + const organizer = provider.events.get(HOLD_ORGANIZER)!.get(ids[HOLD_ORGANIZER]); + assert.equal(organizer.location, HOLD_ZOOM_LOCATION); + assert.ok(organizer.attendees.some((attendee: { email: string }) => attendee.email === 'guest@example.test')); + assert.ok(!organizer.attendees.some((attendee: { email: string }) => attendee.email === PUBLIC_DTC_EVENTS_CALENDAR)); + assert.deepEqual(Object.keys(ids), [PUBLIC_DTC_EVENTS_CALENDAR, HOLD_ORGANIZER, ...DEFAULT_HOLD_GOOGLE_CALENDARS]); + assert.equal(timed.data.invite.googleEventIds[PUBLIC_DTC_EVENTS_CALENDAR], entry.id); + + // Linked on the Card as its single DTC events row, and listed live by cards invite list. + assert.equal(publicRows(timed.data.card).length, 1); + assert.equal(publicRows(timed.data.card)[0].eventId, entry.id); + assert.equal(publicRows(timed.data.card)[0].label, card.title); + assert.deepEqual(timed.data.card.calendarInvites.map((invite) => invite.calendar), + [PUBLIC_DTC_EVENTS_CALENDAR, HOLD_ORGANIZER, ...DEFAULT_HOLD_GOOGLE_CALENDARS]); + const listed = await invoke('GET', `/api/cards/${card.id}/calendar-invites`, undefined, { verify: '1' }); + assert.equal(listed.data.check.state, 'verified'); + assert.equal(listed.data.invites.find((invite: { calendar: string }) => invite.calendar === PUBLIC_DTC_EVENTS_CALENDAR).staleAt, undefined); + assert.equal(timed.data.taskClosure.outcome, 'closed'); + assert.equal((await inviteTasks(card.id))[0].status, 'done'); + }); + + it('a rerun reuses the same entries and a move updates the public entry in place', async () => { + const provider = google(); + const { card } = await podcastCard('Moved entry'); + const first = (await time(card.id, '2026-12-01 17:00')).data; + const [publicId, organizerId] = [PUBLIC_DTC_EVENTS_CALENDAR, HOLD_ORGANIZER].map((calendar) => first.card.eventTime.googleEventIds[calendar]); + assert.equal(guestNotifications(provider), 1); + + const again = (await time(card.id, '2026-12-01 17:00')).data; + assert.equal(again.card.eventTime.googleEventIds[PUBLIC_DTC_EVENTS_CALENDAR], publicId); + assert.equal(publicRows(again.card).length, 1, 'one DTC events row after a rerun'); + assert.equal(publicEvents(provider).length, 1, 'a rerun adds no second public entry'); + assert.equal(provider.events.get(HOLD_ORGANIZER)!.size, 1); + assert.equal(guestNotifications(provider), 1, 'a rerun notifies nobody'); + + const moved = (await time(card.id, '2026-12-08 18:00', { duration: 90 })).data; + assert.equal(moved.card.eventTime.googleEventIds[PUBLIC_DTC_EVENTS_CALENDAR], publicId, 'the public entry moves; none is left behind at the old time'); + assert.equal(moved.card.eventTime.googleEventIds[HOLD_ORGANIZER], organizerId); + assert.equal(publicEvents(provider).length, 1); + const entry = provider.events.get(PUBLIC_DTC_EVENTS_CALENDAR)!.get(publicId); + assert.equal(entry.start.dateTime, '2026-12-08T17:00:00.000Z'); + assert.equal(entry.end.dateTime, '2026-12-08T18:30:00.000Z'); + assert.equal(entry.location, STREAM); + assert.equal(entry.description, PUBLIC_DESCRIPTION); + assert.deepEqual(publicRows(moved.card).map((row) => row.eventId), [publicId]); + assert.equal(guestNotifications(provider), 2, 'only the move notifies the guest'); + // The public calendar is only ever written silently. + for (const call of provider.calls.filter((item) => ['POST', 'PATCH'].includes(item.method) + && decodeURIComponent(item.url.pathname).includes(PUBLIC_DTC_EVENTS_CALENDAR) && !item.url.pathname.endsWith('/import'))) { + assert.equal(call.url.searchParams.get('sendUpdates'), 'none'); + } + }); + + it('a deferred public leg leaves the Card deferred and the invite Task open; the rerun completes it without re-inviting', async () => { + const provider = google(); + provider.state.failCalendar = PUBLIC_DTC_EVENTS_CALENDAR; + const { card } = await podcastCard('Deferred entry'); + const first = await time(card.id, '2026-12-01 17:00'); + assert.equal(first.code, 502, first.raw); + assert.equal(first.data.invite.outcome, 'deferred'); + assert.match(first.data.error, /public event sync could not complete/); + assert.equal(provider.events.get(HOLD_ORGANIZER)!.size, 1, 'the invitation itself was written'); + assert.equal(publicEvents(provider).length, 0); + // What is live is linked, so the missing DTC events row is visible. + assert.deepEqual(first.data.card.calendarInvites.map((invite) => invite.calendar), [HOLD_ORGANIZER, ...DEFAULT_HOLD_GOOGLE_CALENDARS]); + assert.equal(first.data.taskClosure.outcome, 'not_attempted'); + assert.equal((await inviteTasks(card.id))[0].status, 'todo', 'the Task cannot close while the public entry is missing'); + assert.equal(guestNotifications(provider), 1); + + provider.state.failCalendar = ''; + const retried = await time(card.id, '2026-12-01 17:00'); + assert.equal(retried.code, 200, retried.raw); + assert.equal(retried.data.invite.outcome, 'sent'); + assert.equal(retried.data.taskClosure.outcome, 'closed'); + assert.equal(publicEvents(provider).length, 1); + assert.equal(provider.events.get(HOLD_ORGANIZER)!.size, 1); + assert.equal(publicRows(retried.data.card).length, 1); + assert.equal(retried.data.card.calendarInvites.length, 3); + assert.equal((await inviteTasks(card.id))[0].status, 'done'); + assert.equal(guestNotifications(provider), 1, 'the retry notifies nobody'); + }); + + it('a hold that still carries a pre-Orin invitation blocks only the invitation: the public entry is created and listed', async () => { + const provider = google(); + const { card, hold } = await podcastCard('Legacy hold'); + // Before invitations had an Orin organizer, a hold recorded its Google events under other calendars. + await putCalendarHold(db, { ...hold, googleEventIds: { primary: 'legacy-invite', [PUBLIC_DTC_EVENTS_CALENDAR]: 'gone-public-copy' } }); + const timed = await time(card.id, '2026-12-01 17:00'); + assert.equal(timed.code, 502, timed.raw); + assert.match(timed.data.error, /organizer reconciliation before sending an Orin invite/); + assert.equal(timed.data.invite.outcome, 'deferred'); + assert.equal(guestNotifications(provider), 0, 'a pre-Orin invitation is never re-issued or impersonated'); + + const [entry] = publicEvents(provider); + assert.equal(publicEvents(provider).length, 1, 'the gone public copy is neither reused nor duplicated'); + assert.equal(entry.summary, card.title); + assert.equal(entry.description, PUBLIC_DESCRIPTION); + assert.deepEqual(timed.data.card.calendarInvites.map((invite) => [invite.calendar, invite.eventId]), [[PUBLIC_DTC_EVENTS_CALENDAR, entry.id]]); + assert.equal(timed.data.card.eventTime.sync, 'deferred'); + assert.equal(timed.data.card.eventTime.googleEventIds.primary, 'legacy-invite'); + assert.equal((await inviteTasks(card.id))[0].status, 'todo'); + const listed = await invoke('GET', `/api/cards/${card.id}/calendar-invites`, undefined, { verify: '1' }); + assert.equal(listed.data.check.state, 'verified'); + assert.equal(listed.data.invites.length, 1); + assert.equal(listed.data.invites[0].staleAt, undefined); + assert.equal(timed.data.hold.googleEventIds[PUBLIC_DTC_EVENTS_CALENDAR], undefined); + + // A rerun moves nothing and adds nothing. + const again = await time(card.id, '2026-12-01 17:00'); + assert.equal(again.code, 502, again.raw); + assert.equal(again.data.card.eventTime.googleEventIds[PUBLIC_DTC_EVENTS_CALENDAR], entry.id); + assert.equal(publicEvents(provider).length, 1); + assert.equal(guestNotifications(provider), 0); + }); + + it('waits for the Luma subtitle rather than publish the Card description or an entry without one', async () => { + const provider = google(); + provider.state.lumaStatus = 404; + const { card } = await podcastCard('No Luma subtitle'); + const first = await time(card.id, '2026-12-01 17:00'); + assert.equal(first.code, 502, first.raw); + assert.match(first.data.error, /Luma page did not provide one/); + assert.equal(publicEvents(provider).length, 0, 'nothing is published without the Luma subtitle'); + + provider.state.lumaStatus = 200; + const retried = await time(card.id, '2026-12-01 17:00'); + assert.equal(retried.code, 200, retried.raw); + assert.equal(publicEvents(provider)[0].description, PUBLIC_DESCRIPTION); + assert.ok(!JSON.stringify(publicEvents(provider)).includes('amazon.com'), 'the Card description is internal and never published'); + }); + + it('confirm-hold creates the public entry too, and the hold itself carries the invitation only', async () => { + const provider = google(); + const { card, hold } = await podcastCard('Confirmed hold'); + const confirmed = await invoke('POST', `/api/calendar-holds/${hold.id}/confirm`, {}); + assert.equal(confirmed.code, 200, confirmed.raw); + assert.equal(confirmed.data.hold.googleSync.state, 'synced'); + + const storedHold = (await getCalendarHold(db, hold.id))!; + assert.ok(storedHold.googleEventIds[HOLD_ORGANIZER]); + assert.equal(storedHold.googleEventIds[PUBLIC_DTC_EVENTS_CALENDAR], undefined, 'releasing the hold never has to touch the public calendar'); + const stored = (await getCardConsistent(db, card.id))!; + assert.equal(publicRows(stored).length, 1); + const [entry] = publicEvents(provider); + assert.equal(entry.id, stored.eventTime!.googleEventIds[PUBLIC_DTC_EVENTS_CALENDAR]); + assert.equal(entry.summary, card.title); + assert.equal(entry.description, PUBLIC_DESCRIPTION); + assert.deepEqual(entry.attendees || [], []); + + // Re-timing the Card keeps the hold free of the public entry and moves the entry in place. + const moved = await time(card.id, '2026-12-02 17:00'); + assert.equal(moved.code, 200, moved.raw); + assert.equal(moved.data.hold.googleEventIds[PUBLIC_DTC_EVENTS_CALENDAR], undefined); + assert.equal(moved.data.card.eventTime.googleEventIds[PUBLIC_DTC_EVENTS_CALENDAR], entry.id); + assert.equal(publicEvents(provider).length, 1); + }); + + it('never reuses a legacy public attendee copy, and leaves a matching hand-made entry with guests untouched', async () => { + const provider = google(); + // Before public entries stood alone, the public calendar held an attendee copy of the invitation. + const legacy = { + id: 'legacy-copy', status: 'confirmed', summary: 'Legacy episode', location: HOLD_ZOOM_LOCATION, + description: 'Zoom link: https://zoom.us/j/1', attendees: [{ email: 'guest@example.test' }], + start: { dateTime: '2026-12-01T16:00:00.000Z', timeZone: 'Europe/Berlin' }, + end: { dateTime: '2026-12-01T17:00:00.000Z', timeZone: 'Europe/Berlin' }, + }; + provider.events.set(PUBLIC_DTC_EVENTS_CALENDAR, new Map([['legacy-copy', legacy]])); + const { card, hold } = await podcastCard('Legacy copy'); + const interval = cardEventInterval('2026-12-01 17:00'); + const seeded = await updateCard(db, card.id, { + expectedVersion: card.version, + patch: { + eventTime: { ...interval, eventKey: hold.id, googleEventIds: { ...hold.googleEventIds, [PUBLIC_DTC_EVENTS_CALENDAR]: 'legacy-copy' }, sync: 'synced', syncStartedAt: new Date().toISOString() }, + calendarInvites: [{ eventId: 'legacy-copy', calendar: PUBLIC_DTC_EVENTS_CALENDAR, createdAt: new Date().toISOString(), createdBy: 'test' }], + }, + }); + const timed = await time(card.id, '2026-12-01 17:00'); + assert.equal(timed.code, 200, timed.raw); + assert.deepEqual(provider.events.get(PUBLIC_DTC_EVENTS_CALENDAR)!.get('legacy-copy'), legacy, 'the legacy copy is neither edited nor deleted'); + assert.equal(publicEvents(provider).length, 2); + assert.deepEqual(publicRows(timed.data.card).map((row) => row.eventId), [timed.data.card.eventTime.googleEventIds[PUBLIC_DTC_EVENTS_CALENDAR]]); + assert.notEqual(timed.data.card.eventTime.googleEventIds[PUBLIC_DTC_EVENTS_CALENDAR], 'legacy-copy'); + assert.equal(timed.data.hold.googleEventIds[PUBLIC_DTC_EVENTS_CALENDAR], undefined); + assert.equal(seeded.version, card.version + 1); + + // A hand-made entry that matches this event but has guests is reported, never edited or duplicated. + const { card: other } = await podcastCard('Handmade entry'); + const handmade = { + id: 'handmade', status: 'confirmed', summary: other.title, location: STREAM, + description: `A hand-made subtitle\nStream: ${STREAM}\nLuma: ${LUMA}`, attendees: [{ email: 'someone@example.test' }], + start: { dateTime: '2026-12-03T16:00:00.000Z', timeZone: 'Europe/Berlin' }, + end: { dateTime: '2026-12-03T17:00:00.000Z', timeZone: 'Europe/Berlin' }, + }; + provider.events.set(PUBLIC_DTC_EVENTS_CALENDAR, new Map([['handmade', handmade]])); + const refused = await time(other.id, '2026-12-03 17:00'); + assert.equal(refused.code, 502, refused.raw); + assert.match(refused.data.error, /attendees or private meeting details; it was left untouched/); + assert.deepEqual([...provider.events.get(PUBLIC_DTC_EVENTS_CALENDAR)!.values()], [handmade]); + }); +}); + +describe('Luma event subtitle', () => { + const page = (content: string) => (async () => new Response( + ``, { status: 200 })) as typeof fetch; + + it('is the first line of the public og:description, entities decoded and bounded; a missing page gives none', async () => { + assert.equal(await lumaEventSubtitle(LUMA, page('Agents "answering questions" - Ann & Bob's team Long description …')), + 'Agents "answering questions" - Ann & Bob\'s team'); + assert.equal((await lumaEventSubtitle(LUMA, page(`${'s'.repeat(400)} next`)))!.length, 300); + assert.equal(await lumaEventSubtitle(LUMA, (async () => new Response('')) as typeof fetch), undefined); + assert.equal(await lumaEventSubtitle(LUMA, (async () => new Response('gone', { status: 404 })) as typeof fetch), undefined); + assert.equal(await lumaEventSubtitle(LUMA, (async () => { throw new Error('offline'); }) as typeof fetch), undefined); + }); +}); diff --git a/backend/tests/course-event-slots.test.ts b/backend/tests/course-event-slots.test.ts index 03bcff6e..8825a4c5 100644 --- a/backend/tests/course-event-slots.test.ts +++ b/backend/tests/course-event-slots.test.ts @@ -299,7 +299,6 @@ describe('course event slots: event Cards instead of text', () => { dtcEvent.status = 'cancelled'; const verifiedStale = await invoke('GET', `/api/cards/${qaCardId}/calendar-invites`, undefined, { verify: '1' }); assert.ok(parsed(verifiedStale).invites.find((invite: any) => invite.eventId === dtcEventId).staleAt); - dtcEvent.status = 'confirmed'; const moved = await invoke('POST', `/api/cards/${qaCardId}/time`, { at: '2026-11-11 17:00' }); assert.equal(moved.statusCode, 200, moved.body); @@ -312,6 +311,17 @@ describe('course event slots: event Cards instead of text', () => { assert.equal(google.events.get(DEFAULT_HOLD_GOOGLE_CALENDARS[0])!.size, 3, 'moving updates the personal copy in place instead of duplicating'); assert.ok(google.calls.filter((call) => call.method === 'PATCH').every((call) => call.url.searchParams.get('sendUpdates') === 'none')); + // A live public entry moves with its Card: the same entry, none left behind at the old time. + const liveDtcEventId = parsed(moved).card.eventTime.googleEventIds[PUBLIC_DTC_EVENTS_CALENDAR]; + assert.notEqual(liveDtcEventId, dtcEventId); + const movedAgain = await invoke('POST', `/api/cards/${qaCardId}/time`, { at: '2026-11-12 18:00' }); + assert.equal(movedAgain.statusCode, 200, movedAgain.body); + assert.equal(parsed(movedAgain).card.eventTime.googleEventIds[PUBLIC_DTC_EVENTS_CALENDAR], liveDtcEventId); + assert.deepEqual(parsed(movedAgain).card.calendarInvites.map((invite: any) => invite.calendar).sort(), + [PUBLIC_DTC_EVENTS_CALENDAR, HOLD_ORGANIZER, ...DEFAULT_HOLD_GOOGLE_CALENDARS].sort()); + assert.equal(google.events.get(PUBLIC_DTC_EVENTS_CALENDAR)!.get(liveDtcEventId).start.dateTime, '2026-11-12T17:00:00.000Z'); + assert.equal(google.events.get(PUBLIC_DTC_EVENTS_CALENDAR)!.size, 4, 'moving updates the public entry in place instead of leaving the old one behind'); + courseTasks = await listTasksByCard(client, created.card.id); const latestPrepare = courseTasks.find((task) => task.templateTaskRef === 'prepare-events')!; const complete = await invoke('PUT', `/api/tasks/${latestPrepare.id}`, { expectedVersion: latestPrepare.version, status: 'done' }); diff --git a/backend/tests/helpers/hold-google.ts b/backend/tests/helpers/hold-google.ts index 1aaac0c5..759789eb 100644 --- a/backend/tests/helpers/hold-google.ts +++ b/backend/tests/helpers/hold-google.ts @@ -2,14 +2,23 @@ import assert from 'node:assert/strict'; import { PUBLIC_DTC_EVENTS_CALENDAR } from '../../src/calendar/dapierBroker'; import { HOLD_ORGANIZER } from '../../src/calendar/holdGoogleSync'; +/** The subtitle the fake Luma event page carries for every event (` - `). */ +export const LUMA_SUBTITLE = 'Public subtitle - Guest Speaker'; +const LUMA_PAGE = `` + + ``; + export function holdGoogleProvider() { const events = new Map>(); const calls: Array<{ url: URL; method: string; body?: any }> = []; let sequence = 0; - const state = { account: HOLD_ORGANIZER, failCalendar: '', loseInviteResponse: false }; + const state = { account: HOLD_ORGANIZER, failCalendar: '', loseInviteResponse: false, lumaStatus: 200 }; const fetchImpl = (async (input: any, init: any = {}) => { const url = new URL(String(input)); const method = init.method || 'GET'; + // A guest invite Card's public subtitle comes from its Luma event page. That read is not a Google call. + if (/^(luma\.com|lu\.ma)$/.test(url.hostname)) { + return new Response(state.lumaStatus === 200 ? LUMA_PAGE : 'not found', { status: state.lumaStatus }); + } const body = init.body ? JSON.parse(init.body) : undefined; calls.push({ url, method, body }); if (url.pathname === '/api/agent/token') return Response.json({ access_token: 'test-google' }); diff --git a/cli/src/commands/cards.mjs b/cli/src/commands/cards.mjs index 0c12636c..91617bcf 100644 --- a/cli/src/commands/cards.mjs +++ b/cli/src/commands/cards.mjs @@ -45,8 +45,9 @@ Usage dataops cards update --count FIELD=N[,FIELD=N] [--apply] Change a count (e.g. workshops=3); preview by default dataops cards time --at "YYYY-MM-DD HH:MM" [--duration 60] [--tz Europe/Berlin] - [--guests EMAIL,EMAIL] [--json] Set the event time; Luma events sync silently to DTC - events and Alexey personal, other events invite guests + [--guests EMAIL,EMAIL] [--json] Set the event time. A Luma link adds the public entry on + DTC events (no guests, no Zoom); a Luma Card without a + hold gets silent copies, other Cards invite guests dataops cards event-slots [--apply] [--json] A course's event Cards (Q&A, launch, workshops); --apply creates and links the missing ones, undated @@ -595,7 +596,8 @@ export async function time(args, io) { if (result.card.anchorDate) io.print(`Card date: ${result.card.anchorDate}${result.movedTasks ? ` (${result.movedTasks} open Tasks re-dated)` : ''}`); if (result.rescheduleTaskId) io.print(`Reschedule checklist Task: ${result.rescheduleTaskId}`); for (const invite of result.card.calendarInvites || []) { - io.print(`invite: ${invite.eventId} on ${calendarLabel(invite.calendar)}${invite.staleAt ? ' STALE (gone in Google)' : ''} ${invite.url || ''}`); + const kind = String(invite.calendar).endsWith('@group.calendar.google.com') ? 'public entry' : 'invite'; + io.print(`${kind}: ${invite.eventId} on ${calendarLabel(invite.calendar)}${invite.staleAt ? ' STALE (gone in Google)' : ''} ${invite.url || ''}`); } if (result.taskClosure?.message) io.print(`taskClosure (${result.taskClosure.outcome}): ${result.taskClosure.message}`); } diff --git a/cli/test/card-time.test.mjs b/cli/test/card-time.test.mjs index cda8e01f..31f7467e 100644 --- a/cli/test/card-time.test.mjs +++ b/cli/test/card-time.test.mjs @@ -47,6 +47,27 @@ test('cards time human output prints invite result and task-closure outcome', as assert.match(text, /invite: evt-1/); assert.match(text, /taskClosure \(blocked\): Invite task "Create a calendar invite for guest speaker"/); }); +test('cards time labels the public DTC events entry apart from the guest invitation', async () => { + fakePortal({ + 'POST /api/cards/test/time': { + card: { + id: 'test', + eventTime: { startIso: '2026-12-01T16:00:00.000Z', endIso: '2026-12-01T17:00:00.000Z', timeZone: 'Europe/Berlin' }, + calendarInvites: [ + { eventId: 'public-1', calendar: 'f8qidjnq0jhscp8809k1eghs60@group.calendar.google.com', label: 'From Ad-Hoc SQL to AI Agents' }, + { eventId: 'private-1', calendar: 'orin@datatalks.club' }, + ], + }, + invite: { outcome: 'sent', state: 'synced' }, + taskClosure: { outcome: 'closed', message: 'Closed invite task.', tasks: [] }, + }, + }); + const io = captureIo(); + assert.equal(await run(['cards', 'time', 'test', '--at', '2026-12-01 17:00'], io), 0); + const text = io.text(); + assert.match(text, /public entry: public-1 on DTC events/); + assert.match(text, /invite: private-1 on orin@datatalks\.club/); +}); test('cards time requires --at before requesting API', async () => { const calls = fakePortal({}); const io = captureIo();