diff --git a/backend/src/calendar/linkConfirmedHold.ts b/backend/src/calendar/linkConfirmedHold.ts index c7e8c175..51c103b7 100644 --- a/backend/src/calendar/linkConfirmedHold.ts +++ b/backend/src/calendar/linkConfirmedHold.ts @@ -4,6 +4,7 @@ import { getCardConsistent } from '../db/cards'; import { getCalendarHold, listCalendarHolds } from '../db/calendarHolds'; import type { PodcastEpisode } from '../db/podcastEpisodes'; import { adoptEventDate, calendarInviteUrl, closeCardInviteTasks, parseCardGuests } from './cardInvite'; +import { ensureCardQnaForDatedEvent } from '../qna/service'; import { HOLD_ZOOM_LOCATION, HOLD_ATTENDEE_DENY_LIST } from './holds'; import { buildGuestInvite } from './guestInvite'; import { fetchGoogleEvent, HOLD_ORGANIZER, type HoldGoogleDeps } from './holdGoogleSync'; @@ -124,6 +125,7 @@ export async function linkConfirmedHold( catch (e: any) { if (['TransactionCanceledException', 'ConditionalCheckFailedException'].includes(e.name)) throw new HoldLinkError('Calendar association changed; reread all records before retrying'); throw e; } const linked = (await getCardConsistent(client, card.id))!; const dated = await adoptEventDate(client, linked, card.eventTime); + await ensureCardQnaForDatedEvent(client, dated.card); const taskClosure = await closeCardInviteTasks(client, dated.card, actorId); return { mode: 'apply', ...preview, card: (await getCardConsistent(client, card.id))!, taskClosure }; } \ No newline at end of file diff --git a/backend/src/cards/createCard.ts b/backend/src/cards/createCard.ts index 09ac2db1..16b7e2d0 100644 --- a/backend/src/cards/createCard.ts +++ b/backend/src/cards/createCard.ts @@ -6,6 +6,7 @@ * created anywhere is instantiated from a Template and gets the same * validation, ownership rule, Template projection, and title parsing. */ +import { ensureCardQnaQuietly, isQnaEventType } from '../qna/service'; import type { DynamoDBDocumentClient } from '@aws-sdk/lib-dynamodb'; import { prepareGuestIntake } from '../events/guestIntakeCreate'; @@ -369,7 +370,11 @@ export async function createCardFromInput( body.counts as Record | undefined, intake?.tasks, ); - return { ok: true, card, tasks, template }; + // Dated podcast, webinar and workshop Cards get their audience Q&A room now; undated Cards get one once dated. + const withQna = isQnaEventType(template.type) && card.anchorDate + ? await ensureCardQnaQuietly(client, card) + : card; + return { ok: true, card: withQna, tasks, template }; } catch (error) { if (intake) { try { diff --git a/backend/src/docs/frontend-assets.json b/backend/src/docs/frontend-assets.json index 13904854..31a67bb7 100644 --- a/backend/src/docs/frontend-assets.json +++ b/backend/src/docs/frontend-assets.json @@ -218,6 +218,7 @@ "src/surfaces/work-detail/card-documents.js", "src/surfaces/work-detail/card-invites.js", "src/surfaces/work-detail/card-panel.js", + "src/surfaces/work-detail/card-qna.js", "src/surfaces/work-detail/card-references.js", "src/surfaces/work-detail/card-summary.js", "src/surfaces/work-detail/card-template-review.js", diff --git a/backend/src/qna/client.ts b/backend/src/qna/client.ts new file mode 100644 index 00000000..c31cd6fb --- /dev/null +++ b/backend/src/qna/client.ts @@ -0,0 +1,113 @@ +/** + * Client for the DataQnA audience Q&A service (https://qna.dtcdev.click, + * DataTalksClub/dataqna). Authenticates with the API key kept in the team + * secret store as `.dataqna-api-key`; the key is never logged. + */ +import { readRuntimeSecret } from '../secrets/reader'; + +export const QNA_BASE_URL = 'https://qna.dtcdev.click'; + +export interface QnaRoom { + roomId: string; + slug: string; + url: string; + presentUrl: string; + state: string; +} + +export interface QnaQuestion { + questionId: string; + text: string; + authorName: string | null; + status: string; + score: number; + pinned: boolean; + createdAt: string; + answeredAt: string | null; +} + +export interface QnaClient { + createRoom(input: { title: string; slug: string; description: string; idempotencyKey: string }): Promise; + addRoomAdmin(roomId: string, email: string): Promise; + closeRoom(roomId: string): Promise; + listQuestions(roomId: string): Promise; +} + +export class QnaServiceError extends Error {} + +function secretName(): string { + return process.env.DATAQNA_API_KEY_SECRET_NAME || 'dataops-v1.dataqna-api-key'; +} + +function toRoom(raw: Record): QnaRoom { + return { + roomId: String(raw.room_id), + slug: String(raw.slug), + url: String(raw.url), + presentUrl: String(raw.present_url || ''), + state: String(raw.state), + }; +} + +function toQuestion(raw: Record): QnaQuestion { + return { + questionId: String(raw.question_id), + text: String(raw.text), + authorName: raw.anonymous || !raw.author_name ? null : String(raw.author_name), + status: String(raw.status), + score: Number(raw.score) || 0, + pinned: raw.pinned === true, + createdAt: String(raw.created_at), + answeredAt: raw.answered_at ? String(raw.answered_at) : null, + }; +} + +export function createQnaClient( + fetchImpl: typeof fetch = fetch, + readKey: () => Promise = () => readRuntimeSecret(secretName()), +): QnaClient { + async function call(method: string, path: string, body?: unknown): Promise> { + const key = (await readKey()).trim(); + const response = await fetchImpl(`${QNA_BASE_URL}/api/v1${path}`, { + method, + headers: { authorization: `Bearer ${key}`, ...(body ? { 'content-type': 'application/json' } : {}) }, + ...(body ? { body: JSON.stringify(body) } : {}), + }); + const text = await response.text(); + let parsed: Record = {}; + try { parsed = text ? JSON.parse(text) : {}; } catch { /* non-JSON error body */ } + if (!response.ok) { + const detail = (parsed.error as { message?: string } | undefined)?.message || text.slice(0, 200); + throw new QnaServiceError(`Q&A service ${method} ${path} failed (${response.status}): ${detail}`); + } + return parsed; + } + return { + async createRoom(input) { + return toRoom(await call('POST', '/rooms', { + title: input.title, + slug: input.slug, + description: input.description, + state: 'open', + idempotency_key: input.idempotencyKey, + })); + }, + async addRoomAdmin(roomId, email) { + await call('POST', `/rooms/${encodeURIComponent(roomId)}/admins`, { email }); + }, + async closeRoom(roomId) { + return toRoom(await call('PATCH', `/rooms/${encodeURIComponent(roomId)}`, { state: 'closed' })); + }, + async listQuestions(roomId) { + const items: QnaQuestion[] = []; + let cursor: string | null = null; + do { + const qs: string = `status=visible&status=answered&limit=500${cursor ? `&cursor=${encodeURIComponent(cursor)}` : ''}`; + const page = await call('GET', `/rooms/${encodeURIComponent(roomId)}/questions?${qs}`); + for (const item of (page.items as Record[]) || []) items.push(toQuestion(item)); + cursor = typeof page.next_cursor === 'string' && page.next_cursor ? page.next_cursor : null; + } while (cursor); + return items; + }, + }; +} diff --git a/backend/src/qna/service.ts b/backend/src/qna/service.ts new file mode 100644 index 00000000..bdaa5789 --- /dev/null +++ b/backend/src/qna/service.ts @@ -0,0 +1,150 @@ +import type { DynamoDBDocumentClient } from '@aws-sdk/lib-dynamodb'; +import { updateCardAdditive } from '../db/cards'; +import { getTemplate } from '../db/templates'; +import type { Card, CardQna, CardQnaQuestion } from '../types'; +import { createQnaClient, type QnaClient } from './client'; + +/** Event formats that get an audience Q&A room (sponsorship is only a flag). */ +export const QNA_EVENT_TYPES = ['podcast', 'webinar', 'workshop'] as const; + +let client: QnaClient | null = null; +export function setQnaClientForTests(next: QnaClient | null): void { + client = next; +} +function qna(): QnaClient { + return client ?? (client = createQnaClient()); +} + +export function isQnaEventType(type: string | null | undefined): boolean { + return (QNA_EVENT_TYPES as readonly string[]).includes(String(type || '').toLowerCase()); +} + +export async function cardHasQnaEventType(db: DynamoDBDocumentClient, card: Card): Promise { + const template = await getTemplate(db, card.templateId); + return isQnaEventType(template?.type); +} + +function slugFor(card: Card): string { + const base = String(card.title || 'event').toLowerCase().normalize('NFKD').replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 40).replace(/-+$/g, ''); + return `${base || 'event'}-${card.id.replace(/[^a-z0-9]/gi, '').slice(0, 8).toLowerCase()}`; +} + +/** Host account granted admin access on every DataOps-created Q&A room. */ +export function hostAdminEmail(): string { + return (process.env.DATAQNA_HOST_ADMIN_EMAIL || 'alexey@datatalks.club').trim().toLowerCase(); +} + +/** Create the Card's Q&A room once; the room's idempotency key is the Card id, so retries return the same room. */ +export async function ensureCardQna(db: DynamoDBDocumentClient, card: Card): Promise { + if (card.qna) return card; + const room = await qna().createRoom({ + title: `${card.title || 'Event'} — live Q&A`, + slug: slugFor(card), + description: 'Ask your questions for the live event. Upvote the ones you want answered.', + idempotencyKey: `dataops-card-${card.id}`, + }); + const adminEmail = hostAdminEmail(); + if (adminEmail) await qna().addRoomAdmin(room.roomId, adminEmail); + const created: CardQna = { roomId: room.roomId, slug: room.slug, url: room.url, presentUrl: room.presentUrl, createdAt: new Date().toISOString() }; + return updateCardAdditive(db, card, (current) => ({ qna: current.qna ?? created })); +} + +/** Best-effort variant for card creation: a Q&A outage must never block the Card. */ +export async function ensureCardQnaQuietly(db: DynamoDBDocumentClient, card: Card): Promise { + try { + return await ensureCardQna(db, card); + } catch (error) { + console.warn(`Q&A room for Card ${card.id} was not created: ${(error as Error).message}`); + return card; + } +} + +/** Auto-create the Q&A room once an event Card has a date (`anchorDate`); never blocks the caller. */ +export async function ensureCardQnaForDatedEvent(db: DynamoDBDocumentClient, card: Card): Promise { + if (card.qna || !card.anchorDate || card.status === 'archived' || card.stage === 'done') return card; + if (!(await cardHasQnaEventType(db, card))) return card; + return ensureCardQnaQuietly(db, card); +} + +/** Close the room and keep every audience question on the Card. Idempotent: a saved Card is returned unchanged. */ +export async function closeCardQna(db: DynamoDBDocumentClient, card: Card): Promise { + const base = card.qna ? card : await ensureCardQna(db, card); + const current = base.qna!; + if (current.questionsSavedAt) return base; + await qna().closeRoom(current.roomId); + const questions = await qna().listQuestions(current.roomId); + const now = new Date().toISOString(); + return updateCardAdditive(db, base, (fresh) => ({ + qna: { ...(fresh.qna ?? current), closedAt: now, questionsSavedAt: now, questions }, + })); +} + +export interface CardQnaQuestions { + roomUrl: string; + presentUrl: string; + state: 'open' | 'closed'; + /** `live` while the room is open, `saved` once the Card holds the permanent copy. */ + source: 'live' | 'saved'; + savedAt: string | null; + questions: CardQnaQuestion[]; +} + +/** The stable read model behind the Card's live-questions preview. */ +export async function readCardQnaQuestions(card: Card): Promise { + const room = card.qna; + if (!room) return null; + if (room.questionsSavedAt) { + return { roomUrl: room.url, presentUrl: room.presentUrl, state: 'closed', source: 'saved', savedAt: room.questionsSavedAt, questions: room.questions ?? [] }; + } + const questions = await qna().listQuestions(room.roomId); + return { roomUrl: room.url, presentUrl: room.presentUrl, state: 'open', source: 'live', savedAt: null, questions }; +} + +export interface CardQnaAnnouncement { + qnaUrl: string; + registrationUrl: string | null; + text: string; +} + +/** Build the event announcement snippet with the Card's Q&A room link filled in automatically. */ +export function buildCardAnnouncement(card: Card): CardQnaAnnouncement | null { + const qnaUrl = card.qna?.url?.trim(); + if (!qnaUrl) return null; + const regLink = (card.cardLinks || []).find((link) => { + const name = String(link.name || '').trim().toLowerCase(); + return Boolean(link.url?.trim()) && (name === 'luma' || name === 'event page'); + }); + const registrationUrl = regLink?.url?.trim() || null; + const datePart = card.anchorDate ? ` on ${String(card.anchorDate).slice(0, 10)}` : ''; + const lines = [`Join us for ${card.title || 'our upcoming event'}${datePart}!`]; + if (registrationUrl) lines.push('', `Register here: ${registrationUrl}`); + lines.push(registrationUrl ? `Ask questions live: ${qnaUrl}` : `\nAsk questions live: ${qnaUrl}`); + return { qnaUrl, registrationUrl, text: lines.join('\n') }; +} + +export interface QnaBackfillResult { created: string[]; skipped: number; failed: Array<{ cardId: string; error: string }> } + +/** Give every upcoming dated event Card a Q&A room. */ +export async function backfillCardQna(db: DynamoDBDocumentClient, cards: Card[]): Promise { + const result: QnaBackfillResult = { created: [], skipped: 0, failed: [] }; + for (const card of cards) { + if ( + card.qna + || !card.anchorDate + || card.status === 'archived' + || card.stage === 'done' + || card.stage === 'after-event' + || !(await cardHasQnaEventType(db, card)) + ) { + result.skipped += 1; + continue; + } + try { + await ensureCardQna(db, card); + result.created.push(card.id); + } catch (error) { + result.failed.push({ cardId: card.id, error: (error as Error).message }); + } + } + return result; +} diff --git a/backend/src/routes/cardQna.ts b/backend/src/routes/cardQna.ts new file mode 100644 index 00000000..6db0ab4b --- /dev/null +++ b/backend/src/routes/cardQna.ts @@ -0,0 +1,53 @@ +import type { DynamoDBDocumentClient } from '@aws-sdk/lib-dynamodb'; +import { getCardConsistent, listAllCards } from '../db/cards'; +import { resolveInteractiveActor, workAdminForbidden } from '../identity/actor'; +import { backfillCardQna, buildCardAnnouncement, cardHasQnaEventType, closeCardQna, ensureCardQna, readCardQnaQuestions } from '../qna/service'; +import type { LambdaEvent, LambdaResponse } from '../types'; +import { JSON_HEADERS } from '../http'; + +const json = (statusCode: number, body: unknown): LambdaResponse => ({ statusCode, headers: JSON_HEADERS, body: JSON.stringify(body) }); + +/** + * Card Q&A routes (audience Q&A on qna.dtcdev.click): + * POST /api/cards/qna/backfill admin: give every upcoming dated event Card a room + * GET /api/cards/:id/qna/questions stable read model: live while open, saved copy once closed + * GET /api/cards/:id/qna/announcement announcement snippet with the Card's Q&A room link + * POST /api/cards/:id/qna create the Card's room (idempotent) + * POST /api/cards/:id/qna/close close the room and save every question on the Card + */ +export async function handleCardQnaRoute( + method: string, + suffix: string, + event: LambdaEvent, + client: DynamoDBDocumentClient, +): Promise { + const backfill = /^\/qna\/backfill\/?$/.test(suffix); + const match = suffix.match(/^\/([^/]+)\/qna(?:\/(questions|announcement|close))?\/?$/); + if (!backfill && !match) return null; + const read = method === 'GET'; + const resolved = await resolveInteractiveActor(client, event, read ? 'work-read' : 'work-write'); + if (!resolved.ok) return resolved.response; + const actor = resolved.actor; + + if (backfill) { + if (method !== 'POST') return json(405, { error: 'Method not allowed' }); + if (!actor.testBypass && !actor.isAdmin) return workAdminForbidden('Backfilling Q&A rooms requires an admin'); + return json(200, await backfillCardQna(client, await listAllCards(client))); + } + + const [, id, action] = match!; + const card = await getCardConsistent(client, id); + if (!card) return json(404, { error: 'Card not found' }); + if (action === 'questions' || action === 'announcement') { + if (!read) return json(405, { error: 'Method not allowed' }); + const body = action === 'announcement' ? buildCardAnnouncement(card) : await readCardQnaQuestions(card); + return body ? json(200, body) : json(404, { error: 'This Card has no Q&A room', code: 'qna_not_found' }); + } + if (method !== 'POST') return json(405, { error: 'Method not allowed' }); + if (!actor.testBypass && !actor.isAdmin && !(actor.id && card.ownerId === actor.id)) { + return workAdminForbidden('Managing the Q&A requires the Card owner or an admin'); + } + if (!(await cardHasQnaEventType(client, card))) return json(422, { error: 'Only podcast, webinar and workshop Cards have a Q&A', code: 'qna_not_event_card' }); + const updated = action === 'close' ? await closeCardQna(client, card) : await ensureCardQna(client, card); + return json(200, { qna: updated.qna }); +} diff --git a/backend/src/routes/cards.ts b/backend/src/routes/cards.ts index fa404c6e..58ec8135 100644 --- a/backend/src/routes/cards.ts +++ b/backend/src/routes/cards.ts @@ -28,6 +28,8 @@ import { import { attachLinkedCards, cardBackReferences } from '../cards/taskCardLinkView'; import { ensureEventSlotCards } from '../cards/eventSlots'; import { buildFormatAuditReport } from '../cards/formatAudit'; +import { ensureCardQnaForDatedEvent } from '../qna/service'; +import { handleCardQnaRoute } from './cardQna'; import { redateCardTemplateTasks } from '../cards/redateTemplateTasks'; import { CardDeletionBlockedError, @@ -369,6 +371,9 @@ async function handleCardRoutes( return await handleCollection(method, rawBody, client, event); } + const qnaResponse = await handleCardQnaRoute(method, suffix, event, client); + if (qnaResponse) return qnaResponse; + // Route: /api/cards/template-updates/:action const batchTemplateUpdateMatch = suffix.match(/^\/template-updates\/(preview|apply)\/?$/); if (batchTemplateUpdateMatch) { @@ -884,8 +889,9 @@ async function handleSingle( console.error('Standalone Markdown step sync after Card tagging failed:', failure); } } + const withQna = card.anchorDate && !card.qna ? await ensureCardQnaForDatedEvent(client, card) : card; const templateIdByType = await getTemplateIdByType(client); - return json(200, { card: await projectCard(new TeamDirectory(client), card, undefined, templateIdByType) }); + return json(200, { card: await projectCard(new TeamDirectory(client), withQna, undefined, templateIdByType) }); } if (method === 'DELETE') { @@ -1145,7 +1151,8 @@ async function handleCardTime(method: string, id: string, rawBody: string | null }) : null; const dated = await adoptEventDate(client, result.card, card.eventTime); - const projected = await projectCard(new TeamDirectory(client), dated.card, undefined, await getTemplateIdByType(client)); + const withQna = await ensureCardQnaForDatedEvent(client, dated.card); + const projected = await projectCard(new TeamDirectory(client), withQna, undefined, await getTemplateIdByType(client)); return json(result.sync.state === 'synced' ? 200 : 502, { ...result, card: projected, inviteCheck: verified.check, movedTasks: dated.movedTasks, ...(rescheduleTask ? { rescheduleTaskId: rescheduleTask.id } : {}), diff --git a/backend/src/routes/taskValidation.ts b/backend/src/routes/taskValidation.ts index c88781a2..d5dc57a0 100644 --- a/backend/src/routes/taskValidation.ts +++ b/backend/src/routes/taskValidation.ts @@ -1,5 +1,6 @@ import { DynamoDBDocumentClient } from '@aws-sdk/lib-dynamodb'; +import { closeCardQna } from '../qna/service'; import { getArtifact, listArtifacts } from '../db/artifacts'; import { getCard } from '../db/cards'; import { listTasksByCard } from '../db/tasks'; @@ -707,3 +708,25 @@ export async function validateDoneProofOnCreate(client: DynamoDBDocumentClient, return null; } + +/** Template task id of the post-event step 'Close Q&A and save all audience questions'. */ +export const CLOSE_QNA_TASK_REF = 'close-qna-save-questions'; + +/** + * Completing the close-Q&A step closes the Card's Q&A room and stores every + * audience question on the Card first; the Task closes only if that worked. + */ +export async function closeQnaOnDone( + client: DynamoDBDocumentClient, + taskData: Record, +): Promise { + if (taskData.templateTaskRef !== CLOSE_QNA_TASK_REF || !isNonEmptyString(taskData.cardId)) return null; + const card = await getCard(client, String(taskData.cardId).trim()); + if (!card) return null; + try { + await closeCardQna(client, card); + return null; + } catch (error) { + return `Cannot mark task as done: closing the Q&A and saving its questions failed (${(error as Error).message}). Retry.`; + } +} diff --git a/backend/src/routes/tasks.ts b/backend/src/routes/tasks.ts index b0333568..530f914b 100644 --- a/backend/src/routes/tasks.ts +++ b/backend/src/routes/tasks.ts @@ -74,6 +74,7 @@ import { validateActionChannel, validateActionNote, validateCalendarInviteRequirement, + closeQnaOnDone, validateLinkedCardRequirement, validateDateOrTimestampValue, validateDoneProof, @@ -1243,6 +1244,9 @@ export async function handleTaskRoutes( const proofError = await validateDoneProof(client, existing.id, existing, updates); if (proofError) return jsonResponse(400, { error: proofError }); + const qnaError = await closeQnaOnDone(client, taskData); + if (qnaError) return jsonResponse(502, { error: qnaError }); + updates.completedAt = now; if (actorId) updates.completedBy = actorId; const resolvedEvent = makeTaskHistoryEvent('wait-resolved', existing, { @@ -1524,6 +1528,11 @@ export async function handleTaskRoutes( return jsonResponse(400, { error: proofError }); } + if (existing.status !== 'done') { + const qnaError = await closeQnaOnDone(client, taskData); + if (qnaError) return jsonResponse(502, { error: qnaError }); + } + updates.completedAt = completedAt; const actorId = actor.id; if (actorId) updates.completedBy = actorId; diff --git a/backend/src/types.ts b/backend/src/types.ts index fbd488f2..2587ebec 100644 --- a/backend/src/types.ts +++ b/backend/src/types.ts @@ -395,6 +395,26 @@ export interface CardCalendarInvite { staleAt?: string; } +export interface CardQnaQuestion { + questionId: string; + text: string; + authorName: string | null; + status: string; + score: number; + pinned: boolean; + createdAt: string; + answeredAt: string | null; +} +export interface CardQna { + roomId: string; + slug: string; + url: string; + presentUrl: string; + createdAt: string; + closedAt?: string; + questionsSavedAt?: string; + questions?: CardQnaQuestion[]; +} export interface Card { guestIntake?: { jobId: string; taskId: string; status: import('./events/guestIntakeStore').GuestIntakeStatus; skipEmail: boolean; recipient?: string; messageId?: string; sentAt?: string; startIso?: string; error?: string }; id: string; @@ -460,6 +480,12 @@ export interface Card { status?: 'proposed' | 'approved' | 'released'; }; tags?: string[]; + /** + * The audience Q&A room of an event Card (podcast, webinar, workshop) on + * qna.dtcdev.click. `questions` is the permanent copy saved when the room + * was closed by the "Close Q&A and save all audience questions" step. + */ + qna?: CardQna; /** * Administrative owner of the Card. Optional: existing and system-created * Cards without an explicit owner are honestly unassigned and are never diff --git a/backend/tests/card-qna.test.ts b/backend/tests/card-qna.test.ts new file mode 100644 index 00000000..7c7d21af --- /dev/null +++ b/backend/tests/card-qna.test.ts @@ -0,0 +1,203 @@ +import { describe, it, before, after } from 'node:test'; +import assert from 'node:assert'; +import type { DynamoDBDocumentClient } from '@aws-sdk/lib-dynamodb'; + +import { getClient } from '../src/db/client'; +import { createTables, startLocal, stopLocal } from '../scripts/local-dynamodb'; +import { createTemplate } from '../src/db/templates'; +import { createUser } from '../src/db/users'; +import { humanBearer } from './helpers/human-bearer'; +import { setQnaClientForTests } from '../src/qna/service'; +import { createQnaClient, type QnaClient, type QnaQuestion } from '../src/qna/client'; +import type { LambdaResponse, Template } from '../src/types'; + +describe('Event card audience Q&A (qna.dtcdev.click)', () => { + let client: DynamoDBDocumentClient; + let handler: typeof import('../src/handler').handler; + let adminUserId: string; + let adminToken: string; + let podcast: Template; + let webinar: Template; + let workshop: Template; + let newsletter: Template; + let closeStep: Template; + const rooms = new Map(); + const questions: QnaQuestion[] = [ + { questionId: 'q1', text: 'What is dbt?', authorName: 'Maria', status: 'visible', score: 4, pinned: false, createdAt: '2026-12-01T18:00:00Z', answeredAt: null }, + { questionId: 'q2', text: 'Why Lambda?', authorName: null, status: 'answered', score: 1, pinned: false, createdAt: '2026-12-01T18:05:00Z', answeredAt: '2026-12-01T18:30:00Z' }, + ]; + let failClose = false; + const fake: QnaClient = { + async createRoom(input) { + for (const [id, r] of rooms) if (r.key === input.idempotencyKey) return { roomId: id, slug: r.slug, url: `https://qna.dtcdev.click/r/${r.slug}`, presentUrl: `https://qna.dtcdev.click/admin/rooms/${id}/present`, state: 'open' }; + const id = `room-${rooms.size + 1}`; + rooms.set(id, { slug: input.slug, state: 'open', key: input.idempotencyKey, admins: [] }); + return { roomId: id, slug: input.slug, url: `https://qna.dtcdev.click/r/${input.slug}`, presentUrl: `https://qna.dtcdev.click/admin/rooms/${id}/present`, state: 'open' }; + }, + async addRoomAdmin(roomId, email) { + const r = rooms.get(roomId)!; + if (!r.admins.includes(email)) r.admins.push(email); + }, + async closeRoom(roomId) { + if (failClose) throw new Error('Q&A service down'); + const r = rooms.get(roomId)!; + r.state = 'closed'; + return { roomId, slug: r.slug, url: '', presentUrl: '', state: 'closed' }; + }, + async listQuestions() { return questions; }, + }; + + before(async () => { + const port = await startLocal(); + client = await getClient(port); + await createTables(client); + process.env.IS_LOCAL = 'true'; + handler = (await import('../src/handler')).handler; + const user = await createUser(client, { email: 'qna-admin@datatalks.club', name: 'Qna Admin', passwordHash: 'unused', role: 'admin' }); + adminUserId = user.id; + adminToken = await humanBearer(client, adminUserId); + setQnaClientForTests(fake); + const tasks = [{ refId: 'run', description: 'Run the event', offsetDays: 0 }]; + const make = (name: string, type: string, taskDefinitions: any[] = tasks) => createTemplate(client, { name, type, origin: 'git', sourcePath: `workflow-templates/${type}.yaml`, sourceRevision: `sha-${type}`, triggerType: 'manual', taskDefinitions }); + podcast = await make('Podcast', 'podcast'); + webinar = await make('Webinar', 'webinar'); + workshop = await make('Workshop', 'workshop'); + newsletter = await make('Newsletter', 'newsletter'); + closeStep = await make('Webinar close', 'webinar', [{ refId: 'close-qna-save-questions', description: 'Close Q&A and save all audience questions', offsetDays: 1 }]); + }); + + after(async () => { + setQnaClientForTests(null); + await stopLocal(); + delete process.env.IS_LOCAL; + }); + + function req(method: string, path: string, body?: unknown) { + return handler({ + httpMethod: method, path, + headers: { authorization: `Bearer ${adminToken}`, 'x-user-id': adminUserId, host: 'ops.dtcdev.click', 'x-forwarded-proto': 'https' }, + queryStringParameters: null, + body: body === undefined ? null : JSON.stringify(body), + }, {}) as Promise; + } + const payload = (r: LambdaResponse): any => JSON.parse(r.body); + const newCard = (templateId: string, title: string) => req('POST', '/api/cards', { templateId, title, anchorDate: '2026-12-01' }); + + it('creates one Q&A room per podcast, webinar and workshop Card, grants host admin, and fills announcement', async () => { + for (const [tpl, title] of [[podcast, 'Podcast One'], [webinar, 'Webinar One'], [workshop, 'Workshop One']] as const) { + const res = await newCard(tpl.id, title); + assert.strictEqual(res.statusCode, 201); + const card = payload(res).card ?? payload(res); + assert.match(card.qna.url, /^https:\/\/qna\.dtcdev\.click\/r\//); + assert.deepStrictEqual(rooms.get(card.qna.roomId)?.admins, ['alexey@datatalks.club']); + const read = payload(await req('GET', `/api/cards/${card.id}`)).card ?? payload(await req('GET', `/api/cards/${card.id}`)); + assert.strictEqual(read.qna.url, card.qna.url); + const ann = payload(await req('GET', `/api/cards/${card.id}/qna/announcement`)); + assert.strictEqual(ann.qnaUrl, card.qna.url); + assert.ok(ann.text.includes(card.qna.url)); + } + }); + + it('waits until an undated event Card gets a date before creating its Q&A room', async () => { + const { createCardFromInput } = await import('../src/cards/createCard'); + const undated = await createCardFromInput( + client, + { id: adminUserId, isAdmin: true, testBypass: false }, + { templateId: podcast.id, title: 'Undated Podcast' }, + { provisionalAnchorDate: '2026-12-20' }, + ); + assert.strictEqual(undated.ok, true, !undated.ok ? undated.response.body : ''); + if (!undated.ok) return; + assert.strictEqual(undated.card.anchorDate, undefined); + assert.strictEqual(undated.card.qna, undefined); + + const datedRes = await req('PUT', `/api/cards/${undated.card.id}`, { + anchorDate: '2026-12-20', + expectedVersion: undated.card.version, + }); + assert.strictEqual(datedRes.statusCode, 200, datedRes.body); + const dated = payload(datedRes).card ?? payload(datedRes); + assert.match(dated.qna.url, /^https:\/\/qna\.dtcdev\.click\/r\//); + assert.deepStrictEqual(rooms.get(dated.qna.roomId)?.admins, ['alexey@datatalks.club']); + }); + + it('gives other formats no room', async () => { + const res = await newCard(newsletter.id, 'Newsletter One'); + assert.strictEqual(res.statusCode, 201); + assert.strictEqual((payload(res).card ?? payload(res)).qna, undefined); + }); + + it('keeps card creation working when the Q&A service is down', async () => { + setQnaClientForTests({ ...fake, createRoom: async () => { throw new Error('down'); } }); + const res = await newCard(webinar.id, 'Webinar Outage'); + assert.strictEqual(res.statusCode, 201); + const card = payload(res).card ?? payload(res); + assert.strictEqual(card.qna, undefined); + setQnaClientForTests(fake); + const ensured = await req('POST', `/api/cards/${card.id}/qna`); + assert.strictEqual(ensured.statusCode, 200); + assert.ok(payload(ensured).qna.url); + const again = await req('POST', `/api/cards/${card.id}/qna`); + assert.strictEqual(payload(again).qna.roomId, payload(ensured).qna.roomId); + }); + + it('serves the live questions, then the saved copy after the close step', async () => { + const created = payload(await newCard(closeStep.id, 'Webinar Close')); + const c = created.card ?? created; + const live = payload(await req('GET', `/api/cards/${c.id}/qna/questions`)); + assert.strictEqual(live.source, 'live'); + assert.strictEqual(live.state, 'open'); + assert.strictEqual(live.questions.length, 2); + + const tasks = payload(await req('GET', `/api/cards/${c.id}/tasks`)); + const task = (tasks.tasks ?? tasks).find((t: any) => t.templateTaskRef === 'close-qna-save-questions'); + assert.ok(task, 'close step task exists'); + + failClose = true; + const failed = await req('PUT', `/api/tasks/${task.id}`, { status: 'done', expectedVersion: task.version }); + assert.strictEqual(failed.statusCode, 502); + failClose = false; + + const done = await req('PUT', `/api/tasks/${task.id}`, { status: 'done', expectedVersion: task.version }); + assert.strictEqual(done.statusCode, 200, done.body); + const after = payload(await req('GET', `/api/cards/${c.id}`)); + const stored = (after.card ?? after).qna; + assert.ok(stored.closedAt && stored.questionsSavedAt); + assert.strictEqual(stored.questions.length, 2); + const saved = payload(await req('GET', `/api/cards/${c.id}/qna/questions`)); + assert.strictEqual(saved.source, 'saved'); + assert.strictEqual(saved.state, 'closed'); + assert.strictEqual(saved.questions[0].text, 'What is dbt?'); + }); + + it('backfills only event Cards that have no room', async () => { + setQnaClientForTests({ ...fake, createRoom: async () => { throw new Error('down'); } }); + const a = payload(await newCard(podcast.id, 'Podcast Backfill')); + setQnaClientForTests(fake); + const result = payload(await req('POST', '/api/cards/qna/backfill')); + assert.ok(result.created.includes((a.card ?? a).id)); + assert.deepStrictEqual(result.failed, []); + const second = payload(await req('POST', '/api/cards/qna/backfill')); + assert.deepStrictEqual(second.created, []); + }); + + it('the real client speaks the DataQnA API without leaking the key', async () => { + const seen: Array<{ url: string; init: any }> = []; + const http = createQnaClient(async (url: any, init: any) => { + seen.push({ url: String(url), init }); + const body = String(url).includes('/questions') + ? { items: [{ question_id: 'a', text: 't', author_name: 'M', anonymous: true, status: 'visible', score: 2, pinned: false, created_at: 'x' }], next_cursor: null } + : { room_id: 'r1', slug: 's', url: 'https://qna.dtcdev.click/r/s', present_url: 'p', state: 'open' }; + return new Response(JSON.stringify(body), { status: 200 }); + }, async () => 'dq_secret'); + const room = await http.createRoom({ title: 'T', slug: 's', description: 'd', idempotencyKey: 'k' }); + assert.strictEqual(room.url, 'https://qna.dtcdev.click/r/s'); + await http.addRoomAdmin('r1', 'alexey@datatalks.club'); + const qs = await http.listQuestions('r1'); + assert.strictEqual(qs[0].authorName, null); + assert.strictEqual(seen[0].init.headers.authorization, 'Bearer dq_secret'); + assert.ok(seen[0].url.startsWith('https://qna.dtcdev.click/api/v1/rooms')); + assert.strictEqual(seen[1].url, 'https://qna.dtcdev.click/api/v1/rooms/r1/admins'); + assert.strictEqual(seen[1].init.body, JSON.stringify({ email: 'alexey@datatalks.club' })); + }); +}); diff --git a/cli/src/commands/cards.mjs b/cli/src/commands/cards.mjs index 605bb5c7..5783f9e5 100644 --- a/cli/src/commands/cards.mjs +++ b/cli/src/commands/cards.mjs @@ -181,6 +181,8 @@ export async function show(args, io) { ["sponsored", card.sponsored === true ? "yes" : undefined], ["source docs", card.sourceDocIds], ["version", card.version], + ["Q&A link", card.qna?.url], + ["Q&A questions", card.qna?.questionsSavedAt ? `${card.qna.questions?.length ?? 0} saved ${card.qna.questionsSavedAt}` : card.qna ? "room open" : undefined], ]); for (const link of card.cardLinks || []) { io.print(`link: ${link.name || link.label} = ${link.url || "(not filled)"}`); diff --git a/frontend/src/surfaces/work-detail/card-panel.js b/frontend/src/surfaces/work-detail/card-panel.js index 49c8e435..2286eaaa 100644 --- a/frontend/src/surfaces/work-detail/card-panel.js +++ b/frontend/src/surfaces/work-detail/card-panel.js @@ -24,6 +24,7 @@ import { renderCardGuestInvitation, renderCardTemplateLink, } from "./card-summary.js"; +import { renderCardQna } from "./card-qna.js"; import { renderCardEventTime, renderCardInvitesSection } from "./card-invites.js"; import { renderWebinarMaterialsAction } from "./webinar-materials.js"; import { renderCardReferencesSection } from "./card-references.js"; @@ -405,6 +406,8 @@ export function createCardPanel(context) { main.append(meta); const invitation = renderCardGuestInvitation({ request, workApiUrl, reload: reloadCardIntent }, card); if (invitation) main.append(invitation); + const qnaSection = renderCardQna({ request, workApiUrl }, card); + if (qnaSection) main.append(qnaSection); main.append(renderCardNewsletterIssue({ request, workApiUrl, reload: reloadCardIntent }, card)); const materialsAction = renderWebinarMaterialsAction({ request, workApiUrl, reload: reloadCardIntent }, card, state.workSnapshot.templates); if (materialsAction) main.append(materialsAction); diff --git a/frontend/src/surfaces/work-detail/card-qna.js b/frontend/src/surfaces/work-detail/card-qna.js new file mode 100644 index 00000000..a9c11d42 --- /dev/null +++ b/frontend/src/surfaces/work-detail/card-qna.js @@ -0,0 +1,107 @@ +import { opensInNewTab } from "../../core/links.js"; + +// The audience Q&A of an event Card (podcast, webinar, workshop): the public +// room link, the presenter view, and the audience questions — live while the +// room is open, the saved copy once the "Close Q&A and save all audience +// questions" step has run. Cards without a room render nothing. +function linkRow(label, href) { + const row = document.createElement("p"); + row.append(`${label}: `); + const link = document.createElement("a"); + link.href = href; + link.textContent = href; + opensInNewTab(link); + row.append(link); + return row; +} + +export function buildCardQnaAnnouncement(card) { + const qnaUrl = card?.qna?.url?.trim(); + if (!qnaUrl) return ""; + const regLink = (card.cardLinks || []).find((link) => { + const name = String(link?.name || "").trim().toLowerCase(); + return Boolean(link?.url?.trim()) && (name === "luma" || name === "event page"); + }); + const datePart = card.anchorDate ? ` on ${String(card.anchorDate).slice(0, 10)}` : ""; + const lines = [`Join us for ${card.title || "our upcoming event"}${datePart}!`]; + if (regLink?.url?.trim()) lines.push("", `Register here: ${regLink.url.trim()}`); + lines.push(regLink?.url?.trim() ? `Ask questions live: ${qnaUrl}` : `\nAsk questions live: ${qnaUrl}`); + return lines.join("\n"); +} + +export function renderCardQna({ request, workApiUrl }, card) { + const qna = card?.qna; + if (!qna?.url) return null; + const section = document.createElement("section"); + section.className = "workflow-detail-section card-qna"; + section.dataset.cardQna = ""; + const heading = document.createElement("strong"); + heading.textContent = qna.questionsSavedAt ? "Audience Q&A (closed, questions saved)" : "Audience Q&A"; + section.append(heading, linkRow("Audience link", qna.url)); + if (qna.presentUrl && !qna.questionsSavedAt) section.append(linkRow("Presenter view", qna.presentUrl)); + + const toggle = document.createElement("button"); + toggle.type = "button"; + toggle.className = "btn btn-secondary"; + toggle.dataset.cardQnaQuestions = ""; + const label = qna.questionsSavedAt && qna.questions ? `Show saved questions (${qna.questions.length})` : "Show audience questions"; + toggle.textContent = label; + const list = document.createElement("ol"); + list.className = "card-qna__questions"; + list.hidden = true; + const status = document.createElement("p"); + status.hidden = true; + toggle.addEventListener("click", async () => { + if (!list.hidden) { + list.hidden = true; + toggle.textContent = label; + return; + } + toggle.disabled = true; + try { + const data = await request(workApiUrl(`/api/cards/${encodeURIComponent(card.id)}/qna/questions`)); + list.replaceChildren(...data.questions.map((question) => { + const item = document.createElement("li"); + const score = question.score > 1 ? ` (+${question.score})` : ""; + const answered = question.status === "answered" ? " ✓ answered" : ""; + item.textContent = `${question.text} — ${question.authorName || "Anonymous"}${score}${answered}`; + return item; + })); + status.hidden = data.questions.length > 0; + status.textContent = data.questions.length ? "" : "No questions yet."; + list.hidden = false; + toggle.textContent = "Hide audience questions"; + } catch (error) { + status.hidden = false; + status.textContent = `Could not load questions: ${error?.message || error}`; + } finally { + toggle.disabled = false; + } + }); + section.append(toggle, status, list); + const announcementText = buildCardQnaAnnouncement(card); + if (announcementText && !qna.questionsSavedAt) { + const details = document.createElement("details"); + details.className = "card-qna__announcement"; + details.dataset.cardQnaAnnouncement = ""; + const summary = document.createElement("summary"); + summary.textContent = "Announcement with Q&A link"; + const pre = document.createElement("pre"); + pre.textContent = announcementText; + const copy = document.createElement("button"); + copy.type = "button"; + copy.className = "btn btn-secondary"; + copy.textContent = "Copy announcement"; + copy.addEventListener("click", async () => { + try { + await globalThis.navigator?.clipboard?.writeText(announcementText); + copy.textContent = "Copied"; + } catch { + copy.textContent = "Copy failed"; + } + }); + details.append(summary, pre, copy); + section.append(details); + } + return section; +} diff --git a/frontend/test/card-qna.test.mjs b/frontend/test/card-qna.test.mjs new file mode 100644 index 00000000..45da6def --- /dev/null +++ b/frontend/test/card-qna.test.mjs @@ -0,0 +1,33 @@ +import assert from "node:assert/strict"; +import { afterEach, test } from "node:test"; +import { renderCardQna } from "../src/surfaces/work-detail/card-qna.js"; +import { FakeDocument, FakeElement } from "./support/fake-dom.mjs"; +const savedDocument = globalThis.document; +afterEach(() => { globalThis.document = savedDocument; }); + +test("a Card without a Q&A room renders nothing", () => { + globalThis.document = new FakeDocument(new FakeElement("main")); + assert.equal(renderCardQna({ request: async () => ({}), workApiUrl: (p) => p }, { id: "c1" }), null); +}); + +test("a Card with a room shows its link and loads questions on one click", async () => { + globalThis.document = new FakeDocument(new FakeElement("main")); + const calls = []; + const card = { + id: "c1", + title: "Live Data Podcast", + anchorDate: "2026-12-01", + cardLinks: [{ name: "Luma", url: "https://luma.com/abc" }], + qna: { url: "https://qna.dtcdev.click/r/x", presentUrl: "https://qna.dtcdev.click/admin/rooms/1/present" }, + }; + const section = renderCardQna({ + request: async (url) => { calls.push(url); return { questions: [{ text: "Why?", authorName: null, score: 3, status: "visible" }] }; }, + workApiUrl: (p) => p, + }, card); + assert.ok(section.textContent.includes("https://qna.dtcdev.click/r/x")); + assert.ok(section.textContent.includes("Register here: https://luma.com/abc")); + assert.ok(section.textContent.includes("Ask questions live: https://qna.dtcdev.click/r/x")); + await section.querySelector("button").click(); + assert.deepEqual(calls, ["/api/cards/c1/qna/questions"]); + assert.ok(section.textContent.includes("Why? — Anonymous (+3)")); +});