Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions backend/src/calendar/linkConfirmedHold.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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 };
}
7 changes: 6 additions & 1 deletion backend/src/cards/createCard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -369,7 +370,11 @@ export async function createCardFromInput(
body.counts as Record<string, number> | 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 {
Expand Down
1 change: 1 addition & 0 deletions backend/src/docs/frontend-assets.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
113 changes: 113 additions & 0 deletions backend/src/qna/client.ts
Original file line number Diff line number Diff line change
@@ -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 `<stack>.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<QnaRoom>;
addRoomAdmin(roomId: string, email: string): Promise<void>;
closeRoom(roomId: string): Promise<QnaRoom>;
listQuestions(roomId: string): Promise<QnaQuestion[]>;
}

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<string, unknown>): 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<string, unknown>): 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<string> = () => readRuntimeSecret(secretName()),
): QnaClient {
async function call(method: string, path: string, body?: unknown): Promise<Record<string, unknown>> {
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<string, unknown> = {};
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<string, unknown>[]) || []) items.push(toQuestion(item));
cursor = typeof page.next_cursor === 'string' && page.next_cursor ? page.next_cursor : null;
} while (cursor);
return items;
},
};
}
150 changes: 150 additions & 0 deletions backend/src/qna/service.ts
Original file line number Diff line number Diff line change
@@ -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<boolean> {
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<Card> {
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<Card> {
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<Card> {
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<Card> {
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<CardQnaQuestions | null> {
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<QnaBackfillResult> {
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;
}
53 changes: 53 additions & 0 deletions backend/src/routes/cardQna.ts
Original file line number Diff line number Diff line change
@@ -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<LambdaResponse | null> {
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 });
}
Loading