From 4a41cb7caee4f598bc2d19e0cff6ace687db2e3a Mon Sep 17 00:00:00 2001 From: Alexey Grigorev Date: Mon, 23 Nov 2026 13:06:57 +0100 Subject: [PATCH 01/12] Newsletter issue blocks: editable copy of Relay blocks, revisions, three-way Relay sync --- backend/src/newsletter/blocks.ts | 365 ++++++++++++++++++++++ backend/src/newsletter/blocksRelay.ts | 144 +++++++++ backend/src/newsletter/blocksStore.ts | 163 ++++++++++ backend/src/newsletter/blocksSync.ts | 383 ++++++++++++++++++++++++ backend/src/routes/newsletterBlocks.ts | 122 ++++++++ backend/src/routes/newsletterIssues.ts | 8 + backend/tests/newsletter-blocks.test.ts | 324 ++++++++++++++++++++ 7 files changed, 1509 insertions(+) create mode 100644 backend/src/newsletter/blocks.ts create mode 100644 backend/src/newsletter/blocksRelay.ts create mode 100644 backend/src/newsletter/blocksStore.ts create mode 100644 backend/src/newsletter/blocksSync.ts create mode 100644 backend/src/routes/newsletterBlocks.ts create mode 100644 backend/tests/newsletter-blocks.test.ts diff --git a/backend/src/newsletter/blocks.ts b/backend/src/newsletter/blocks.ts new file mode 100644 index 00000000..30d034f9 --- /dev/null +++ b/backend/src/newsletter/blocks.ts @@ -0,0 +1,365 @@ +/** + * Newsletter content blocks: the editable pieces of one issue (intro, sponsor, + * event spotlight, course updates, events list, recording, article...). + * + * Relay renders and sends the newsletter from its own blocks. DataOps keeps an + * editable copy of the same blocks so staff can edit every block here, with a + * revision history per edit, and syncs it with Relay both ways. Neither side is + * overwritten blindly: each block remembers the content both sides last agreed + * on (its sync base), and a sync is a three-way merge against that base: + * + * changed only here -> push to Relay + * changed only in Relay -> pull into DataOps + * changed on both sides -> conflict; the whole sync stops before any write + * + * Block field names, kinds and limits mirror Relay's + * `mailing.services.newsletters.BLOCK_TYPES`, so content that saves here also + * saves in Relay (whose block update is strict). + */ +import { createHash } from 'crypto'; + +export type BlockFieldKind = 'text' | 'url' | 'markdown' | 'lines' | 'html'; + +export const FIELD_KINDS: Record = { + kicker: 'text', + title: 'text', + meta: 'text', + image_url: 'url', + image_link: 'url', + body: 'markdown', + bullets: 'lines', + closing: 'markdown', + cta_text: 'text', + cta_url: 'url', + issue_label: 'text', + summary: 'markdown', + events: 'lines', + links: 'lines', + footer: 'markdown', + html: 'html', +}; + +export const FIELD_LABELS: Record = { + kicker: 'Section label ("-" for none)', + title: 'Title', + meta: 'Date / details line', + image_url: 'Image URL', + image_link: 'Image link', + body: 'Text (Markdown)', + bullets: 'Bullet points (one per line)', + closing: 'Closing text (Markdown)', + cta_text: 'Button text', + cta_url: 'Button link', + issue_label: 'Issue label', + summary: 'This week (Markdown)', + events: 'Events (one per line: when · type | title | https://link | with Speaker)', + links: 'Links (one per line: title | https://link | optional note)', + footer: 'Text under the list (Markdown)', + html: 'HTML', +}; + +export const MAX_LENGTHS: Record = { + text: 500, + url: 2000, + markdown: 20_000, + lines: 20_000, + html: 100_000, +}; + +const CARD_FIELDS = ['kicker', 'title', 'meta', 'image_url', 'image_link', 'body', 'bullets', 'closing', 'cta_text', 'cta_url']; + +export interface BlockTypeSpec { + label: string; + fields: string[]; + required: string[]; + defaults: Record; +} + +const card = (label: string, kicker = '', required: string[] = ['title']): BlockTypeSpec => ({ + label, + fields: CARD_FIELDS, + required, + defaults: kicker ? { kicker } : {}, +}); + +export const BLOCK_TYPES: Record = { + intro: { label: 'Intro', fields: ['issue_label', 'summary'], required: ['summary'], defaults: {} }, + sponsor: card('Sponsor (main)', 'SPONSORED', ['title', 'cta_text', 'cta_url']), + sponsor_secondary: card('Sponsor (secondary)', 'SPONSORED', ['title', 'cta_url']), + course_promo: card('Course promo', '', ['title', 'cta_text', 'cta_url']), + own_promo: card('Own promo', '', ['title']), + course_update: card('Course update'), + event_spotlight: card('Event spotlight', 'EVENT', ['title', 'cta_url']), + events_list: { + label: 'Upcoming events list', + fields: ['kicker', 'title', 'events', 'footer'], + required: ['events'], + defaults: { kicker: 'EVENTS', title: 'Upcoming Events' }, + }, + recording: card('Recording', 'RECORDINGS'), + podcast_episode: card('Podcast episode', 'PODCAST'), + alexey_article: card('Article (Alexey on Data)', 'READ'), + book_of_week: card('Book of the week', 'BOOK OF THE WEEK'), + feature: card('Feature'), + link_list: { label: 'Link list', fields: ['kicker', 'title', 'links'], required: ['links'], defaults: {} }, + html: { label: 'Custom HTML', fields: ['html'], required: ['html'], defaults: {} }, +}; + +export type BlockData = Record; + +export class BlockValidationError extends Error { + constructor(public readonly errors: Record) { + super(`Invalid block content: ${Object.entries(errors).map(([k, v]) => `${k} ${v}`).join(', ')}`); + } +} + +function validUrl(value: string): boolean { + try { + const parsed = new URL(value); + return ( + (parsed.protocol === 'http:' || parsed.protocol === 'https:') + && Boolean(parsed.hostname) + && !parsed.username + && !parsed.password + && ![...value].some((c) => c.charCodeAt(0) < 33) + ); + } catch { + return false; + } +} + +const lines = (value: string) => value.split(/\r?\n/).map((line) => line.trim()).filter(Boolean); + +/** + * Clean `data` for `type` the way Relay's strict update does (trim, drop empty + * fields, reject unknown fields, bad URLs, over-long values and missing required + * fields). Returns the cleaned data or throws BlockValidationError. + */ +export function validateBlockData(type: string, data: unknown, { draft = false } = {}): BlockData { + const spec = BLOCK_TYPES[type]; + if (!spec) throw new BlockValidationError({ type: 'unknown_block_type' }); + if (!data || typeof data !== 'object' || Array.isArray(data)) throw new BlockValidationError({ data: 'must_be_object' }); + const input = data as Record; + const errors: Record = {}; + for (const name of Object.keys(input)) { + if (!spec.fields.includes(name)) errors[`data.${name}`] = 'unknown_field'; + } + const cleaned: BlockData = {}; + for (const name of spec.fields) { + const kind = FIELD_KINDS[name]; + let value = input[name] ?? ''; + if (typeof value !== 'string') { + errors[`data.${name}`] = 'must_be_string'; + continue; + } + if (kind !== 'html') value = value.trim(); + const text = value as string; + if (text.length > MAX_LENGTHS[kind]) { + errors[`data.${name}`] = 'too_long'; + continue; + } + if (kind === 'url' && text && !validUrl(text)) { + errors[`data.${name}`] = 'invalid_url'; + continue; + } + if (!draft && spec.required.includes(name) && !text && !spec.defaults[name]) { + errors[`data.${name}`] = 'required'; + continue; + } + if (name === 'events') { + lines(text).forEach((line, index) => { + const parts = line.split('|').map((part) => part.trim()); + if (parts.length > 2 && parts[2] && !validUrl(parts[2])) errors[`data.events.${index}`] = 'invalid_url'; + }); + } + if (name === 'links') { + lines(text).forEach((line, index) => { + const parts = line.split('|').map((part) => part.trim()); + if (parts.length < 2 || !validUrl(parts[1])) errors[`data.links.${index}`] = 'invalid_url'; + }); + } + if (text) cleaned[name] = text; + } + if (Object.keys(errors).length) throw new BlockValidationError(errors); + return cleaned; +} + +/** Comparable form of a block's content: type plus non-empty fields in key order. */ +export function canonicalBlock(type: string, data: Record | null | undefined): string { + const entries = Object.entries(data || {}) + .filter(([, value]) => typeof value === 'string' && value !== '') + .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)); + return JSON.stringify([type, entries]); +} + +export function blockHash(type: string, data: Record | null | undefined): string { + return createHash('sha256').update(canonicalBlock(type, data)).digest('hex').slice(0, 32); +} + +export function blockLabel(type: string): string { + return BLOCK_TYPES[type]?.label || type; +} + +// ---------------------------------------------------------------- stored shape + +export type RelayTarget = 'production' | 'dev'; +export const RELAY_TARGETS: RelayTarget[] = ['production', 'dev']; + +/** What both sides last agreed on for one block. */ +export interface BlockSyncBase { + hash: string; + relayUpdatedAt: string; + syncedAt: string; +} + +export interface IssueBlock { + /** Stable DataOps id of the block (`rb-` for blocks that came from Relay). */ + id: string; + relayBlockId: number; + position: number; + type: string; + data: BlockData; + /** Bumped on every change to this block (edit or pull). */ + version: number; + updatedAt: string; + updatedBy: string; + updatedByName: string | null; + base: BlockSyncBase; +} + +export interface IssueBlockSet { + issueId: string; + relay: { target: RelayTarget; issueKey: string }; + /** Issue-level fields as last read from Relay (shown, not edited here). */ + relayIssue: { subject: string; previewText: string; campaignStatus: string | null; updatedAt: string }; + blocks: IssueBlock[]; + version: number; + lastSync: { at: string; byName: string | null; summary: string } | null; + createdAt: string; + updatedAt: string; +} + +// ---------------------------------------------------------------- Relay payload + +export interface RelayBlock { + id: number; + position: number; + type: string; + data: Record; + needs_review?: boolean; + updated_by?: string; + updated_at: string; +} + +export interface RelayIssue { + key: string; + subject: string; + preview_text?: string; + issue_number?: number | null; + campaign?: { status?: string } | null; + updated_at: string; + blocks: RelayBlock[]; +} + +// ---------------------------------------------------------------- three-way plan + +export type SyncAction = 'in_sync' | 'push' | 'pull' | 'add' | 'remove' | 'conflict'; + +export interface SyncStep { + action: SyncAction; + blockId: string | null; + relayBlockId: number; + type: string; + reason: string; +} + +export interface SyncPlan { + steps: SyncStep[]; + conflicts: SyncStep[]; + pushes: SyncStep[]; + pulls: SyncStep[]; +} + +/** + * Compare each block against its sync base. Never decides a winner when both + * sides changed: that is a conflict, and executing a plan with conflicts is + * refused as a whole. + */ +export function planSync(blocks: IssueBlock[], relay: RelayIssue): SyncPlan { + const steps: SyncStep[] = []; + const relayById = new Map(relay.blocks.map((block) => [block.id, block])); + const seen = new Set(); + for (const local of blocks) { + const remote = relayById.get(local.relayBlockId); + const localHash = blockHash(local.type, local.data); + const localChanged = localHash !== local.base.hash; + const common = { blockId: local.id, relayBlockId: local.relayBlockId, type: local.type }; + if (!remote) { + steps.push( + localChanged + ? { ...common, action: 'conflict', reason: 'deleted in Relay but edited in DataOps' } + : { ...common, action: 'remove', reason: 'deleted in Relay' }, + ); + continue; + } + seen.add(remote.id); + const remoteHash = blockHash(remote.type, remote.data); + const remoteChanged = remoteHash !== local.base.hash; + if (localHash === remoteHash) { + steps.push({ ...common, action: 'in_sync', reason: localChanged ? 'both sides made the same change' : 'unchanged' }); + } else if (localChanged && remoteChanged) { + steps.push({ + ...common, + action: 'conflict', + reason: `edited in DataOps and in Relay (Relay: ${remote.updated_by || 'unknown'} at ${remote.updated_at})`, + }); + } else if (localChanged) { + steps.push({ ...common, action: 'push', reason: 'edited in DataOps' }); + } else { + steps.push({ ...common, action: 'pull', reason: `edited in Relay by ${remote.updated_by || 'unknown'}` }); + } + } + for (const remote of relay.blocks) { + if (seen.has(remote.id)) continue; + steps.push({ action: 'add', blockId: null, relayBlockId: remote.id, type: remote.type, reason: 'new in Relay' }); + } + return { + steps, + conflicts: steps.filter((step) => step.action === 'conflict'), + pushes: steps.filter((step) => step.action === 'push'), + pulls: steps.filter((step) => step.action === 'pull' || step.action === 'add' || step.action === 'remove'), + }; +} + +export const localBlockId = (relayBlockId: number) => `rb-${relayBlockId}`; + +/** A local block that mirrors `remote` exactly, with the sync base set to it. */ +export function blockFromRelay(remote: RelayBlock, now: string, actor: { id: string; name: string | null }, version = 1): IssueBlock { + return { + id: localBlockId(remote.id), + relayBlockId: remote.id, + position: remote.position, + type: remote.type, + data: { ...(remote.data || {}) }, + version, + updatedAt: now, + updatedBy: actor.id, + updatedByName: actor.name, + base: { hash: blockHash(remote.type, remote.data), relayUpdatedAt: remote.updated_at, syncedAt: now }, + }; +} + +// ---------------------------------------------------------------- diffs + +export interface FieldChange { + field: string; + before: string; + after: string; +} + +export function changedFields(before: BlockData | null, after: BlockData | null): FieldChange[] { + const keys = [...new Set([...Object.keys(before || {}), ...Object.keys(after || {})])].sort(); + return keys + .map((field) => ({ field, before: before?.[field] ?? '', after: after?.[field] ?? '' })) + .filter((change) => change.before !== change.after); +} diff --git a/backend/src/newsletter/blocksRelay.ts b/backend/src/newsletter/blocksRelay.ts new file mode 100644 index 00000000..a607d854 --- /dev/null +++ b/backend/src/newsletter/blocksRelay.ts @@ -0,0 +1,144 @@ +/** + * Relay newsletter-issue API client for block sync. + * + * Two fixed targets, each with its own runtime secret, so a synced issue can + * only talk to the Relay it was linked to. Every call has a timeout and every + * failure throws a RelayError naming the call; nothing is retried silently. + * The API key is only ever sent as a header, never logged or returned. + */ +import { readRuntimeSecret } from '../secrets/reader'; +import type { RelayBlock, RelayIssue, RelayTarget } from './blocks'; + +export const RELAY_TARGET_CONFIG: Record = { + production: { url: 'https://relay.datatalks.club', secret: 'relay-production.dtc-newsletter-api-key' }, + // The dev secret's value is a JSON object of keys; the API key is RELAY_API_KEY. + dev: { url: 'https://dev.relay.datatalks.club', secret: 'relay-dev.api-keys', secretField: 'RELAY_API_KEY' }, +}; + +export const RELAY_TIMEOUT_MS = 15_000; +/** Relay sits behind CloudFront, whose WAF rejects bodies over ~8 KB with a bare 403. */ +export const MAX_RELAY_BODY_BYTES = 7000; + +export class RelayError extends Error { + constructor(message: string, public readonly status = 502, public readonly code = 'relay_error') { + super(message); + } +} + +export interface RelayDeps { + fetchImpl: typeof fetch; + readSecret: (name: string) => Promise; +} + +const deps: RelayDeps = { fetchImpl: (...args) => globalThis.fetch(...args), readSecret: readRuntimeSecret }; + +/** Tests swap the network and the secret store; returns a restore function. */ +export function setRelayDepsForTests(next: Partial): () => void { + const previous = { ...deps }; + Object.assign(deps, next); + return () => Object.assign(deps, previous); +} + +async function relayKey(target: RelayTarget): Promise { + const config = RELAY_TARGET_CONFIG[target]; + let raw: string; + try { + raw = await deps.readSecret(config.secret); + } catch (error) { + throw new RelayError( + `Relay ${target} API key unavailable: DataOps secret ${config.secret} could not be read (${(error as Error).message}).`, + 503, + 'relay_credentials_missing', + ); + } + let key = raw.trim(); + if (config.secretField) { + try { + key = String((JSON.parse(raw) as Record)[config.secretField] || '').trim(); + } catch { + key = ''; + } + } + if (!key) { + throw new RelayError(`DataOps secret ${config.secret} has no Relay API key.`, 503, 'relay_credentials_missing'); + } + return key; +} + +export interface RelayClient { + target: RelayTarget; + url: string; + getIssue(issueKey: string): Promise; + getBlock(issueKey: string, blockId: number): Promise; + putBlock(issueKey: string, blockId: number, type: string, data: Record): Promise; +} + +export function relayBodyBytes(type: string, data: Record): number { + return Buffer.byteLength(JSON.stringify({ type, data }), 'utf8'); +} + +export async function relayClient(target: RelayTarget): Promise { + const config = RELAY_TARGET_CONFIG[target]; + if (!config) throw new RelayError(`Unknown Relay target ${target}.`, 400, 'relay_target_unknown'); + const key = await relayKey(target); + + async function call(method: string, path: string, body?: unknown): Promise { + const label = `Relay ${target} ${method} ${path}`; + const payload = body === undefined ? undefined : JSON.stringify(body); + if (payload && Buffer.byteLength(payload, 'utf8') > MAX_RELAY_BODY_BYTES) { + throw new RelayError( + `${label}: body is ${Buffer.byteLength(payload, 'utf8')} bytes, over the ${MAX_RELAY_BODY_BYTES}-byte limit ` + + "(Relay's CloudFront WAF rejects bodies over ~8 KB). Shorten the block.", + 422, + 'relay_body_too_large', + ); + } + let response: Response; + try { + response = await deps.fetchImpl(`${config.url}${path}`, { + method, + headers: { + authorization: `Bearer ${key}`, + accept: 'application/json', + ...(payload ? { 'content-type': 'application/json' } : {}), + }, + body: payload, + signal: AbortSignal.timeout(RELAY_TIMEOUT_MS), + }); + } catch (error) { + const name = (error as { name?: string })?.name; + const reason = name === 'TimeoutError' || name === 'AbortError' + ? `timed out after ${RELAY_TIMEOUT_MS / 1000}s` + : (error as Error)?.message || 'network error'; + throw new RelayError(`${label} failed: ${reason}.`, 504, 'relay_unreachable'); + } + const text = await response.text(); + if (!response.ok) { + const hint = response.status === 403 && !text.trim().startsWith('{') ? ' (a bare 403 usually means the CloudFront WAF body limit)' : ''; + const status = response.status === 404 ? 404 : 502; + throw new RelayError(`${label} returned HTTP ${response.status}: ${text.slice(0, 300)}${hint}`, status, 'relay_http_error'); + } + try { + return JSON.parse(text) as T; + } catch { + throw new RelayError(`${label} returned a non-JSON body.`, 502, 'relay_bad_response'); + } + } + + const issuePath = (issueKey: string) => `/api/newsletter-issues/${encodeURIComponent(issueKey)}`; + return { + target, + url: config.url, + async getIssue(issueKey) { + const { issue } = await call<{ issue: RelayIssue }>('GET', issuePath(issueKey)); + if (!issue || !Array.isArray(issue.blocks)) throw new RelayError(`Relay ${target} issue ${issueKey} has no blocks list.`); + return issue; + }, + async getBlock(issueKey, blockId) { + return (await call<{ block: RelayBlock }>('GET', `${issuePath(issueKey)}/blocks/${blockId}`)).block; + }, + async putBlock(issueKey, blockId, type, data) { + return (await call<{ block: RelayBlock }>('PUT', `${issuePath(issueKey)}/blocks/${blockId}`, { type, data })).block; + }, + }; +} diff --git a/backend/src/newsletter/blocksStore.ts b/backend/src/newsletter/blocksStore.ts new file mode 100644 index 00000000..7405b884 --- /dev/null +++ b/backend/src/newsletter/blocksStore.ts @@ -0,0 +1,163 @@ +/** + * Storage for newsletter issue blocks (see ./blocks.ts). + * + * One item per issue holds the whole block set (a weekly issue has ~10 small + * blocks), written with an optimistic `version` condition so two writers never + * silently overwrite each other. Every content change appends one revision + * item (before/after of one block), the history `dataops newsletter revisions` + * reads. + */ +import { DeleteCommand, GetCommand, PutCommand, QueryCommand } from '@aws-sdk/lib-dynamodb'; +import type { DynamoDBDocumentClient } from '@aws-sdk/lib-dynamodb'; +import { TABLE_ARTIFACTS } from '../db/tableNames'; +import type { BlockData, IssueBlockSet } from './blocks'; + +export type BlockRevisionOrigin = 'import' | 'edit' | 'relay-pull' | 'relay-remove'; + +export interface BlockRevision { + issueId: string; + revision: number; + blockId: string; + relayBlockId: number; + blockType: string; + origin: BlockRevisionOrigin; + createdAt: string; + actorUserId: string; + actorName: string | null; + /** Who changed it in Relay, for pulled revisions (Relay's `updated_by`). */ + relayActor?: string; + before: BlockData | null; + after: BlockData | null; +} + +export class BlockSetVersionConflict extends Error { + constructor(issueId: string) { + super(`The blocks of issue ${issueId} changed while saving; reload and retry.`); + } +} + +const setKey = (issueId: string) => ({ PK: `NL_BLOCKS#${issueId}`, SK: 'SET' }); +const revisionPk = (issueId: string) => `NL_BLOCK_REV#${issueId}`; +const revisionKey = (issueId: string, revision: number) => ({ + PK: revisionPk(issueId), + SK: `REV#${String(revision).padStart(8, '0')}`, +}); + +function strip(item: Record | undefined): T | null { + if (!item) return null; + const { PK: _pk, SK: _sk, ...rest } = item; + return rest as T; +} + +export async function getBlockSet(client: DynamoDBDocumentClient, issueId: string): Promise { + const res = await client.send(new GetCommand({ TableName: TABLE_ARTIFACTS, Key: setKey(issueId), ConsistentRead: true })); + return strip(res.Item as Record | undefined); +} + +/** + * Write `next` if the stored set is still at `expectedVersion` (0 = must not + * exist yet). `next.version` must be `expectedVersion + 1`. + */ +export async function putBlockSet( + client: DynamoDBDocumentClient, + next: IssueBlockSet, + expectedVersion: number, +): Promise { + try { + await client.send( + new PutCommand({ + TableName: TABLE_ARTIFACTS, + Item: { ...setKey(next.issueId), ...next }, + ...(expectedVersion === 0 + ? { ConditionExpression: 'attribute_not_exists(PK)' } + : { + ConditionExpression: '#version = :expected', + ExpressionAttributeNames: { '#version': 'version' }, + ExpressionAttributeValues: { ':expected': expectedVersion }, + }), + }), + ); + } catch (error) { + if ((error as { name?: string })?.name === 'ConditionalCheckFailedException') { + throw new BlockSetVersionConflict(next.issueId); + } + throw error; + } +} + +export async function deleteBlockSet(client: DynamoDBDocumentClient, issueId: string): Promise { + await client.send(new DeleteCommand({ TableName: TABLE_ARTIFACTS, Key: setKey(issueId) })); + for (const revision of await listBlockRevisions(client, issueId)) { + await client.send(new DeleteCommand({ TableName: TABLE_ARTIFACTS, Key: revisionKey(issueId, revision.revision) })); + } +} + +async function latestRevisionNumber(client: DynamoDBDocumentClient, issueId: string): Promise { + const res = await client.send( + new QueryCommand({ + TableName: TABLE_ARTIFACTS, + KeyConditionExpression: 'PK = :pk', + ExpressionAttributeValues: { ':pk': revisionPk(issueId) }, + ScanIndexForward: false, + Limit: 1, + ConsistentRead: true, + }), + ); + const latest = strip((res.Items || [])[0] as Record | undefined); + return latest?.revision || 0; +} + +/** Append revisions in order; numbers continue from the latest stored one. */ +export async function appendBlockRevisions( + client: DynamoDBDocumentClient, + issueId: string, + revisions: Omit[], +): Promise { + const written: BlockRevision[] = []; + let next = revisions.length ? await latestRevisionNumber(client, issueId) : 0; + for (const revision of revisions) { + for (let attempt = 0; ; attempt += 1) { + next += 1; + const item: BlockRevision = { ...revision, issueId, revision: next }; + try { + await client.send( + new PutCommand({ + TableName: TABLE_ARTIFACTS, + Item: { ...revisionKey(issueId, next), ...item }, + ConditionExpression: 'attribute_not_exists(PK)', + }), + ); + written.push(item); + break; + } catch (error) { + if ((error as { name?: string })?.name !== 'ConditionalCheckFailedException' || attempt >= 4) throw error; + // A concurrent writer took the number; continue after the latest one. + next = await latestRevisionNumber(client, issueId); + } + } + } + return written; +} + +export async function listBlockRevisions(client: DynamoDBDocumentClient, issueId: string): Promise { + const revisions: BlockRevision[] = []; + let start: Record | undefined; + do { + const page = await client.send( + new QueryCommand({ + TableName: TABLE_ARTIFACTS, + KeyConditionExpression: 'PK = :pk', + ExpressionAttributeValues: { ':pk': revisionPk(issueId) }, + ScanIndexForward: true, + ConsistentRead: true, + ExclusiveStartKey: start, + }), + ); + for (const item of page.Items || []) { + const revision = strip(item as Record); + if (revision) revisions.push(revision); + } + start = page.LastEvaluatedKey as Record | undefined; + } while (start); + return revisions; +} diff --git a/backend/src/newsletter/blocksSync.ts b/backend/src/newsletter/blocksSync.ts new file mode 100644 index 00000000..ffbcb679 --- /dev/null +++ b/backend/src/newsletter/blocksSync.ts @@ -0,0 +1,383 @@ +/** + * Import, edit and two-way Relay sync of newsletter issue blocks. + * + * Decision: two-way sync with a per-block three-way merge, not DataOps as the + * only source of truth. Relay stays the renderer and sender, and its blocks + * keep being written outside DataOps (Relay's own editor, template autofill, + * `dataops newsletter relay-sync` for the sponsor block), so a one-way + * "DataOps builds Relay" would overwrite those edits. Instead each block keeps + * the content both sides last agreed on; a sync pushes blocks changed only in + * DataOps, pulls blocks changed only in Relay, and refuses to write anything + * when any block changed on both sides. + */ +import type { DynamoDBDocumentClient } from '@aws-sdk/lib-dynamodb'; +import { + blockFromRelay, + blockHash, + planSync, + validateBlockData, + type IssueBlock, + type IssueBlockSet, + type RelayIssue, + type RelayTarget, + type SyncPlan, + type SyncStep, +} from './blocks'; +import { + appendBlockRevisions, + getBlockSet, + putBlockSet, + type BlockRevision, +} from './blocksStore'; +import { MAX_RELAY_BODY_BYTES, RelayError, relayBodyBytes, relayClient } from './blocksRelay'; + +export interface BlockActor { + id: string; + name: string | null; +} + +export class BlocksError extends Error { + constructor( + message: string, + public readonly status: number, + public readonly code: string, + public readonly detail: Record = {}, + ) { + super(message); + } +} + +type NewRevision = Omit; + +const EDITABLE_CAMPAIGN_STATUSES = new Set(['draft']); + +function relayIssueSummary(issue: RelayIssue): IssueBlockSet['relayIssue'] { + return { + subject: issue.subject || '', + previewText: issue.preview_text || '', + campaignStatus: issue.campaign?.status || null, + updatedAt: issue.updated_at, + }; +} + +export async function importBlocks( + client: DynamoDBDocumentClient, + issueId: string, + input: { target: RelayTarget; issueKey: string }, + actor: BlockActor, +): Promise { + const existing = await getBlockSet(client, issueId); + if (existing) { + throw new BlocksError( + `Issue ${issueId} already has blocks linked to Relay ${existing.relay.target} ${existing.relay.issueKey}; use sync.`, + 409, + 'blocks_already_imported', + ); + } + const relay = await relayClient(input.target); + const remote = await relay.getIssue(input.issueKey); + const now = new Date().toISOString(); + const blocks = [...remote.blocks] + .sort((a, b) => a.position - b.position) + .map((block) => blockFromRelay(block, now, actor)); + const set: IssueBlockSet = { + issueId, + relay: { target: input.target, issueKey: remote.key || input.issueKey }, + relayIssue: relayIssueSummary(remote), + blocks, + version: 1, + lastSync: { at: now, byName: actor.name, summary: `imported ${blocks.length} blocks` }, + createdAt: now, + updatedAt: now, + }; + await putBlockSet(client, set, 0); + await appendBlockRevisions( + client, + issueId, + remote.blocks.map((block) => ({ + blockId: `rb-${block.id}`, + relayBlockId: block.id, + blockType: block.type, + origin: 'import', + createdAt: now, + actorUserId: actor.id, + actorName: actor.name, + relayActor: block.updated_by || '', + before: null, + after: { ...block.data }, + })), + ); + return set; +} + +export async function requireBlockSet(client: DynamoDBDocumentClient, issueId: string): Promise { + const set = await getBlockSet(client, issueId); + if (!set) { + throw new BlocksError( + `Issue ${issueId} has no blocks yet. Import them from Relay first (dataops newsletter blocks --import ).`, + 404, + 'blocks_not_imported', + ); + } + return set; +} + +export async function editBlock( + client: DynamoDBDocumentClient, + issueId: string, + blockId: string, + input: { data: unknown; expectedVersion: unknown }, + actor: BlockActor, +): Promise<{ set: IssueBlockSet; block: IssueBlock; changed: boolean }> { + const set = await requireBlockSet(client, issueId); + const block = set.blocks.find((item) => item.id === blockId); + if (!block) throw new BlocksError(`Issue ${issueId} has no block ${blockId}.`, 404, 'block_not_found'); + if (input.expectedVersion !== block.version) { + throw new BlocksError( + `Block ${blockId} is at version ${block.version}, not ${String(input.expectedVersion)}: it changed since you opened it. Reload, then edit again.`, + 409, + 'block_version_conflict', + { currentVersion: block.version }, + ); + } + const data = validateBlockData(block.type, input.data); + if (blockHash(block.type, data) === blockHash(block.type, block.data)) return { set, block, changed: false }; + const now = new Date().toISOString(); + const updated: IssueBlock = { + ...block, + data, + version: block.version + 1, + updatedAt: now, + updatedBy: actor.id, + updatedByName: actor.name, + }; + const next: IssueBlockSet = { + ...set, + blocks: set.blocks.map((item) => (item.id === blockId ? updated : item)), + version: set.version + 1, + updatedAt: now, + }; + await putBlockSet(client, next, set.version); + await appendBlockRevisions(client, issueId, [ + { + blockId, + relayBlockId: block.relayBlockId, + blockType: block.type, + origin: 'edit', + createdAt: now, + actorUserId: actor.id, + actorName: actor.name, + before: block.data, + after: data, + }, + ]); + return { set: next, block: updated, changed: true }; +} + +export interface SyncResult { + dryRun: boolean; + relay: { target: RelayTarget; url: string; issueKey: string }; + plan: SyncStep[]; + pushed: number[]; + pulled: number[]; + summary: string; + set: IssueBlockSet; +} + +function summarize(plan: SyncPlan): string { + const counts = new Map(); + for (const step of plan.steps) counts.set(step.action, (counts.get(step.action) || 0) + 1); + return [...counts.entries()].map(([action, count]) => `${count} ${action}`).join(', ') || 'no blocks'; +} + +/** Three-way sync with Relay. Refuses as a whole on any conflict. */ +export async function syncBlocks( + client: DynamoDBDocumentClient, + issueId: string, + options: { dryRun: boolean }, + actor: BlockActor, +): Promise { + const set = await requireBlockSet(client, issueId); + const relay = await relayClient(set.relay.target); + const remote = await relay.getIssue(set.relay.issueKey); + const plan = planSync(set.blocks, remote); + const where = { target: set.relay.target, url: relay.url, issueKey: set.relay.issueKey }; + + if (plan.conflicts.length) { + throw new BlocksError( + `Sync refused: ${plan.conflicts.length} block(s) changed both in DataOps and in Relay since the last sync. ` + + 'Nothing was written. Resolve each conflict by making both sides equal (copy one into the other), then sync again.', + 409, + 'blocks_sync_conflict', + { plan: plan.steps, conflicts: plan.conflicts }, + ); + } + const campaignStatus = remote.campaign?.status || null; + if (plan.pushes.length && campaignStatus && !EDITABLE_CAMPAIGN_STATUSES.has(campaignStatus)) { + throw new BlocksError( + `Sync refused: Relay issue ${set.relay.issueKey} has a ${campaignStatus} campaign, so its blocks are no longer edited. Nothing was written.`, + 409, + 'blocks_campaign_locked', + { plan: plan.steps }, + ); + } + const localById = new Map(set.blocks.map((block) => [block.id, block])); + for (const step of plan.pushes) { + const block = localById.get(step.blockId as string) as IssueBlock; + const bytes = relayBodyBytes(block.type, block.data); + if (bytes > MAX_RELAY_BODY_BYTES) { + throw new BlocksError( + `Sync refused: block ${block.id} (${block.type}) is ${bytes} bytes, over Relay's ${MAX_RELAY_BODY_BYTES}-byte request limit. Shorten it. Nothing was written.`, + 422, + 'relay_body_too_large', + { plan: plan.steps }, + ); + } + } + if (options.dryRun) { + return { dryRun: true, relay: where, plan: plan.steps, pushed: [], pulled: [], summary: summarize(plan), set }; + } + + const now = new Date().toISOString(); + const remoteById = new Map(remote.blocks.map((block) => [block.id, block])); + const blocks = new Map(set.blocks.map((block) => [block.id, { ...block }])); + const revisions: NewRevision[] = []; + const pushed: number[] = []; + const pulled: number[] = []; + let failure: unknown = null; + + // Pushes first, one block per request; each re-reads the Relay block right + // before writing so an edit made in Relay since the plan is not overwritten. + for (const step of plan.pushes) { + const block = blocks.get(step.blockId as string) as IssueBlock; + const seen = remoteById.get(block.relayBlockId)!; + try { + const fresh = await relay.getBlock(set.relay.issueKey, block.relayBlockId); + if (fresh.updated_at !== seen.updated_at || blockHash(fresh.type, fresh.data) !== blockHash(seen.type, seen.data)) { + throw new BlocksError( + `Sync stopped: Relay block ${block.relayBlockId} changed during the sync (by ${fresh.updated_by || 'unknown'} at ${fresh.updated_at}). ` + + `It was not overwritten. ${pushed.length} block(s) pushed before this were saved; sync again to see the conflict.`, + 409, + 'blocks_sync_conflict', + ); + } + const saved = await relay.putBlock(set.relay.issueKey, block.relayBlockId, block.type, block.data); + const savedHash = blockHash(saved.type, saved.data); + if (savedHash !== blockHash(block.type, block.data)) { + // Relay normalized the content; record what it actually stored. + revisions.push({ + blockId: block.id, + relayBlockId: block.relayBlockId, + blockType: saved.type, + origin: 'relay-pull', + createdAt: now, + actorUserId: actor.id, + actorName: actor.name, + relayActor: 'relay normalization on push', + before: block.data, + after: { ...saved.data }, + }); + block.data = { ...saved.data }; + block.type = saved.type; + block.version += 1; + } + block.base = { hash: savedHash, relayUpdatedAt: saved.updated_at, syncedAt: now }; + remoteById.set(saved.id, saved); + pushed.push(block.relayBlockId); + } catch (error) { + failure = error; + break; + } + } + + if (!failure) { + for (const step of plan.steps) { + if (step.action === 'pull') { + const block = blocks.get(step.blockId as string)!; + const source = remoteById.get(block.relayBlockId)!; + revisions.push({ + blockId: block.id, + relayBlockId: block.relayBlockId, + blockType: source.type, + origin: 'relay-pull', + createdAt: now, + actorUserId: actor.id, + actorName: actor.name, + relayActor: source.updated_by || '', + before: block.data, + after: { ...source.data }, + }); + Object.assign(block, { + type: source.type, + data: { ...source.data }, + version: block.version + 1, + updatedAt: now, + updatedBy: actor.id, + updatedByName: actor.name, + base: { hash: blockHash(source.type, source.data), relayUpdatedAt: source.updated_at, syncedAt: now }, + }); + pulled.push(block.relayBlockId); + } else if (step.action === 'add') { + const source = remoteById.get(step.relayBlockId)!; + const block = blockFromRelay(source, now, actor); + blocks.set(block.id, block); + revisions.push({ + blockId: block.id, + relayBlockId: source.id, + blockType: source.type, + origin: 'relay-pull', + createdAt: now, + actorUserId: actor.id, + actorName: actor.name, + relayActor: source.updated_by || '', + before: null, + after: { ...source.data }, + }); + pulled.push(source.id); + } else if (step.action === 'remove') { + const block = blocks.get(step.blockId as string)!; + blocks.delete(block.id); + revisions.push({ + blockId: block.id, + relayBlockId: block.relayBlockId, + blockType: block.type, + origin: 'relay-remove', + createdAt: now, + actorUserId: actor.id, + actorName: actor.name, + before: block.data, + after: null, + }); + pulled.push(block.relayBlockId); + } else if (step.action === 'in_sync') { + const block = blocks.get(step.blockId as string)!; + const source = remoteById.get(block.relayBlockId)!; + block.base = { hash: blockHash(source.type, source.data), relayUpdatedAt: source.updated_at, syncedAt: now }; + } + } + } + + // Block order follows Relay (blocks are added and reordered there). + for (const block of blocks.values()) { + const source = remoteById.get(block.relayBlockId); + if (source) block.position = source.position; + } + const summary = failure + ? `stopped after pushing ${pushed.length}: ${(failure as Error).message}` + : `${summarize(plan)}; pushed ${pushed.length}, pulled ${pulled.length}`; + const next: IssueBlockSet = { + ...set, + relayIssue: relayIssueSummary(remote), + blocks: [...blocks.values()].sort((a, b) => a.position - b.position), + version: set.version + 1, + lastSync: { at: now, byName: actor.name, summary }, + updatedAt: now, + }; + await putBlockSet(client, next, set.version); + await appendBlockRevisions(client, issueId, revisions); + if (failure) { + if (failure instanceof BlocksError || failure instanceof RelayError) throw failure; + throw new BlocksError(`Sync stopped: ${(failure as Error).message}`, 502, 'blocks_sync_failed'); + } + return { dryRun: false, relay: where, plan: plan.steps, pushed, pulled, summary, set: next }; +} diff --git a/backend/src/routes/newsletterBlocks.ts b/backend/src/routes/newsletterBlocks.ts new file mode 100644 index 00000000..be98bcce --- /dev/null +++ b/backend/src/routes/newsletterBlocks.ts @@ -0,0 +1,122 @@ +/** + * /api/newsletter-issues/:id/blocks — an issue's editable content blocks. + * + * GET /blocks the block set (404 blocks_not_imported before import) + * POST /blocks/import {target, issueKey}: copy a Relay issue's blocks in + * PUT /blocks/:blockId {data, version}: edit one block (records a revision) + * POST /blocks/sync {dryRun}: three-way sync with Relay (409 on conflict) + * GET /blocks/revisions every revision, oldest first (?block= filters) + * + * See ../newsletter/blocksSync.ts for why the sync is two-way. + */ +import type { DynamoDBDocumentClient } from '@aws-sdk/lib-dynamodb'; +import type { LambdaEvent, LambdaResponse } from '../types'; +import { json, parseJsonObjectEventOrEmpty } from '../http'; +import { resolveNewsletterIssue } from '../db/newsletterIssues'; +import { resolveInteractiveActor, type VerifiedActor } from '../identity/actor'; +import { + BLOCK_TYPES, + BlockValidationError, + FIELD_KINDS, + FIELD_LABELS, + RELAY_TARGETS, + blockHash, + blockLabel, + changedFields, + type IssueBlockSet, + type RelayTarget, +} from '../newsletter/blocks'; +import { BlockSetVersionConflict, listBlockRevisions } from '../newsletter/blocksStore'; +import { RelayError } from '../newsletter/blocksRelay'; +import { BlocksError, editBlock, importBlocks, requireBlockSet, syncBlocks, type BlockActor } from '../newsletter/blocksSync'; + +const blockActor = (actor: VerifiedActor): BlockActor => ({ id: actor.id, name: actor.user?.name || actor.user?.email || null }); + +/** The set as the API returns it: labels, field specs and pending-change flags added. */ +export function blockSetView(set: IssueBlockSet) { + return { + ...set, + blocks: set.blocks.map((block) => { + const spec = BLOCK_TYPES[block.type]; + return { + ...block, + label: blockLabel(block.type), + fields: (spec?.fields || Object.keys(block.data)).map((name) => ({ + name, + label: FIELD_LABELS[name] || name, + kind: FIELD_KINDS[name] || 'text', + required: Boolean(spec?.required.includes(name)), + default: spec?.defaults[name] || '', + })), + changedSinceSync: blockHash(block.type, block.data) !== block.base.hash, + }; + }), + }; +} + +function failure(error: unknown): LambdaResponse { + if (error instanceof BlocksError) return json(error.status, { error: error.message, code: error.code, ...error.detail }); + if (error instanceof RelayError) return json(error.status, { error: error.message, code: error.code }); + if (error instanceof BlockValidationError) { + return json(400, { error: error.message, code: 'block_invalid', fields: error.errors }); + } + if (error instanceof BlockSetVersionConflict) return json(409, { error: error.message, code: 'blocks_version_conflict' }); + throw error; +} + +export async function handleNewsletterBlockRoutes( + issueRef: string, + rest: string, + method: string, + event: LambdaEvent, + client: DynamoDBDocumentClient, +): Promise { + const readOnly = method === 'GET'; + const resolved = await resolveInteractiveActor(client, event, readOnly ? 'work-read' : 'work-write'); + if (!resolved.ok) return resolved.response; + const issue = await resolveNewsletterIssue(client, issueRef); + if (!issue) return json(404, { error: 'Newsletter issue not found', code: 'issue_not_found' }); + const actor = blockActor(resolved.actor); + const body = readOnly ? {} : parseJsonObjectEventOrEmpty(event); + if (!body) return json(400, { error: 'Invalid JSON' }); + + try { + if (rest === '' || rest === '/') { + if (method !== 'GET') return json(405, { error: 'Method not allowed' }); + return json(200, { issueId: issue.id, blocks: blockSetView(await requireBlockSet(client, issue.id)) }); + } + if (rest === '/import') { + if (method !== 'POST') return json(405, { error: 'Method not allowed' }); + const target = String(body.target || 'production') as RelayTarget; + if (!RELAY_TARGETS.includes(target)) return json(400, { error: `target must be one of ${RELAY_TARGETS.join(', ')}` }); + const issueKey = String(body.issueKey || '').trim(); + if (!/^[a-z0-9][a-z0-9-]{0,119}$/.test(issueKey)) return json(400, { error: 'issueKey must be a Relay issue key like weekly-304' }); + const set = await importBlocks(client, issue.id, { target, issueKey }, actor); + return json(201, { issueId: issue.id, blocks: blockSetView(set) }); + } + if (rest === '/sync') { + if (method !== 'POST') return json(405, { error: 'Method not allowed' }); + const result = await syncBlocks(client, issue.id, { dryRun: body.dryRun === true }, actor); + return json(200, { issueId: issue.id, ...result, set: undefined, blocks: blockSetView(result.set) }); + } + if (rest === '/revisions') { + if (method !== 'GET') return json(405, { error: 'Method not allowed' }); + const set = await requireBlockSet(client, issue.id); + const filter = event.queryStringParameters?.block || ''; + const revisions = (await listBlockRevisions(client, issue.id)) + .filter((revision) => !filter || revision.blockId === filter || String(revision.relayBlockId) === filter) + .map((revision) => ({ ...revision, label: blockLabel(revision.blockType), changes: changedFields(revision.before, revision.after) })); + return json(200, { issueId: issue.id, relay: set.relay, revisions }); + } + const blockMatch = rest.match(/^\/([^/]+)$/); + if (blockMatch) { + if (method !== 'PUT') return json(405, { error: 'Method not allowed' }); + const blockId = decodeURIComponent(blockMatch[1]); + const result = await editBlock(client, issue.id, blockId, { data: body.data, expectedVersion: body.version }, actor); + return json(200, { issueId: issue.id, changed: result.changed, blocks: blockSetView(result.set) }); + } + return json(404, { error: 'Not found' }); + } catch (error) { + return failure(error); + } +} diff --git a/backend/src/routes/newsletterIssues.ts b/backend/src/routes/newsletterIssues.ts index 9e459d97..058e79e7 100644 --- a/backend/src/routes/newsletterIssues.ts +++ b/backend/src/routes/newsletterIssues.ts @@ -91,6 +91,8 @@ import { GmailMessageRouteError, resolveGmailMessageRoute } from '../sponsorDocs import { applySponsorRoute, SponsorRouteError } from '../newsletter/sponsorRoute'; import { ReportSendError, sendIssueReport } from '../newsletter/reportSend'; import { json, parseJsonObjectEvent } from '../http'; +import { handleNewsletterBlockRoutes } from './newsletterBlocks'; +import { deleteBlockSet } from '../newsletter/blocksStore'; const ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/; const KINDS = new Set(['weekly', 'standalone']); @@ -765,6 +767,7 @@ async function deleteRoute(id: string, body: Body, event: LambdaEvent, client: D body.confirmCardDeletion === true, ); if (failure) return failure; + await deleteBlockSet(client, existing.id); return { statusCode: 204, headers: {}, body: '' }; } try { @@ -772,6 +775,7 @@ async function deleteRoute(id: string, body: Body, event: LambdaEvent, client: D } catch { return json(409, { error: 'Conflicting delete' }); } + await deleteBlockSet(client, existing.id); return { statusCode: 204, headers: {}, body: '' }; } @@ -1178,6 +1182,10 @@ export async function handleNewsletterIssueRoutes( const body = parse(event) || {}; return mailchimpMetricsRoute(decodeURIComponent(mailchimpMetrics[1]), body, event, client); } + const blocksRoute = path.match(/^\/api\/newsletter-issues\/([^/]+)\/blocks(\/.*)?$/); + if (blocksRoute) { + return handleNewsletterBlockRoutes(decodeURIComponent(blocksRoute[1]), blocksRoute[2] || '', method, event, client); + } const imageRoute = path.match(/^\/api\/newsletter-issues\/([^/]+)\/images\/?$/); if (imageRoute) { if (method !== 'POST') return json(405, { error: 'Method not allowed' }); diff --git a/backend/tests/newsletter-blocks.test.ts b/backend/tests/newsletter-blocks.test.ts new file mode 100644 index 00000000..23364d02 --- /dev/null +++ b/backend/tests/newsletter-blocks.test.ts @@ -0,0 +1,324 @@ +import { describe, it, before, after, beforeEach } 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 { buildNewsletterIssue, createNewsletterIssue } from '../src/db/newsletterIssues'; +import { createUser } from '../src/db/users'; +import { setRelayDepsForTests } from '../src/newsletter/blocksRelay'; +import { blockHash, planSync, validateBlockData, type IssueBlock, type RelayIssue } from '../src/newsletter/blocks'; +import { humanBearer } from './helpers/human-bearer'; + +type FakeBlock = { id: number; position: number; type: string; data: Record; updated_by: string; updated_at: string }; + +/** An in-memory Relay newsletter API: GET issue, GET/PUT block. */ +class FakeRelay { + issues = new Map(); + calls: string[] = []; + tick = 0; + /** Runs right before a block GET returns (to simulate a concurrent Relay edit). */ + beforeBlockGet: ((block: FakeBlock) => void) | null = null; + apiKeySeen = ''; + + stamp() { + this.tick += 1; + return `2026-11-23T10:00:${String(this.tick).padStart(2, '0')}+00:00`; + } + + seed(key: string, blocks: Omit[]) { + this.issues.set(key, { + key, + subject: `Subject ${key}`, + campaign: null, + blocks: blocks.map((block) => ({ ...block, updated_by: 'api:dtc-newsletter', updated_at: this.stamp() })), + }); + } + + editInRelay(key: string, id: number, data: Record) { + const block = this.issues.get(key)!.blocks.find((item) => item.id === id)!; + block.data = data; + block.updated_by = 'alexey@datatalks.club'; + block.updated_at = this.stamp(); + } + + fetch = async (url: string | URL | Request, init?: RequestInit): Promise => { + const method = init?.method || 'GET'; + const u = new URL(String(url)); + this.calls.push(`${method} ${u.host}${u.pathname}`); + this.apiKeySeen = String((init?.headers as Record)?.authorization || ''); + const match = u.pathname.match(/^\/api\/newsletter-issues\/([^/]+)(?:\/blocks\/(\d+))?$/); + const issue = match && this.issues.get(decodeURIComponent(match[1])); + if (!issue) return new Response(JSON.stringify({ errors: { key: 'not_found' } }), { status: 404 }); + const payload = () => ({ ...issue, preview_text: '', updated_at: this.stamp() }); + if (!match![2]) return new Response(JSON.stringify({ issue: payload() }), { status: 200 }); + const block = issue.blocks.find((item) => item.id === Number(match![2])); + if (!block) return new Response(JSON.stringify({ errors: { block_id: 'not_found' } }), { status: 404 }); + if (method === 'GET') { + this.beforeBlockGet?.(block); + return new Response(JSON.stringify({ block }), { status: 200 }); + } + const body = JSON.parse(String(init?.body || '{}')); + block.type = body.type; + block.data = body.data; + block.updated_by = 'api:dtc-newsletter'; + block.updated_at = this.stamp(); + return new Response(JSON.stringify({ block }), { status: 200 }); + }; +} + +const SECRETS: Record = { + 'relay-production.dtc-newsletter-api-key': 'prod-key-123', + 'relay-dev.api-keys': JSON.stringify({ RELAY_API_KEY: 'dev-key-456', RELAY_WEBHOOK: 'x' }), +}; + +describe('Newsletter issue blocks (/api/newsletter-issues/:id/blocks)', () => { + let client: DynamoDBDocumentClient; + let handler: typeof import('../src/handler').handler; + let token: string; + let userId: string; + let relay: FakeRelay; + let restore: () => void; + let issueSeq = 0; + + 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: 'alexey@datatalks.club', name: 'Alexey', passwordHash: 'x', role: 'admin' }); + userId = user.id; + token = await humanBearer(client, userId); + }); + + after(async () => { + await stopLocal(); + delete process.env.IS_LOCAL; + }); + + beforeEach(() => { + restore?.(); + relay = new FakeRelay(); + restore = setRelayDepsForTests({ + fetchImpl: relay.fetch as typeof fetch, + readSecret: async (name) => { + if (!(name in SECRETS)) throw new Error('missing'); + return SECRETS[name]; + }, + }); + }); + + async function req(method: string, path: string, body?: unknown, query?: Record) { + const res = await handler( + { + httpMethod: method, + path, + headers: { authorization: `Bearer ${token}`, 'x-user-id': userId, host: 'ops.dtcdev.click', 'x-forwarded-proto': 'https' }, + queryStringParameters: query || null, + body: body === undefined ? null : JSON.stringify(body), + }, + {}, + ); + return { status: res.statusCode, body: res.body ? JSON.parse(res.body) : null }; + } + + async function newIssue() { + issueSeq += 1; + const issue = buildNewsletterIssue( + { kind: 'weekly', publicationDate: `2027-0${issueSeq}-01`, issueNumber: 900 + issueSeq, status: 'planned', slots: {} }, + `issue-blocks-${issueSeq}`, + ); + await createNewsletterIssue(client, issue); + return issue.id; + } + + function seedWeekly(key: string) { + relay.seed(key, [ + { id: 113, position: 0, type: 'intro', data: { issue_label: '#304', summary: 'Hello this week' } }, + { id: 114, position: 1, type: 'sponsor', data: { title: 'Sponsor', kicker: 'SPONSORED', cta_text: 'Go', cta_url: 'https://x.example/a' } }, + { id: 115, position: 2, type: 'events_list', data: { events: 'Mon · Webinar | Talk | https://x.example/e' } }, + ]); + } + + async function imported(key = 'weekly-304', target = 'dev') { + const id = await newIssue(); + seedWeekly(key); + const res = await req('POST', `/api/newsletter-issues/${id}/blocks/import`, { target, issueKey: key }); + assert.strictEqual(res.status, 201, JSON.stringify(res.body)); + return { id, set: res.body.blocks }; + } + + it('imports every Relay block with the right key per target, and lists them', async () => { + const id = await newIssue(); + assert.strictEqual((await req('GET', `/api/newsletter-issues/${id}/blocks`)).body.code, 'blocks_not_imported'); + seedWeekly('weekly-304'); + const res = await req('POST', `/api/newsletter-issues/${id}/blocks/import`, { target: 'production', issueKey: 'weekly-304' }); + assert.strictEqual(res.status, 201); + assert.strictEqual(relay.apiKeySeen, 'Bearer prod-key-123'); + assert.deepStrictEqual(relay.calls, ['GET relay.datatalks.club/api/newsletter-issues/weekly-304']); + const listed = (await req('GET', `/api/newsletter-issues/${id}/blocks`)).body.blocks; + assert.deepStrictEqual(listed.blocks.map((b: IssueBlock) => [b.id, b.type, b.position]), [ + ['rb-113', 'intro', 0], + ['rb-114', 'sponsor', 1], + ['rb-115', 'events_list', 2], + ]); + assert.ok(listed.blocks[1].fields.some((f: { name: string }) => f.name === 'cta_url')); + assert.strictEqual(listed.relayIssue.subject, 'Subject weekly-304'); + // Importing twice is refused rather than overwriting. + assert.strictEqual((await req('POST', `/api/newsletter-issues/${id}/blocks/import`, { target: 'production', issueKey: 'weekly-304' })).status, 409); + const revisions = (await req('GET', `/api/newsletter-issues/${id}/blocks/revisions`)).body.revisions; + assert.deepStrictEqual(revisions.map((r: { origin: string }) => r.origin), ['import', 'import', 'import']); + + relay.calls = []; + const dev = await newIssue(); + await req('POST', `/api/newsletter-issues/${dev}/blocks/import`, { target: 'dev', issueKey: 'weekly-304' }); + assert.strictEqual(relay.apiKeySeen, 'Bearer dev-key-456'); + assert.match(relay.calls[0], /^GET dev\.relay\.datatalks\.club\//); + }); + + it('records an edit as a revision with a field diff and rejects stale or invalid edits', async () => { + const { id } = await imported(); + const path = `/api/newsletter-issues/${id}/blocks/rb-113`; + const ok = await req('PUT', path, { version: 1, data: { issue_label: '#304', summary: 'Hello edited week ' } }); + assert.strictEqual(ok.status, 200, JSON.stringify(ok.body)); + const block = ok.body.blocks.blocks.find((b: IssueBlock) => b.id === 'rb-113'); + assert.strictEqual(block.data.summary, 'Hello edited week'); + assert.strictEqual(block.version, 2); + assert.strictEqual(block.changedSinceSync, true); + assert.strictEqual((await req('PUT', path, { version: 1, data: { summary: 'x' } })).body.code, 'block_version_conflict'); + const bad = await req('PUT', `/api/newsletter-issues/${id}/blocks/rb-114`, { version: 1, data: { title: 'T', cta_text: 'Go', cta_url: 'not a url', bogus: 'x' } }); + assert.strictEqual(bad.status, 400); + assert.deepStrictEqual(bad.body.fields, { 'data.bogus': 'unknown_field', 'data.cta_url': 'invalid_url' }); + + const revisions = (await req('GET', `/api/newsletter-issues/${id}/blocks/revisions`, undefined, { block: '113' })).body.revisions; + assert.deepStrictEqual(revisions.map((r: { origin: string }) => r.origin), ['import', 'edit']); + assert.strictEqual(revisions[1].actorName, 'Alexey'); + assert.deepStrictEqual(revisions[1].changes, [{ field: 'summary', before: 'Hello this week', after: 'Hello edited week' }]); + }); + + it('pushes DataOps edits and pulls Relay edits in one sync, then round-trips', async () => { + const { id } = await imported(); + await req('PUT', `/api/newsletter-issues/${id}/blocks/rb-113`, { version: 1, data: { issue_label: '#304', summary: 'From DataOps' } }); + relay.editInRelay('weekly-304', 115, { events: 'Tue · Workshop | New | https://x.example/n' }); + + const dry = await req('POST', `/api/newsletter-issues/${id}/blocks/sync`, { dryRun: true }); + assert.strictEqual(dry.status, 200); + assert.deepStrictEqual(dry.body.plan.map((s: { action: string }) => s.action), ['push', 'in_sync', 'pull']); + assert.ok(!relay.calls.some((c) => c.startsWith('PUT')), 'dry run writes nothing'); + + const res = await req('POST', `/api/newsletter-issues/${id}/blocks/sync`, {}); + assert.strictEqual(res.status, 200, JSON.stringify(res.body)); + assert.deepStrictEqual(res.body.pushed, [113]); + assert.deepStrictEqual(res.body.pulled, [115]); + assert.strictEqual(relay.issues.get('weekly-304')!.blocks[0].data.summary, 'From DataOps'); + const blocks = res.body.blocks.blocks; + assert.strictEqual(blocks[2].data.events, 'Tue · Workshop | New | https://x.example/n'); + assert.ok(blocks.every((b: { changedSinceSync: boolean }) => !b.changedSinceSync)); + + const again = await req('POST', `/api/newsletter-issues/${id}/blocks/sync`, {}); + assert.deepStrictEqual(again.body.plan.map((s: { action: string }) => s.action), ['in_sync', 'in_sync', 'in_sync']); + const origins = (await req('GET', `/api/newsletter-issues/${id}/blocks/revisions`)).body.revisions.map((r: { origin: string }) => r.origin); + assert.deepStrictEqual(origins, ['import', 'import', 'import', 'edit', 'relay-pull']); + }); + + it('refuses the whole sync when a block changed on both sides, writing nothing', async () => { + const { id } = await imported(); + await req('PUT', `/api/newsletter-issues/${id}/blocks/rb-113`, { version: 1, data: { summary: 'DataOps version' } }); + await req('PUT', `/api/newsletter-issues/${id}/blocks/rb-115`, { version: 1, data: { events: 'Wed · Talk | Pushable | https://x.example/p' } }); + relay.editInRelay('weekly-304', 113, { summary: 'Relay version' }); + const res = await req('POST', `/api/newsletter-issues/${id}/blocks/sync`, {}); + assert.strictEqual(res.status, 409); + assert.strictEqual(res.body.code, 'blocks_sync_conflict'); + assert.deepStrictEqual(res.body.conflicts.map((c: { relayBlockId: number }) => c.relayBlockId), [113]); + assert.ok(!relay.calls.some((c) => c.startsWith('PUT')), 'no block pushed'); + assert.strictEqual(relay.issues.get('weekly-304')!.blocks[0].data.summary, 'Relay version'); + const local = (await req('GET', `/api/newsletter-issues/${id}/blocks`)).body.blocks.blocks; + assert.strictEqual(local[0].data.summary, 'DataOps version'); + + // Resolving by making both sides equal lets the sync through. + await req('PUT', `/api/newsletter-issues/${id}/blocks/rb-113`, { version: 2, data: { summary: 'Relay version' } }); + const ok = await req('POST', `/api/newsletter-issues/${id}/blocks/sync`, {}); + assert.strictEqual(ok.status, 200, JSON.stringify(ok.body)); + assert.deepStrictEqual(ok.body.pushed, [115]); + }); + + it('does not overwrite a Relay edit made between planning and pushing', async () => { + const { id } = await imported(); + await req('PUT', `/api/newsletter-issues/${id}/blocks/rb-114`, { version: 1, data: { title: 'New', cta_text: 'Go', cta_url: 'https://x.example/a' } }); + relay.beforeBlockGet = (block) => { + block.data = { ...block.data, title: 'Concurrent Relay edit' }; + block.updated_at = relay.stamp(); + relay.beforeBlockGet = null; + }; + const res = await req('POST', `/api/newsletter-issues/${id}/blocks/sync`, {}); + assert.strictEqual(res.status, 409); + assert.match(res.body.error, /changed during the sync/); + assert.strictEqual(relay.issues.get('weekly-304')!.blocks[1].data.title, 'Concurrent Relay edit'); + const next = await req('POST', `/api/newsletter-issues/${id}/blocks/sync`, { dryRun: true }); + assert.strictEqual(next.status, 409); + assert.strictEqual(next.body.conflicts[0].relayBlockId, 114); + }); + + it('refuses to push into a Relay issue whose campaign left draft, and surfaces Relay failures', async () => { + const { id } = await imported(); + await req('PUT', `/api/newsletter-issues/${id}/blocks/rb-113`, { version: 1, data: { summary: 'late edit' } }); + relay.issues.get('weekly-304')!.campaign = { status: 'sent' }; + const locked = await req('POST', `/api/newsletter-issues/${id}/blocks/sync`, {}); + assert.strictEqual(locked.status, 409); + assert.strictEqual(locked.body.code, 'blocks_campaign_locked'); + + relay.issues.delete('weekly-304'); + const missing = await req('POST', `/api/newsletter-issues/${id}/blocks/sync`, {}); + assert.strictEqual(missing.status, 404); + assert.match(missing.body.error, /Relay dev GET \/api\/newsletter-issues\/weekly-304 returned HTTP 404/); + + restore(); + restore = setRelayDepsForTests({ + fetchImpl: (async () => { throw Object.assign(new Error('aborted'), { name: 'TimeoutError' }); }) as typeof fetch, + readSecret: async (name) => SECRETS[name], + }); + const slow = await req('POST', `/api/newsletter-issues/${id}/blocks/sync`, {}); + assert.strictEqual(slow.status, 504); + assert.match(slow.body.error, /timed out after 15s/); + assert.doesNotMatch(JSON.stringify(slow.body), /dev-key-456/); + }); + + it('refuses a block body over the Relay request limit before writing', async () => { + const { id } = await imported(); + const long = Array.from({ length: 80 }, (_, i) => `Day ${i} · Talk | Title ${i} ${'x'.repeat(60)} | https://x.example/${i}`).join('\n'); + await req('PUT', `/api/newsletter-issues/${id}/blocks/rb-115`, { version: 1, data: { events: long } }); + const res = await req('POST', `/api/newsletter-issues/${id}/blocks/sync`, {}); + assert.strictEqual(res.status, 422); + assert.strictEqual(res.body.code, 'relay_body_too_large'); + assert.ok(!relay.calls.some((c) => c.startsWith('PUT'))); + }); +}); + +describe('newsletter block planning', () => { + const base = (type: string, data: Record) => ({ hash: blockHash(type, data), relayUpdatedAt: 't0', syncedAt: 't0' }); + const local = (data: Record, baseData: Record): IssueBlock => ({ + id: 'rb-1', relayBlockId: 1, position: 0, type: 'intro', data, version: 1, updatedAt: '', updatedBy: '', updatedByName: null, base: base('intro', baseData), + }); + const remote = (blocks: { id: number; data: Record }[]): RelayIssue => ({ + key: 'k', subject: 's', updated_at: 't', blocks: blocks.map((b, i) => ({ ...b, position: i, type: 'intro', updated_at: 't1' })), + }); + + it('classifies deletions in Relay and new Relay blocks', () => { + const removed = planSync([local({ summary: 'a' }, { summary: 'a' })], remote([])); + assert.deepStrictEqual(removed.steps.map((s) => s.action), ['remove']); + const edited = planSync([local({ summary: 'b' }, { summary: 'a' })], remote([])); + assert.deepStrictEqual(edited.steps.map((s) => s.action), ['conflict']); + const added = planSync([], remote([{ id: 9, data: { summary: 'n' } }])); + assert.deepStrictEqual(added.steps.map((s) => s.action), ['add']); + const same = planSync([local({ summary: 'b' }, { summary: 'a' })], remote([{ id: 1, data: { summary: 'b' } }])); + assert.deepStrictEqual(same.steps.map((s) => s.action), ['in_sync']); + }); + + it('validates like Relay: trims, drops empty fields, keeps html whitespace, checks required fields', () => { + assert.deepStrictEqual(validateBlockData('intro', { summary: ' s ', issue_label: '' }), { summary: 's' }); + assert.deepStrictEqual(validateBlockData('html', { html: ' x ' }), { html: ' x ' }); + assert.throws(() => validateBlockData('intro', { summary: '' }), /data.summary required/); + assert.deepStrictEqual(validateBlockData('events_list', { events: 'a | b | https://x.example' }), { events: 'a | b | https://x.example' }); + }); +}); From eb3fa07dcc65eba855333bd94ba4adc74b263120 Mon Sep 17 00:00:00 2001 From: Alexey Grigorev Date: Mon, 23 Nov 2026 13:08:29 +0100 Subject: [PATCH 02/12] CLI: newsletter blocks, block-edit, blocks-sync and revisions --diff --- cli/src/cli.mjs | 4 + cli/src/commands/newsletter.mjs | 15 ++- cli/src/commands/newsletterBlocks.mjs | 186 ++++++++++++++++++++++++++ cli/src/commands/sponsorDocs.mjs | 2 +- cli/test/newsletter-blocks.test.mjs | 71 ++++++++++ 5 files changed, 276 insertions(+), 2 deletions(-) create mode 100644 cli/src/commands/newsletterBlocks.mjs create mode 100644 cli/test/newsletter-blocks.test.mjs diff --git a/cli/src/cli.mjs b/cli/src/cli.mjs index da6d1b54..42771138 100644 --- a/cli/src/cli.mjs +++ b/cli/src/cli.mjs @@ -303,6 +303,10 @@ export async function run(argv, io = console) { print(sponsorDocs.newsletterDocHelp); return EXIT.ok; } + if (commandName === "newsletter" && ["blocks", "block-edit", "blocks-sync", "revisions"].includes(rest[0])) { + print(newsletter.blocksHelp); + return EXIT.ok; + } if (commandName === "newsletter" && rest[0] === "relay-sync") { print(newsletter.relaySyncHelp); return EXIT.ok; diff --git a/cli/src/commands/newsletter.mjs b/cli/src/commands/newsletter.mjs index e3c3fe03..d67882ce 100644 --- a/cli/src/commands/newsletter.mjs +++ b/cli/src/commands/newsletter.mjs @@ -6,6 +6,7 @@ import { apiFor } from "../session.mjs"; import { planNewsletterSync, readNewsletterCsv, sheetIssues } from "../newsletterSheet.mjs"; import { rewriteVerificationUri } from "./auth.mjs"; import { relaySync, relaySyncHelp } from "./newsletterRelay.mjs"; +import { blockEdit, blocks, blocksHelp, blocksSync, revisions } from "./newsletterBlocks.mjs"; import { domainDocCommand } from "./sponsorDocs.mjs"; import { multipart } from "./tasks.mjs"; @@ -80,6 +81,14 @@ Usage sponsor document (title, kicker, body, bullets, closing, image, CTA): one per-block write, updating the existing block. Details: dataops newsletter relay-sync --help + dataops newsletter blocks [--show] [--import [--target production|dev]] + dataops newsletter block-edit --field --value + dataops newsletter blocks-sync [--dry-run] + dataops newsletter revisions [--block ] [--diff] [--rev N] + Every content block of the issue (intro, sponsor, events, + recording, article...), editable here and on the issue page; + per-edit revisions with diffs; two-way Relay sync that refuses + on conflicts. Details: dataops newsletter blocks --help dataops newsletter image upload Upload an image (PNG, JPEG, GIF, or WebP) to durable public hosting for the issue and print its https:// URL @@ -1070,7 +1079,7 @@ in issue.md and the HTML preview. `; export { newsletterImageHelp as imageHelp }; -export { relaySyncHelp }; +export { relaySyncHelp, blocksHelp }; async function imageUpload(args, io) { const usage = "dataops newsletter image upload "; @@ -1178,6 +1187,10 @@ export const commands = { markdown, "final-render": finalRender, "relay-sync": relaySync, + blocks, + "block-edit": blockEdit, + "blocks-sync": blocksSync, + revisions, metrics, "pull-mailchimp": pullMailchimp, report, diff --git a/cli/src/commands/newsletterBlocks.mjs b/cli/src/commands/newsletterBlocks.mjs new file mode 100644 index 00000000..096f5e81 --- /dev/null +++ b/cli/src/commands/newsletterBlocks.mjs @@ -0,0 +1,186 @@ +// Newsletter issue blocks: list, import from Relay, edit, sync with Relay, and +// read the revision history (who changed which block, and how). + +import { readFileSync } from "node:fs"; +import { UsageError } from "../errors.mjs"; +import { enc, optionalString, positional, table } from "../format.mjs"; +import { apiFor } from "../session.mjs"; +import { formatLineDiff } from "./sponsorDocs.mjs"; + +export const blocksHelp = `dataops newsletter blocks / block-edit / blocks-sync / revisions - issue content blocks + +Usage + dataops newsletter blocks [--show] [--json] + dataops newsletter blocks --import [--target production|dev] + dataops newsletter block-edit --field --value + dataops newsletter block-edit --field --value-file + dataops newsletter block-edit --data-file + dataops newsletter blocks-sync [--dry-run] [--json] + dataops newsletter revisions [--block ] [--origin edit|import|relay-pull] + [--diff] [--rev N] [--json] + +Every block of the issue (intro, sponsor, event spotlight, course updates, +events list, recording, article, ...) is editable in DataOps on the issue page +(/newsletter/) and here. Each edit is a revision; "revisions" lists +them and --diff prints a line diff per changed field (--rev N for one). + +Sync with Relay is two-way, per block, against the content both sides last +agreed on: blocks edited only in DataOps are pushed, blocks edited only in +Relay are pulled. A block edited on both sides is a conflict and the whole +sync is refused before anything is written. --dry-run shows the plan. +Pushing is refused once the Relay campaign has left draft. Nothing is sent. +`; + +function blockRow(block) { + const first = block.data?.title || block.data?.summary || block.data?.events || block.data?.html || ""; + return { + ...block, + preview: String(first).replace(/\s+/g, " ").slice(0, 60), + }; +} + +function printSet(io, set) { + io.print(`relay: ${set.relay.target} ${set.relay.issueKey} · subject: ${set.relayIssue?.subject || ""}`); + if (set.lastSync) io.print(`last sync: ${set.lastSync.at} by ${set.lastSync.byName || "?"} (${set.lastSync.summary})`); + table( + io, + set.blocks.map(blockRow), + [ + ["POS", (b) => String(b.position)], + ["ID", (b) => b.id], + ["TYPE", (b) => b.type], + ["V", (b) => String(b.version)], + ["STATE", (b) => (b.changedSinceSync ? "edited, not pushed" : "in sync")], + ["EDITED BY", (b) => b.updatedByName || ""], + ["CONTENT", (b) => b.preview], + ], + "No blocks.", + ); +} + +export async function blocks(args, io) { + const usage = "dataops newsletter blocks [--import [--target production|dev]]"; + const issue = String(positional(args, 0, usage)); + const api = apiFor(args); + const importKey = optionalString(args, "import"); + const result = importKey + ? await api.post(`/api/newsletter-issues/${enc(issue)}/blocks/import`, { + issueKey: importKey, + target: optionalString(args, "target") || "production", + }) + : await api.get(`/api/newsletter-issues/${enc(issue)}/blocks`); + if (args.json) return result; + if (importKey) io.print(`imported ${result.blocks.blocks.length} blocks from Relay ${result.blocks.relay.target} ${importKey}`); + printSet(io, result.blocks); + if (args.show) { + for (const block of result.blocks.blocks) { + io.print(""); + io.print(`## ${block.id} · ${block.label} (v${block.version})`); + for (const [name, value] of Object.entries(block.data || {})) io.print(`${name}: ${String(value).replace(/\n/g, "\n ")}`); + } + } + return result; +} + +export async function blockEdit(args, io) { + const usage = "dataops newsletter block-edit (--field --value | --value-file | --data-file )"; + const issue = String(positional(args, 0, usage)); + const blockId = String(positional(args, 1, usage)); + const api = apiFor(args); + const current = (await api.get(`/api/newsletter-issues/${enc(issue)}/blocks`)).blocks; + const block = current.blocks.find((item) => item.id === blockId || String(item.relayBlockId) === blockId); + if (!block) throw new UsageError(`No block ${blockId}. Blocks: ${current.blocks.map((b) => b.id).join(", ")}`); + let data; + const dataFile = optionalString(args, "dataFile"); + if (dataFile) { + data = JSON.parse(readFileSync(dataFile, "utf8")); + } else { + const field = optionalString(args, "field"); + if (!field) throw new UsageError(usage); + const valueFile = optionalString(args, "valueFile"); + const value = valueFile ? readFileSync(valueFile, "utf8") : args.value; + if (typeof value !== "string") throw new UsageError(`Pass --value or --value-file . Usage: ${usage}`); + data = { ...block.data, [field]: value }; + } + const result = await api.put(`/api/newsletter-issues/${enc(issue)}/blocks/${enc(block.id)}`, { version: block.version, data }); + if (args.json) return result; + const saved = result.blocks.blocks.find((item) => item.id === block.id); + io.print(result.changed ? `saved ${block.id} as version ${saved.version} (not pushed to Relay yet; run blocks-sync)` : `${block.id} unchanged`); + return result; +} + +export async function blocksSync(args, io) { + const usage = "dataops newsletter blocks-sync [--dry-run]"; + const issue = String(positional(args, 0, usage)); + const api = apiFor(args); + const result = await api.post(`/api/newsletter-issues/${enc(issue)}/blocks/sync`, { dryRun: Boolean(args.dryRun) }); + if (args.json) return result; + io.print(`relay: ${result.relay.target} ${result.relay.issueKey} (${result.relay.url})${result.dryRun ? " · dry run, nothing written" : ""}`); + table( + io, + result.plan, + [ + ["RELAY ID", (s) => String(s.relayBlockId)], + ["TYPE", (s) => s.type], + ["ACTION", (s) => s.action], + ["WHY", (s) => s.reason], + ], + "No blocks.", + ); + if (!result.dryRun) io.print(`pushed: ${result.pushed.join(", ") || "none"} · pulled: ${result.pulled.join(", ") || "none"}`); + return result; +} + +function who(rev) { + if (rev.origin === "relay-pull" || rev.origin === "relay-remove") return `Relay: ${rev.relayActor || "?"}`; + return rev.actorName || rev.actorUserId || "?"; +} + +export async function revisions(args, io) { + const usage = "dataops newsletter revisions [--block ] [--origin ] [--diff] [--rev N]"; + const issue = String(positional(args, 0, usage)); + const api = apiFor(args); + const block = optionalString(args, "block"); + const result = await api.get(`/api/newsletter-issues/${enc(issue)}/blocks/revisions`, { + query: block ? { block: block.replace(/^rb-/, "") } : undefined, + }); + let list = result.revisions || []; + const origin = optionalString(args, "origin"); + if (origin) list = list.filter((rev) => rev.origin === origin); + if (args.rev !== undefined) { + if (!/^[1-9]\d*$/.test(String(args.rev))) throw new UsageError(`--rev must be a positive integer, got "${args.rev}".`); + list = list.filter((rev) => rev.revision === Number(args.rev)); + if (!list.length) throw new UsageError(`No revision ${args.rev} for issue ${issue}.`); + } + if (args.json) return { ...result, revisions: list }; + if (!args.diff && args.rev === undefined) { + table( + io, + list, + [ + ["REV", (r) => String(r.revision)], + ["WHEN", (r) => r.createdAt.slice(0, 19).replace("T", " ")], + ["BLOCK", (r) => `${r.blockId} ${r.blockType}`], + ["ORIGIN", (r) => r.origin], + ["BY", who], + ["CHANGED", (r) => r.changes.map((c) => c.field).join(", ") || "(none)"], + ], + `No revisions for issue ${issue}.`, + ); + return { ...result, revisions: list }; + } + for (const rev of list) { + io.print(`=== rev ${rev.revision} · ${rev.blockId} ${rev.label} · ${rev.origin} by ${who(rev)} · ${rev.createdAt}`); + if (!rev.changes.length) io.print("(no field changes)"); + for (const change of rev.changes) { + io.print(`--- ${change.field} [before]`); + io.print(`+++ ${change.field} [after]`); + const lines = rev.before === null + ? change.after.split("\n").map((line) => `+ ${line}`) + : formatLineDiff(change.before, change.after); + for (const line of lines) io.print(line); + } + io.print(""); + } + return { ...result, revisions: list }; +} diff --git a/cli/src/commands/sponsorDocs.mjs b/cli/src/commands/sponsorDocs.mjs index 5d391941..d9a463d5 100644 --- a/cli/src/commands/sponsorDocs.mjs +++ b/cli/src/commands/sponsorDocs.mjs @@ -608,7 +608,7 @@ function formatActor(rev) { return rev.actorName ? `${kind} (${rev.actorName})` : kind; } -function formatLineDiff(beforeText, afterText) { +export function formatLineDiff(beforeText, afterText) { const a = String(beforeText ?? "").split("\n"); const b = String(afterText ?? "").split("\n"); // Fallback to simple -/+ if very large to avoid O(N*M) memory blowup diff --git a/cli/test/newsletter-blocks.test.mjs b/cli/test/newsletter-blocks.test.mjs new file mode 100644 index 00000000..5788036f --- /dev/null +++ b/cli/test/newsletter-blocks.test.mjs @@ -0,0 +1,71 @@ +import assert from "node:assert/strict"; +import { describe, test } from "node:test"; + +import { captureIo, fakePortal, isolateConfig } from "./helpers.mjs"; + +isolateConfig(); +const { run } = await import("../src/cli.mjs"); + +const set = (blocks) => ({ + issueId: "iss-304", + blocks: { + issueId: "iss-304", + relay: { target: "production", issueKey: "weekly-304" }, + relayIssue: { subject: "Weekly 304" }, + lastSync: { at: "2026-11-23T10:00:00Z", byName: "Orin", summary: "imported 2 blocks" }, + blocks, + }, +}); +const intro = { id: "rb-113", relayBlockId: 113, position: 0, type: "intro", label: "Intro", version: 1, data: { summary: "Hello" }, changedSinceSync: false }; + +describe("newsletter blocks CLI", () => { + test("blocks --import posts the Relay key and prints every block", async () => { + const calls = fakePortal({ "POST /api/newsletter-issues/304/blocks/import": () => ({ status: 201, body: set([intro]) }) }); + const io = captureIo(); + assert.equal(await run(["newsletter", "blocks", "304", "--import", "weekly-304"], io), 0, io.errors.join("\n")); + assert.deepEqual(calls[0].body, { issueKey: "weekly-304", target: "production" }); + assert.match(io.text(), /imported 1 blocks from Relay production weekly-304/); + assert.match(io.text(), /rb-113\s+intro\s+1\s+in sync/); + }); + + test("block-edit sends the block's version with one field replaced", async () => { + const calls = fakePortal({ + "GET /api/newsletter-issues/304/blocks": () => set([intro]), + "PUT /api/newsletter-issues/304/blocks/rb-113": () => ({ changed: true, ...set([{ ...intro, version: 2 }]) }), + }); + const io = captureIo(); + assert.equal(await run(["newsletter", "block-edit", "304", "113", "--field", "issue_label", "--value", "#304"], io), 0, io.errors.join("\n")); + assert.deepEqual(calls[1].body, { version: 1, data: { summary: "Hello", issue_label: "#304" } }); + assert.match(io.text(), /saved rb-113 as version 2/); + }); + + test("blocks-sync surfaces a conflict refusal as an error", async () => { + fakePortal({ + "POST /api/newsletter-issues/304/blocks/sync": () => ({ + status: 409, + body: { error: "Sync refused: 1 block(s) changed both in DataOps and in Relay since the last sync.", code: "blocks_sync_conflict" }, + }), + }); + const io = captureIo(); + assert.notEqual(await run(["newsletter", "blocks-sync", "304"], io), 0); + assert.match(io.errors.join("\n"), /Sync refused/); + }); + + test("revisions lists revisions and --diff prints field line diffs", async () => { + const revisions = [ + { revision: 1, blockId: "rb-113", blockType: "intro", label: "Intro", origin: "import", createdAt: "2026-11-23T10:00:00Z", actorName: "Orin", relayActor: "api:dtc", before: null, after: { summary: "Hello" }, changes: [{ field: "summary", before: "", after: "Hello" }] }, + { revision: 2, blockId: "rb-113", blockType: "intro", label: "Intro", origin: "edit", createdAt: "2026-11-23T11:00:00Z", actorName: "Alexey", before: { summary: "Hello\nworld" }, after: { summary: "Hello\nthere" }, changes: [{ field: "summary", before: "Hello\nworld", after: "Hello\nthere" }] }, + ]; + const calls = fakePortal({ "GET /api/newsletter-issues/304/blocks/revisions": () => ({ issueId: "iss-304", revisions }) }); + const io = captureIo(); + assert.equal(await run(["newsletter", "revisions", "304"], io), 0, io.errors.join("\n")); + assert.match(io.text(), /2\s+2026-11-23 11:00:00\s+rb-113 intro\s+edit\s+Alexey\s+summary/); + + const diff = captureIo(); + assert.equal(await run(["newsletter", "revisions", "304", "--origin", "edit", "--diff", "--block", "rb-113"], diff), 0, diff.errors.join("\n")); + assert.deepEqual(calls[1].query, { block: "113" }); + assert.match(diff.text(), /=== rev 2 · rb-113 Intro · edit by Alexey/); + assert.match(diff.text(), / Hello\n- world\n\+ there/); + assert.doesNotMatch(diff.text(), /rev 1/); + }); +}); From 016dd07178904704d07a06e25b405665a0e71056 Mon Sep 17 00:00:00 2001 From: Alexey Grigorev Date: Mon, 23 Nov 2026 13:16:18 +0100 Subject: [PATCH 03/12] Newsletter issue page: editable content blocks, per-block history, Relay check/sync --- frontend/src/styles/planner.css | 68 +++++ .../surfaces/operations/newsletter-blocks.js | 254 ++++++++++++++++++ .../src/surfaces/planning-newsletter-issue.js | 8 +- frontend/test/newsletter-blocks.test.mjs | 90 +++++++ 4 files changed, 419 insertions(+), 1 deletion(-) create mode 100644 frontend/src/surfaces/operations/newsletter-blocks.js create mode 100644 frontend/test/newsletter-blocks.test.mjs diff --git a/frontend/src/styles/planner.css b/frontend/src/styles/planner.css index 25fa9763..8a68509b 100644 --- a/frontend/src/styles/planner.css +++ b/frontend/src/styles/planner.css @@ -1188,3 +1188,71 @@ a.calendar-day-timeline-title:hover { color: var(--dk-accent-default, inherit); text-decoration: underline; } + +/* Issue page: editable content blocks (operations/newsletter-blocks.js). */ +.newsletter-blocks { + display: grid; + max-width: 860px; + margin-top: var(--dk-space-6); + gap: var(--dk-space-3); +} +.newsletter-blocks__title { + margin: 0; + font-size: var(--dk-text-lg); +} +.newsletter-blocks__status:empty { + display: none; +} +.newsletter-blocks__status[data-tone="danger"] { + color: var(--dk-danger-text); +} +.newsletter-blocks__status[data-tone="success"] { + color: var(--dk-success-text); +} +.newsletter-blocks__bar, +.newsletter-blocks__head, +.newsletter-blocks__actions { + display: flex; + flex-wrap: wrap; + gap: var(--dk-space-2); + align-items: center; +} +.newsletter-blocks__list, +.newsletter-blocks__block, +.newsletter-blocks__import { + display: grid; + gap: var(--dk-space-3); +} +.newsletter-blocks__block { + padding: var(--dk-space-4); +} +.newsletter-blocks__meta { + color: var(--dk-text-muted); + font-size: var(--dk-text-sm); +} +.newsletter-blocks__field { + display: grid; + gap: var(--dk-space-1); +} +.newsletter-blocks__plan { + margin: 0; + padding-left: var(--dk-space-5); + font-size: var(--dk-text-sm); +} +.newsletter-blocks__conflict { + color: var(--dk-danger-text); + font-weight: 600; +} +.newsletter-blocks__revision pre { + margin: var(--dk-space-1) 0; + padding: var(--dk-space-2); + border-radius: var(--dk-radius-sm); + font-size: var(--dk-text-sm); + white-space: pre-wrap; +} +.newsletter-blocks__before { + background: var(--dk-danger-bg); +} +.newsletter-blocks__after { + background: var(--dk-success-bg); +} diff --git a/frontend/src/surfaces/operations/newsletter-blocks.js b/frontend/src/surfaces/operations/newsletter-blocks.js new file mode 100644 index 00000000..90e43e42 --- /dev/null +++ b/frontend/src/surfaces/operations/newsletter-blocks.js @@ -0,0 +1,254 @@ +// The issue page's "Content blocks" section: every block of the newsletter +// issue (intro, sponsor, event spotlight, course updates, events list, +// recording, article...) as an editable form, with per-block history and the +// two-way Relay sync. Edits save to DataOps (one revision each); "Sync with +// Relay" pushes DataOps edits and pulls Relay edits, and is refused as a whole +// when a block changed on both sides. + +const enc = encodeURIComponent; +const MULTILINE = new Set(["markdown", "lines", "html"]); + +function formatWhen(iso) { + if (!iso) return ""; + return String(iso).slice(0, 16).replace("T", " "); +} + +export function createNewsletterBlocksSection({ documentRef, request, workApiUrl }) { + const el = (tag, className, text) => { + const node = (documentRef || globalThis.document).createElement(tag); + if (className) node.className = className; + if (text !== undefined) node.textContent = text; + return node; + }; + const button = (label, variant, action) => { + const node = el("button", `dk-button dk-button--sm${variant ? ` dk-button--${variant}` : ""}`, label); + node.type = "button"; + if (action) node.dataset.blocksAction = action; + return node; + }; + + async function mount(container, issueId) { + const base = workApiUrl(`/api/newsletter-issues/${enc(issueId)}/blocks`); + const section = el("section", "newsletter-blocks"); + section.dataset.newsletterBlocks = ""; + section.setAttribute("aria-labelledby", "newsletter-blocks-title"); + const heading = el("h2", "newsletter-blocks__title", "Content blocks"); + heading.id = "newsletter-blocks-title"; + const status = el("p", "newsletter-blocks__status"); + status.setAttribute("role", "status"); + status.dataset.blocksStatus = ""; + const body = el("div", "newsletter-blocks__body"); + section.append(heading, status, body); + container.append(section); + + let set = null; + + function say(message, tone = "info") { + status.textContent = message; + status.dataset.tone = tone; + } + + function renderImport() { + body.replaceChildren(); + const form = el("form", "newsletter-blocks__import"); + form.dataset.blocksImport = ""; + const keyLabel = el("label", "dk-label", "Relay issue key"); + const key = el("input", "dk-input"); + key.name = "issueKey"; + key.placeholder = "weekly-304"; + key.required = true; + keyLabel.append(key); + const targetLabel = el("label", "dk-label", "Relay"); + const target = el("select", "dk-select"); + target.name = "target"; + for (const value of ["production", "dev"]) { + const option = el("option", "", value); + option.value = value; + target.append(option); + } + targetLabel.append(target); + const submit = button("Import blocks from Relay", "primary"); + submit.type = "submit"; + form.append(el("p", "dk-hint", "This issue has no blocks in DataOps yet. Import them once from its Relay issue."), keyLabel, targetLabel, submit); + form.addEventListener("submit", async (event) => { + event.preventDefault(); + submit.disabled = true; + say("Importing blocks from Relay…"); + try { + const result = await request(`${base}/import`, { + method: "POST", + body: JSON.stringify({ issueKey: key.value.trim(), target: target.value }), + }); + set = result.blocks; + say(`Imported ${set.blocks.length} blocks from Relay ${set.relay.target} ${set.relay.issueKey}.`, "success"); + renderSet(); + } catch (error) { + say(`Import failed: ${error.message}`, "danger"); + submit.disabled = false; + } + }); + body.append(form); + } + + function syncReport(result) { + const list = el("ul", "newsletter-blocks__plan"); + list.dataset.blocksPlan = ""; + for (const step of result.plan || result.conflicts || []) { + const item = el("li", step.action === "conflict" ? "newsletter-blocks__conflict" : ""); + item.textContent = `#${step.relayBlockId} ${step.type}: ${step.action} (${step.reason})`; + list.append(item); + } + return list; + } + + async function runSync(dryRun, report) { + say(dryRun ? "Comparing with Relay…" : "Syncing with Relay…"); + report.replaceChildren(); + try { + const result = await request(`${base}/sync`, { method: "POST", body: JSON.stringify({ dryRun }) }); + report.append(syncReport(result)); + if (!dryRun) { + set = result.blocks; + renderSet(); + say(`Synced with Relay: pushed ${result.pushed.length}, pulled ${result.pulled.length}.`, "success"); + return; + } + say(`Relay check: ${result.summary}. Nothing written.`); + } catch (error) { + say(error.message, "danger"); + if (error.payload?.plan || error.payload?.conflicts) report.append(syncReport(error.payload)); + } + } + + function fieldControl(block, field) { + const wrap = el("label", "dk-label newsletter-blocks__field"); + wrap.append(el("span", "", `${field.label}${field.required ? " *" : ""}`)); + const multiline = MULTILINE.has(field.kind); + const input = el(multiline ? "textarea" : "input", multiline ? "dk-textarea" : "dk-input"); + input.name = field.name; + input.value = block.data?.[field.name] || ""; + if (!multiline) input.type = field.kind === "url" ? "url" : "text"; + if (multiline) input.rows = Math.min(14, Math.max(3, input.value.split("\n").length + 1)); + if (field.default) input.placeholder = field.default; + input.dataset.blockField = field.name; + wrap.append(input); + return wrap; + } + + async function showHistory(block, target) { + target.replaceChildren(el("p", "dk-hint", "Loading history…")); + try { + const result = await request(`${base}/revisions?block=${enc(String(block.relayBlockId))}`); + target.replaceChildren(); + for (const rev of [...result.revisions].reverse()) { + const who = rev.origin.startsWith("relay") ? `Relay (${rev.relayActor || "?"})` : rev.actorName || "?"; + const entry = el("details", "newsletter-blocks__revision"); + entry.append(el("summary", "", `rev ${rev.revision} · ${rev.origin} · ${who} · ${formatWhen(rev.createdAt)} · ${rev.changes.map((c) => c.field).join(", ") || "no changes"}`)); + for (const change of rev.changes) { + entry.append(el("strong", "", change.field)); + if (rev.before) entry.append(el("pre", "newsletter-blocks__before", change.before || "(empty)")); + entry.append(el("pre", "newsletter-blocks__after", change.after || "(empty)")); + } + target.append(entry); + } + if (!result.revisions.length) target.append(el("p", "dk-hint", "No revisions.")); + } catch (error) { + target.replaceChildren(el("p", "dk-field-error", `History unavailable: ${error.message}`)); + } + } + + function blockCard(block) { + const form = el("form", "dk-card newsletter-blocks__block"); + form.dataset.blockId = block.id; + const head = el("div", "newsletter-blocks__head"); + head.append(el("strong", "", block.label)); + head.append(el("span", "dk-mono newsletter-blocks__meta", `${block.type} · Relay #${block.relayBlockId} · v${block.version}`)); + const badge = el( + "span", + `dk-badge ${block.changedSinceSync ? "dk-badge--warning" : "dk-badge--success"}`, + block.changedSinceSync ? "Edited, not synced" : "In sync", + ); + badge.dataset.blockState = block.changedSinceSync ? "edited" : "in-sync"; + head.append(badge); + if (block.updatedByName) head.append(el("span", "dk-hint", `Last change: ${block.updatedByName}, ${formatWhen(block.updatedAt)}`)); + form.append(head); + for (const field of block.fields || []) form.append(fieldControl(block, field)); + const error = el("p", "dk-field-error"); + error.hidden = true; + const actions = el("div", "newsletter-blocks__actions"); + const save = button("Save block", "primary", "save"); + save.type = "submit"; + const historyBtn = button("History", "secondary", "history"); + const history = el("div", "newsletter-blocks__history"); + actions.append(save, historyBtn); + form.append(error, actions, history); + historyBtn.addEventListener("click", () => showHistory(block, history)); + form.addEventListener("submit", async (event) => { + event.preventDefault(); + const data = {}; + for (const input of form.querySelectorAll("[data-block-field]")) data[input.name] = input.value; + save.disabled = true; + error.hidden = true; + try { + const result = await request(`${base}/${enc(block.id)}`, { + method: "PUT", + body: JSON.stringify({ version: block.version, data }), + }); + set = result.blocks; + renderSet(); + say(result.changed ? `Saved ${block.label}. Sync with Relay to publish it there.` : `${block.label}: no changes.`, "success"); + } catch (failure) { + const fields = failure.payload?.fields ? ` (${Object.entries(failure.payload.fields).map(([k, v]) => `${k}: ${v}`).join(", ")})` : ""; + error.textContent = `${failure.message}${fields}`; + error.hidden = false; + save.disabled = false; + } + }); + return form; + } + + function renderSet() { + body.replaceChildren(); + const bar = el("div", "newsletter-blocks__bar"); + const pending = set.blocks.filter((block) => block.changedSinceSync).length; + bar.append( + el( + "span", + "", + `Relay ${set.relay.target} · ${set.relay.issueKey} · ${set.blocks.length} blocks${pending ? ` · ${pending} edited, not synced` : ""}`, + ), + ); + if (set.relayIssue?.subject) bar.append(el("span", "dk-hint", `Subject: ${set.relayIssue.subject}`)); + if (set.lastSync) bar.append(el("span", "dk-hint", `Last sync ${formatWhen(set.lastSync.at)} by ${set.lastSync.byName || "?"}: ${set.lastSync.summary}`)); + const check = button("Check Relay", "secondary", "check"); + const sync = button("Sync with Relay", "primary", "sync"); + const report = el("div", "newsletter-blocks__report"); + check.addEventListener("click", () => runSync(true, report)); + sync.addEventListener("click", () => runSync(false, report)); + const actions = el("div", "newsletter-blocks__actions"); + actions.append(check, sync); + bar.append(actions); + body.append(bar, report); + const list = el("div", "newsletter-blocks__list"); + for (const block of set.blocks) list.append(blockCard(block)); + body.append(list); + } + + say("Loading content blocks…"); + try { + set = (await request(base)).blocks; + say(""); + renderSet(); + } catch (error) { + if (error.code === "blocks_not_imported") { + say(""); + renderImport(); + } else { + say(`Content blocks unavailable: ${error.message}`, "danger"); + } + } + return section; + } + + return { mount }; +} diff --git a/frontend/src/surfaces/planning-newsletter-issue.js b/frontend/src/surfaces/planning-newsletter-issue.js index caa324f9..4c80768e 100644 --- a/frontend/src/surfaces/planning-newsletter-issue.js +++ b/frontend/src/surfaces/planning-newsletter-issue.js @@ -1,9 +1,11 @@ // The per-issue page at /newsletter/: one newsletter issue's // details, reached from the planner's rows and addressable as a deep link. -// Read-only: the planner's rows and its dialog stay the editing surfaces. +// The issue facts are read-only (the planner's rows and dialog edit them); +// the content blocks below them are edited here (operations/newsletter-blocks.js). import { formatIssueDate } from "../core/dates.js"; import { sponsorRecordPath } from "../core/sponsor-routes.js"; import { renderPageHeaderMarkup } from "./operations-overview.js"; +import { createNewsletterBlocksSection } from "./operations/newsletter-blocks.js"; import { SLOT_POSITIONS, cardDueLabel, @@ -27,6 +29,8 @@ export function createNewsletterIssuePage(context) { workApiUrl, } = context; + const blocksSection = createNewsletterBlocksSection({ request, workApiUrl }); + function routeIssueId() { return getActiveWorkspaceRoute?.()?.params?.get("issueId") || ""; } @@ -176,6 +180,8 @@ export function createNewsletterIssuePage(context) { status.textContent = ""; surface.querySelector("#newsletter-issue-title").textContent = item.label || "Newsletter issue"; body.innerHTML = readyMarkup(item); + // The blocks load on their own and report their own failures in place. + blocksSection.mount(body, item.id).catch((error) => console.error("Newsletter blocks failed to render:", error)); return true; } diff --git a/frontend/test/newsletter-blocks.test.mjs b/frontend/test/newsletter-blocks.test.mjs new file mode 100644 index 00000000..71a5d8eb --- /dev/null +++ b/frontend/test/newsletter-blocks.test.mjs @@ -0,0 +1,90 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { createNewsletterBlocksSection } from "../src/surfaces/operations/newsletter-blocks.js"; +import { FakeDocument, FakeElement, findByText } from "./support/fake-dom.mjs"; + +const field = (name, kind = "text", required = false) => ({ name, label: name, kind, required, default: "" }); +const blockSet = (overrides = {}) => ({ + issueId: "iss", + relay: { target: "production", issueKey: "weekly-304" }, + relayIssue: { subject: "Weekly 304" }, + lastSync: null, + blocks: [ + { id: "rb-113", relayBlockId: 113, type: "intro", label: "Intro", version: 1, data: { summary: "Hello" }, fields: [field("issue_label"), field("summary", "markdown", true)], changedSinceSync: false }, + { id: "rb-114", relayBlockId: 114, type: "sponsor", label: "Sponsor (main)", version: 3, data: { title: "Acme" }, fields: [field("title"), field("cta_url", "url")], changedSinceSync: true }, + ], + ...overrides, +}); + +function setup(routes) { + const documentRef = new FakeDocument(); + const calls = []; + const request = async (url, options = {}) => { + const method = options.method || "GET"; + calls.push({ method, url, body: options.body ? JSON.parse(options.body) : undefined }); + const handler = routes[`${method} ${url}`]; + if (!handler) throw Object.assign(new Error(`no route ${method} ${url}`), { status: 404 }); + return handler(calls.at(-1)); + }; + const section = createNewsletterBlocksSection({ documentRef, request, workApiUrl: (path) => path }); + return { section, calls, container: new FakeElement("div") }; +} + +const BASE = "/api/newsletter-issues/iss/blocks"; + +test("renders every block as an editable form with its sync state", async () => { + const { section, container } = setup({ [`GET ${BASE}`]: () => ({ blocks: blockSet() }) }); + await section.mount(container, "iss"); + const forms = container.querySelectorAll("[data-block-id]"); + assert.deepEqual(forms.map((form) => form.dataset.blockId), ["rb-113", "rb-114"]); + const summary = forms[0].querySelectorAll("[data-block-field]").find((input) => input.name === "summary"); + assert.equal(summary.tagName, "TEXTAREA"); + assert.equal(summary.value, "Hello"); + assert.equal(forms[1].querySelector("[data-block-state]").textContent, "Edited, not synced"); + assert.ok(findByText(container, "Relay production · weekly-304 · 2 blocks · 1 edited, not synced")); +}); + +test("saving sends the block version and the edited fields", async () => { + const { section, calls, container } = setup({ + [`GET ${BASE}`]: () => ({ blocks: blockSet() }), + [`PUT ${BASE}/rb-113`]: () => ({ changed: true, blocks: blockSet() }), + }); + await section.mount(container, "iss"); + const form = container.querySelectorAll("[data-block-id]")[0]; + form.querySelectorAll("[data-block-field]").find((input) => input.name === "summary").value = "Edited"; + await form.dispatch("submit"); + assert.deepEqual(calls.at(-1).body, { version: 1, data: { issue_label: "", summary: "Edited" } }); + assert.match(container.querySelector("[data-blocks-status]").textContent, /Saved Intro/); +}); + +test("a refused sync shows the conflict loudly and keeps the edits", async () => { + const conflict = Object.assign(new Error("Sync refused: 1 block(s) changed both in DataOps and in Relay since the last sync."), { + status: 409, + payload: { conflicts: [{ relayBlockId: 114, type: "sponsor", action: "conflict", reason: "edited in DataOps and in Relay" }] }, + }); + const { section, container } = setup({ + [`GET ${BASE}`]: () => ({ blocks: blockSet() }), + [`POST ${BASE}/sync`]: () => { throw conflict; }, + }); + await section.mount(container, "iss"); + await container.querySelector('[data-blocks-action="sync"]').click(); + const status = container.querySelector("[data-blocks-status]"); + assert.equal(status.dataset.tone, "danger"); + assert.match(status.textContent, /Sync refused/); + assert.ok(findByText(container, "#114 sponsor: conflict (edited in DataOps and in Relay)")); +}); + +test("offers an import from Relay when the issue has no blocks yet", async () => { + const notImported = Object.assign(new Error("no blocks"), { status: 404, code: "blocks_not_imported" }); + const { section, calls, container } = setup({ + [`GET ${BASE}`]: () => { throw notImported; }, + [`POST ${BASE}/import`]: () => ({ blocks: blockSet() }), + }); + await section.mount(container, "iss"); + const form = container.querySelector("[data-blocks-import]"); + form.querySelector('[name="issueKey"]').value = "weekly-304"; + form.querySelector('[name="target"]').value = "dev"; + await form.dispatch("submit"); + assert.deepEqual(calls.at(-1).body, { issueKey: "weekly-304", target: "dev" }); + assert.equal(container.querySelectorAll("[data-block-id]").length, 2); +}); From 7572b14570415735484f0740beee880d9a4b65f3 Mon Sep 17 00:00:00 2001 From: Alexey Grigorev Date: Mon, 23 Nov 2026 13:23:11 +0100 Subject: [PATCH 04/12] Register newsletter-blocks surface in the frontend asset manifest --- backend/src/docs/frontend-assets.json | 1 + 1 file changed, 1 insertion(+) diff --git a/backend/src/docs/frontend-assets.json b/backend/src/docs/frontend-assets.json index 47a844cd..4f92f0ca 100644 --- a/backend/src/docs/frontend-assets.json +++ b/backend/src/docs/frontend-assets.json @@ -165,6 +165,7 @@ "src/surfaces/operations/contract-sign.js", "src/surfaces/operations/index.js", "src/surfaces/operations/newsletter-preview.js", + "src/surfaces/operations/newsletter-blocks.js", "src/surfaces/operations/sponsor-doc-bullets.js", "src/surfaces/operations/sponsor-doc-visual.js", "src/surfaces/operations/sponsor-doc-email-card.js", From 0fc808d35e03346da7e23b493deed0175ae7b4cf Mon Sep 17 00:00:00 2001 From: Alexey Grigorev Date: Mon, 23 Nov 2026 13:29:57 +0100 Subject: [PATCH 05/12] CLI: newsletter block list/show/add/edit/move/delete, block-types, sponsor-sync --- cli/skill/SKILL.md | 2 + cli/src/cli.mjs | 2 +- cli/src/commands/newsletter.mjs | 7 +- cli/src/commands/newsletterBlocks.mjs | 219 +++++++++++++++++++++++++- cli/test/newsletter-blocks.test.mjs | 91 +++++++++++ 5 files changed, 317 insertions(+), 4 deletions(-) diff --git a/cli/skill/SKILL.md b/cli/skill/SKILL.md index f3c37bb9..d64e082b 100644 --- a/cli/skill/SKILL.md +++ b/cli/skill/SKILL.md @@ -289,6 +289,8 @@ Use `dataops newsletter markdown show [issue|sources|brief]` to read `dataops newsletter markdown rotate-code ` to rotate the preview access code. To put the sponsor copy into the Relay email, run `dataops newsletter relay-sync --slot primary|secondary` (add `--dry-run` first). It maps the slot's sponsor document (title, kicker, body, bullets, closing, image, CTA) into the Relay issue's sponsor block with one per-block write (under the ~8 KB CloudFront WAF body limit), updating the existing block rather than adding another. The Relay issue key comes from `final-render --relay-key`, or pass `--relay-key`. +Issue content blocks (intro, spotlight, courses, events, recording, article, sponsor) are edited in DataOps: `dataops newsletter block list|show|add|edit|move|delete ...`, `block-types `, `blocks-sync [--dry-run]` (two-way, per block; conflicts refuse the whole sync), `revisions [--block ] [--diff]` (who changed what). Adds, moves and deletes reach Relay on the next `blocks-sync`. Sponsor blocks are special: the main one is pinned first (no move/delete, nothing above it), secondary ones can move but not be deleted, and both are read-only here: edit the sponsor doc, and every doc save syncs the block (`sponsor-sync --slot primary|secondary [--dry-run] [--force]` re-runs it). Refusals print the server message and exit non-zero. + Use `dataops newsletter image upload ` to upload a newsletter image (PNG, JPEG, GIF, or WebP) to durable public hosting and print its public `https://` URL for `issue.md` and the HTML preview. For a podcast episode: `dataops podcast list --status booked` (or `--season N`), diff --git a/cli/src/cli.mjs b/cli/src/cli.mjs index 42771138..410124c7 100644 --- a/cli/src/cli.mjs +++ b/cli/src/cli.mjs @@ -303,7 +303,7 @@ export async function run(argv, io = console) { print(sponsorDocs.newsletterDocHelp); return EXIT.ok; } - if (commandName === "newsletter" && ["blocks", "block-edit", "blocks-sync", "revisions"].includes(rest[0])) { + if (commandName === "newsletter" && ["blocks", "block", "block-edit", "block-types", "blocks-sync", "sponsor-sync", "revisions"].includes(rest[0])) { print(newsletter.blocksHelp); return EXIT.ok; } diff --git a/cli/src/commands/newsletter.mjs b/cli/src/commands/newsletter.mjs index d67882ce..3d22c4ca 100644 --- a/cli/src/commands/newsletter.mjs +++ b/cli/src/commands/newsletter.mjs @@ -6,7 +6,7 @@ import { apiFor } from "../session.mjs"; import { planNewsletterSync, readNewsletterCsv, sheetIssues } from "../newsletterSheet.mjs"; import { rewriteVerificationUri } from "./auth.mjs"; import { relaySync, relaySyncHelp } from "./newsletterRelay.mjs"; -import { blockEdit, blocks, blocksHelp, blocksSync, revisions } from "./newsletterBlocks.mjs"; +import { blockCommand, blockEdit, blockTypes, blocks, blocksHelp, blocksSync, revisions, sponsorSync } from "./newsletterBlocks.mjs"; import { domainDocCommand } from "./sponsorDocs.mjs"; import { multipart } from "./tasks.mjs"; @@ -84,6 +84,8 @@ Usage dataops newsletter blocks [--show] [--import [--target production|dev]] dataops newsletter block-edit --field --value dataops newsletter blocks-sync [--dry-run] + dataops newsletter block list|show|add|edit|move|delete ... (block-types lists the types) + dataops newsletter sponsor-sync --slot primary|secondary [--dry-run] [--force] dataops newsletter revisions [--block ] [--diff] [--rev N] Every content block of the issue (intro, sponsor, events, recording, article...), editable here and on the issue page; @@ -1190,6 +1192,9 @@ export const commands = { blocks, "block-edit": blockEdit, "blocks-sync": blocksSync, + block: blockCommand, + "block-types": blockTypes, + "sponsor-sync": sponsorSync, revisions, metrics, "pull-mailchimp": pullMailchimp, diff --git a/cli/src/commands/newsletterBlocks.mjs b/cli/src/commands/newsletterBlocks.mjs index 096f5e81..bbd6eb9a 100644 --- a/cli/src/commands/newsletterBlocks.mjs +++ b/cli/src/commands/newsletterBlocks.mjs @@ -16,7 +16,16 @@ Usage dataops newsletter block-edit --field --value-file dataops newsletter block-edit --data-file dataops newsletter blocks-sync [--dry-run] [--json] - dataops newsletter revisions [--block ] [--origin edit|import|relay-pull] + dataops newsletter block list [--show] + dataops newsletter block show + dataops newsletter block add --type [--position N] + [--field name=value ...] [--data-file ] + dataops newsletter block edit --field name=value ... | --data-file + dataops newsletter block move (--up | --down | --to N) + dataops newsletter block delete --yes + dataops newsletter block-types [--json] + dataops newsletter sponsor-sync --slot primary|secondary [--dry-run] [--force] + dataops newsletter revisions [--block ] [--origin edit|import|relay-pull|add|move|delete|sponsor-doc] [--diff] [--rev N] [--json] Every block of the issue (intro, sponsor, event spotlight, course updates, @@ -29,6 +38,20 @@ agreed on: blocks edited only in DataOps are pushed, blocks edited only in Relay are pulled. A block edited on both sides is a conflict and the whole sync is refused before anything is written. --dry-run shows the plan. Pushing is refused once the Relay campaign has left draft. Nothing is sent. + +Adding, moving and deleting blocks is local until the next blocks-sync, which +creates, reorders and deletes the blocks in Relay (DataOps is the source of +truth for structure; a Relay-side change to the same block is a conflict). + +Sponsor blocks follow the sponsor document, not the editor: + - the main sponsor block is pinned as the first content block: it cannot be + moved or deleted, and nothing can be placed above it; + - secondary sponsor blocks can be moved but not deleted (they go away when the + slot is removed from the document); + - sponsor block content is read-only here: edit it in the sponsor document; + every sponsor-doc save syncs it. "sponsor-sync" re-runs that sync by hand + (--force overwrites a block changed in Relay after the last sync). +Refusals print the server's message and exit non-zero. `; function blockRow(block) { @@ -133,6 +156,7 @@ export async function blocksSync(args, io) { function who(rev) { if (rev.origin === "relay-pull" || rev.origin === "relay-remove") return `Relay: ${rev.relayActor || "?"}`; + if (rev.origin === "sponsor-doc") return "sponsor doc"; return rev.actorName || rev.actorUserId || "?"; } @@ -163,7 +187,7 @@ export async function revisions(args, io) { ["BLOCK", (r) => `${r.blockId} ${r.blockType}`], ["ORIGIN", (r) => r.origin], ["BY", who], - ["CHANGED", (r) => r.changes.map((c) => c.field).join(", ") || "(none)"], + ["CHANGED", (r) => r.changes.map((c) => c.field).join(", ") || r.detail || "(none)"], ], `No revisions for issue ${issue}.`, ); @@ -171,6 +195,7 @@ export async function revisions(args, io) { } for (const rev of list) { io.print(`=== rev ${rev.revision} · ${rev.blockId} ${rev.label} · ${rev.origin} by ${who(rev)} · ${rev.createdAt}`); + if (rev.detail) io.print(rev.detail); if (!rev.changes.length) io.print("(no field changes)"); for (const change of rev.changes) { io.print(`--- ${change.field} [before]`); @@ -184,3 +209,193 @@ export async function revisions(args, io) { } return { ...result, revisions: list }; } + +const issueArg = (args, usage) => String(positional(args, 0, usage)); +const blocksUrl = (issue, tail = "") => `/api/newsletter-issues/${enc(issue)}/blocks${tail}`; + +function parseFieldPairs(args) { + const raw = args.field === undefined ? [] : Array.isArray(args.field) ? args.field : [args.field]; + const data = {}; + for (const pair of raw) { + const text = String(pair); + const at = text.indexOf("="); + if (at < 1) throw new UsageError(`--field expects name=value, got "${text}".`); + data[text.slice(0, at)] = text.slice(at + 1); + } + return data; +} + +function dataFromArgs(args) { + const dataFile = optionalString(args, "dataFile"); + return dataFile ? JSON.parse(readFileSync(dataFile, "utf8")) : parseFieldPairs(args); +} + +function findBlock(set, ref) { + const block = set.blocks.find((item) => item.id === ref || String(item.relayBlockId) === ref); + if (!block) throw new UsageError(`No block ${ref}. Blocks: ${set.blocks.map((b) => b.id).join(", ")}`); + return block; +} + +function stateLabel(block) { + const state = block.pushState || (block.changedSinceSync ? "edited" : "in-sync"); + return { new: "new, not in Relay", edited: "edited, not pushed", "in-sync": "in sync" }[state] || state; +} + +function printBlock(io, block) { + io.print(`## ${block.id} · ${block.label} (v${block.version}) · ${stateLabel(block)}`); + if (block.sponsor) io.print(`sponsor block (${block.sponsor}): read-only here, edit in the sponsor doc${block.sponsorDocUrl ? ` ${block.sponsorDocUrl}` : ""}`); + for (const [name, value] of Object.entries(block.data || {})) io.print(`${name}: ${String(value).replace(/\n/g, "\n ")}`); +} + +export async function blockCommand(args, io) { + const usage = "dataops newsletter block list|show|add|edit|move|delete ..."; + const action = String(positional(args, 0, usage)); + const sub = { ...args, _: args._.slice(1) }; + const handler = { list: blockList, show: blockShow, add: blockAdd, edit: blockEditV2, move: blockMove, delete: blockDelete }[action]; + if (!handler) throw new UsageError(`Unknown block action "${action}". ${usage}`); + return handler(sub, io); +} + +async function blockList(args, io) { + const usage = "dataops newsletter block list [--show]"; + const result = await apiFor(args).get(blocksUrl(issueArg(args, usage))); + if (args.json) return result; + const set = result.blocks; + io.print(`relay: ${set.relay.target} ${set.relay.issueKey} · subject: ${set.relayIssue?.subject || ""}`); + if (set.orderChanged) io.print("order changed in DataOps, not pushed to Relay yet"); + for (const gone of set.deletedPending || []) io.print(`deleted in DataOps, still in Relay until sync: ${gone.id} ${gone.type}`); + table( + io, + set.blocks.map(blockRow), + [ + ["POS", (b) => String(b.position)], + ["ID", (b) => b.id], + ["TYPE", (b) => b.type], + ["V", (b) => String(b.version)], + ["STATE", stateLabel], + ["RULE", (b) => (b.pinned ? "pinned" : b.sponsor ? "sponsor doc only" : "")], + ["CONTENT", (b) => b.preview], + ], + "No blocks.", + ); + if (args.show) for (const block of set.blocks) { io.print(""); printBlock(io, block); } + return result; +} + +async function blockShow(args, io) { + const usage = "dataops newsletter block show "; + const result = await apiFor(args).get(blocksUrl(issueArg(args, usage))); + const block = findBlock(result.blocks, String(positional(args, 1, usage))); + if (args.json) return { block }; + printBlock(io, block); + return { block }; +} + +async function blockAdd(args, io) { + const usage = "dataops newsletter block add --type [--position N] [--field name=value ...]"; + const issue = issueArg(args, usage); + const type = optionalString(args, "type"); + if (!type) throw new UsageError(`--type is required (see: dataops newsletter block-types). Usage: ${usage}`); + const body = { type, data: dataFromArgs(args) }; + if (args.position !== undefined) { + if (!/^\d+$/.test(String(args.position))) throw new UsageError(`--position must be a non-negative integer, got "${args.position}".`); + body.position = Number(args.position); + } + const result = await apiFor(args).post(blocksUrl(issue), body); + if (args.json) return result; + const added = result.block || result.blocks.blocks.find((b) => b.type === type); + io.print(`added ${added?.id || type} at position ${added?.position ?? "end"} (not in Relay yet; run blocks-sync)`); + return result; +} + +async function blockEditV2(args, io) { + const usage = "dataops newsletter block edit (--field name=value ... | --data-file )"; + const issue = issueArg(args, usage); + const ref = String(positional(args, 1, usage)); + const api = apiFor(args); + const block = findBlock((await api.get(blocksUrl(issue))).blocks, ref); + let data; + if (optionalString(args, "dataFile")) { + data = dataFromArgs(args); + } else { + const single = typeof args.field === "string" && !args.field.includes("="); + if (single) { + const valueFile = optionalString(args, "valueFile"); + const value = valueFile ? readFileSync(valueFile, "utf8") : args.value; + if (typeof value !== "string") throw new UsageError(`Pass --value or --value-file . Usage: ${usage}`); + data = { ...block.data, [args.field]: value }; + } else { + const changes = parseFieldPairs(args); + if (!Object.keys(changes).length) throw new UsageError(`Nothing to change. Usage: ${usage}`); + data = { ...block.data, ...changes }; + } + } + const result = await api.put(blocksUrl(issue, `/${enc(block.id)}`), { version: block.version, data }); + if (args.json) return result; + io.print(result.changed ? `saved ${block.id} (not pushed to Relay yet; run blocks-sync)` : `${block.id} unchanged`); + return result; +} + +async function blockMove(args, io) { + const usage = "dataops newsletter block move (--up | --down | --to N)"; + const issue = issueArg(args, usage); + const ref = String(positional(args, 1, usage)); + const api = apiFor(args); + const block = findBlock((await api.get(blocksUrl(issue))).blocks, ref); + let body; + if (args.up) body = { direction: "up" }; + else if (args.down) body = { direction: "down" }; + else if (args.to !== undefined && /^\d+$/.test(String(args.to))) body = { to: Number(args.to) }; + else throw new UsageError(`Pass --up, --down or --to . Usage: ${usage}`); + const result = await api.post(blocksUrl(issue, `/${enc(block.id)}/move`), body); + if (args.json) return result; + const moved = result.blocks.blocks.find((item) => item.id === block.id); + io.print(`moved ${block.id} to position ${moved?.position} (not pushed to Relay yet; run blocks-sync)`); + return result; +} + +async function blockDelete(args, io) { + const usage = "dataops newsletter block delete --yes"; + const issue = issueArg(args, usage); + const ref = String(positional(args, 1, usage)); + const api = apiFor(args); + const block = findBlock((await api.get(blocksUrl(issue))).blocks, ref); + if (!args.yes) throw new UsageError(`Deleting ${block.id} (${block.label}) removes it from the issue and, on the next sync, from Relay. Re-run with --yes.`); + const result = await api.delete(blocksUrl(issue, `/${enc(block.id)}`)); + if (args.json) return result; + io.print(`deleted ${block.id} (removed from Relay on the next blocks-sync)`); + return result; +} + +export async function blockTypes(args, io) { + const result = await apiFor(args).get(blocksUrl(String(positional(args, 0, "dataops newsletter block-types ")), "/types")); + if (args.json) return result; + table( + io, + result.types, + [ + ["TYPE", (t) => t.type], + ["LABEL", (t) => t.label], + ["ADD", (t) => (t.addable ? "yes" : "sponsor doc only")], + ["FIELDS", (t) => t.fields.map((f) => `${f.name}${f.required ? "*" : ""}`).join(", ")], + ], + "No block types.", + ); + return result; +} + +export async function sponsorSync(args, io) { + const usage = "dataops newsletter sponsor-sync --slot primary|secondary [--dry-run] [--force]"; + const issue = issueArg(args, usage); + const slot = optionalString(args, "slot") || "primary"; + if (slot !== "primary" && slot !== "secondary") throw new UsageError("--slot must be primary or secondary."); + const result = await apiFor(args).post(blocksUrl(issue, "/sponsor-sync"), { + slot, + dryRun: Boolean(args.dryRun), + force: Boolean(args.force), + }); + if (args.json) return result; + const detail = result.result || result; + io.print(`sponsor-sync ${slot}: ${detail.summary || detail.action || "done"}${args.dryRun ? " (dry run, nothing written)" : ""}`); + return result; +} diff --git a/cli/test/newsletter-blocks.test.mjs b/cli/test/newsletter-blocks.test.mjs index 5788036f..85c399f5 100644 --- a/cli/test/newsletter-blocks.test.mjs +++ b/cli/test/newsletter-blocks.test.mjs @@ -69,3 +69,94 @@ describe("newsletter blocks CLI", () => { assert.doesNotMatch(diff.text(), /rev 1/); }); }); + +describe("newsletter block add/move/delete CLI", () => { + const sponsor = { ...intro, id: "rb-114", relayBlockId: 114, position: 1, type: "sponsor", label: "Sponsor (main)", sponsor: "primary", pinned: true, readOnly: true, data: { title: "Acme" } }; + const refusal = (code, error) => ({ status: 409, body: { error, code } }); + + test("block add posts type, position and fields", async () => { + const calls = fakePortal({ + "POST /api/newsletter-issues/304/blocks": () => ({ status: 201, block: { id: "nb-1", position: 2 }, ...set([intro]) }), + }); + const io = captureIo(); + const argv = ["newsletter", "block", "add", "304", "--type", "recording", "--position", "2", "--field", "title=Talk", "--field", "cta_url=https://x.io"]; + assert.equal(await run(argv, io), 0, io.errors.join("\n")); + assert.deepEqual(calls[0].body, { type: "recording", data: { title: "Talk", cta_url: "https://x.io" }, position: 2 }); + assert.match(io.text(), /added nb-1 at position 2/); + }); + + test("block add of a sponsor type prints the server refusal and fails", async () => { + fakePortal({ "POST /api/newsletter-issues/304/blocks": () => refusal("sponsor_block_doc_only", "Sponsor blocks come from the sponsor doc.") }); + const io = captureIo(); + assert.notEqual(await run(["newsletter", "block", "add", "304", "--type", "sponsor"], io), 0); + assert.match(io.errors.join("\n"), /Sponsor blocks come from the sponsor doc/); + }); + + test("block edit with name=value merges into the block's data", async () => { + const calls = fakePortal({ + "GET /api/newsletter-issues/304/blocks": () => set([intro]), + "PUT /api/newsletter-issues/304/blocks/rb-113": () => ({ changed: true, ...set([intro]) }), + }); + const io = captureIo(); + assert.equal(await run(["newsletter", "block", "edit", "304", "rb-113", "--field", "summary=Hi"], io), 0, io.errors.join("\n")); + assert.deepEqual(calls[1].body, { version: 1, data: { summary: "Hi" } }); + }); + + test("block edit of a sponsor block is refused loudly", async () => { + fakePortal({ + "GET /api/newsletter-issues/304/blocks": () => set([intro, sponsor]), + "PUT /api/newsletter-issues/304/blocks/rb-114": () => refusal("sponsor_block_readonly", "Sponsor content is edited in the sponsor doc."), + }); + const io = captureIo(); + assert.notEqual(await run(["newsletter", "block", "edit", "304", "rb-114", "--field", "title=X"], io), 0); + assert.match(io.errors.join("\n"), /edited in the sponsor doc/); + }); + + test("block move sends direction or index; pinned move is refused", async () => { + const calls = fakePortal({ + "GET /api/newsletter-issues/304/blocks": () => set([intro, sponsor]), + "POST /api/newsletter-issues/304/blocks/rb-113/move": () => set([{ ...intro, position: 1 }, { ...sponsor, position: 0 }]), + "POST /api/newsletter-issues/304/blocks/rb-114/move": () => refusal("sponsor_block_pinned", "The main sponsor block is pinned."), + }); + const io = captureIo(); + assert.equal(await run(["newsletter", "block", "move", "304", "rb-113", "--down"], io), 0, io.errors.join("\n")); + assert.deepEqual(calls[1].body, { direction: "down" }); + const bad = captureIo(); + assert.notEqual(await run(["newsletter", "block", "move", "304", "rb-114", "--to", "0"], bad), 0); + assert.deepEqual(calls.at(-1).body, { to: 0 }); + assert.match(bad.errors.join("\n"), /pinned/); + }); + + test("block delete needs --yes and surfaces the secondary-sponsor refusal", async () => { + const calls = fakePortal({ + "GET /api/newsletter-issues/304/blocks": () => set([intro]), + "DELETE /api/newsletter-issues/304/blocks/rb-113": () => set([]), + }); + const io = captureIo(); + assert.notEqual(await run(["newsletter", "block", "delete", "304", "rb-113"], io), 0); + assert.equal(calls.filter((c) => c.method === "DELETE").length, 0); + const ok = captureIo(); + assert.equal(await run(["newsletter", "block", "delete", "304", "rb-113", "--yes"], ok), 0, ok.errors.join("\n")); + assert.match(ok.text(), /deleted rb-113/); + }); + + test("sponsor-sync posts slot, dry-run and force", async () => { + const calls = fakePortal({ "POST /api/newsletter-issues/304/blocks/sponsor-sync": () => ({ result: { summary: "updated 1 block" } }) }); + const io = captureIo(); + assert.equal(await run(["newsletter", "sponsor-sync", "304", "--slot", "secondary", "--force"], io), 0, io.errors.join("\n")); + assert.deepEqual(calls[0].body, { slot: "secondary", dryRun: false, force: true }); + assert.match(io.text(), /sponsor-sync secondary: updated 1 block/); + }); + + test("revisions shows the detail of a move", async () => { + fakePortal({ + "GET /api/newsletter-issues/304/blocks/revisions": () => ({ + issueId: "iss-304", + revisions: [{ revision: 3, blockId: "rb-113", blockType: "intro", label: "Intro", origin: "move", detail: "moved 0 -> 2", createdAt: "2026-11-23T11:00:00Z", actorName: "Alexey", before: null, after: null, changes: [] }], + }), + }); + const io = captureIo(); + assert.equal(await run(["newsletter", "revisions", "304", "--diff"], io), 0, io.errors.join("\n")); + assert.match(io.text(), /moved 0 -> 2/); + }); +}); From 32731b6dc5da577912e710b1a39d639528132302 Mon Sep 17 00:00:00 2001 From: Alexey Grigorev Date: Mon, 23 Nov 2026 13:32:22 +0100 Subject: [PATCH 06/12] Newsletter block editor: add, move (buttons/drag), delete, sponsor read-only, Blocks tab on the preview page, sponsor-doc sync note --- backend/src/docs/frontend-assets.json | 4 + frontend/src/newsletter-preview-page.js | 1 + frontend/src/styles/planner.css | 25 +++ .../operations/newsletter-blocks-add.js | 83 ++++++++ .../operations/newsletter-blocks-card.js | 166 +++++++++++++++ .../operations/newsletter-blocks-dom.js | 53 +++++ .../surfaces/operations/newsletter-blocks.js | 200 +++++++----------- .../surfaces/operations/newsletter-preview.js | 12 +- .../operations/sponsor-doc-newsletter-sync.js | 16 ++ .../src/surfaces/operations/sponsor-docs.js | 4 + frontend/test/newsletter-blocks.test.mjs | 133 +++++++++++- .../test/sponsor-doc-newsletter-sync.test.mjs | 28 +++ 12 files changed, 597 insertions(+), 128 deletions(-) create mode 100644 frontend/src/surfaces/operations/newsletter-blocks-add.js create mode 100644 frontend/src/surfaces/operations/newsletter-blocks-card.js create mode 100644 frontend/src/surfaces/operations/newsletter-blocks-dom.js create mode 100644 frontend/src/surfaces/operations/sponsor-doc-newsletter-sync.js create mode 100644 frontend/test/sponsor-doc-newsletter-sync.test.mjs diff --git a/backend/src/docs/frontend-assets.json b/backend/src/docs/frontend-assets.json index 4f92f0ca..5d5e4f43 100644 --- a/backend/src/docs/frontend-assets.json +++ b/backend/src/docs/frontend-assets.json @@ -166,6 +166,10 @@ "src/surfaces/operations/index.js", "src/surfaces/operations/newsletter-preview.js", "src/surfaces/operations/newsletter-blocks.js", + "src/surfaces/operations/newsletter-blocks-add.js", + "src/surfaces/operations/newsletter-blocks-card.js", + "src/surfaces/operations/newsletter-blocks-dom.js", + "src/surfaces/operations/sponsor-doc-newsletter-sync.js", "src/surfaces/operations/sponsor-doc-bullets.js", "src/surfaces/operations/sponsor-doc-visual.js", "src/surfaces/operations/sponsor-doc-email-card.js", diff --git a/frontend/src/newsletter-preview-page.js b/frontend/src/newsletter-preview-page.js index f4893f2f..e967d282 100644 --- a/frontend/src/newsletter-preview-page.js +++ b/frontend/src/newsletter-preview-page.js @@ -17,6 +17,7 @@ async function request(path, options = {}) { if (!response.ok) { const error = new Error(data.error || "Newsletter preview request failed"); error.status = response.status; + error.payload = data; error.code = data.code || ""; error.retryAfter = Number(response.headers.get("retry-after")) || Number(data.retryAfterSeconds) || 60; throw error; diff --git a/frontend/src/styles/planner.css b/frontend/src/styles/planner.css index 8a68509b..5637a414 100644 --- a/frontend/src/styles/planner.css +++ b/frontend/src/styles/planner.css @@ -1256,3 +1256,28 @@ a.calendar-day-timeline-title:hover { .newsletter-blocks__after { background: var(--dk-success-bg); } + +/* Block editor: read-only sponsor values, add panel, draggable cards. */ +.newsletter-blocks__block[draggable="true"] { + cursor: grab; +} + +.newsletter-blocks__values { + display: grid; + gap: var(--space-1, 4px); +} + +.newsletter-blocks__values dt { + font-weight: 600; +} + +.newsletter-blocks__values dd { + margin: 0; + white-space: pre-wrap; +} + +.newsletter-blocks__add, +.newsletter-blocks__fields { + display: grid; + gap: var(--space-3, 12px); +} diff --git a/frontend/src/surfaces/operations/newsletter-blocks-add.js b/frontend/src/surfaces/operations/newsletter-blocks-add.js new file mode 100644 index 00000000..a7cf4740 --- /dev/null +++ b/frontend/src/surfaces/operations/newsletter-blocks-add.js @@ -0,0 +1,83 @@ +// "Add block" panel: pick a block type (from the Relay block-types mirror the +// server returns), fill its fields (prefilled with the type's defaults) and +// choose where it goes. + +import { collectFields, failureText, fieldControl } from "./newsletter-blocks-dom.js"; + +export function createAddPanel({ dom, request, base, onChange, onFail }) { + const panel = dom.el("div", "newsletter-blocks__add"); + panel.dataset.blocksAdd = ""; + let types = null; + + async function open(set) { + panel.replaceChildren(dom.el("p", "dk-hint", "Loading block types…")); + try { + types ||= (await request(`${base}/types`)).types.filter((item) => item.addable); + } catch (error) { + panel.replaceChildren(dom.el("p", "dk-field-error", `Block types unavailable: ${error.message}`)); + return; + } + const form = dom.el("form", "dk-card newsletter-blocks__block"); + form.dataset.blocksAddForm = ""; + const typeLabel = dom.el("label", "dk-label", "Block type"); + const typeSelect = dom.el("select", "dk-select"); + typeSelect.name = "type"; + for (const item of types) { + const option = dom.el("option", "", item.label); + option.value = item.type; + typeSelect.append(option); + } + typeSelect.value = types[0]?.type || ""; + typeLabel.append(typeSelect); + const posLabel = dom.el("label", "dk-label", "Position"); + const posSelect = dom.el("select", "dk-select"); + posSelect.name = "position"; + const end = dom.el("option", "", "At the end"); + end.value = ""; + posSelect.append(end); + const pinnedAt = set.blocks.findIndex((block) => block.pinned); + set.blocks.forEach((block, index) => { + if (index <= pinnedAt) return; + const option = dom.el("option", "", `Before ${block.label}`); + option.value = String(index); + posSelect.append(option); + }); + posLabel.append(posSelect); + const fieldsBox = dom.el("div", "newsletter-blocks__fields"); + const renderFields = () => { + const spec = types.find((item) => item.type === typeSelect.value); + fieldsBox.replaceChildren(); + for (const field of spec?.fields || []) fieldsBox.append(fieldControl(dom, field, field.default, false)); + }; + typeSelect.addEventListener("change", renderFields); + renderFields(); + const error = dom.el("p", "dk-field-error"); + error.hidden = true; + error.dataset.blockError = ""; + const submit = dom.button("Add block", "primary", "add-submit"); + submit.type = "submit"; + const cancel = dom.button("Cancel", "secondary", "add-cancel"); + cancel.addEventListener("click", () => panel.replaceChildren()); + form.append(typeLabel, posLabel, fieldsBox, error, submit, cancel); + form.addEventListener("submit", async (event) => { + event.preventDefault(); + submit.disabled = true; + error.hidden = true; + const body = { type: typeSelect.value, data: collectFields(fieldsBox) }; + if (posSelect.value !== "") body.position = Number(posSelect.value); + try { + const result = await request(base, { method: "POST", body: JSON.stringify(body) }); + panel.replaceChildren(); + onChange(result.blocks, "Block added. Sync with Relay to create it there."); + } catch (failure) { + error.textContent = failureText(failure); + error.hidden = false; + onFail(error.textContent); + submit.disabled = false; + } + }); + panel.replaceChildren(form); + } + + return { panel, open }; +} diff --git a/frontend/src/surfaces/operations/newsletter-blocks-card.js b/frontend/src/surfaces/operations/newsletter-blocks-card.js new file mode 100644 index 00000000..ae1504c2 --- /dev/null +++ b/frontend/src/surfaces/operations/newsletter-blocks-card.js @@ -0,0 +1,166 @@ +// One block of the issue editor: edit form (or read-only values for sponsor +// blocks), move/delete controls and the per-block revision history. + +import { collectFields, failureText, fieldControl, formatWhen } from "./newsletter-blocks-dom.js"; + +const STATE_LABELS = { new: "New, not in Relay", edited: "Edited, not synced", "in-sync": "In sync" }; + +export function pushState(block) { + return block.pushState || (block.changedSinceSync ? "edited" : "in-sync"); +} + +async function showHistory({ dom, request, base }, block, target) { + target.replaceChildren(dom.el("p", "dk-hint", "Loading history…")); + try { + const key = block.relayBlockId ?? block.id; + const result = await request(`${base}/revisions?block=${encodeURIComponent(String(key))}`); + target.replaceChildren(); + for (const rev of [...result.revisions].reverse()) { + const who = rev.origin.startsWith("relay") ? `Relay (${rev.relayActor || "?"})` : rev.actorName || "?"; + const fieldsChanged = rev.changes.map((c) => c.field).join(", ") || rev.detail || "no changes"; + const entry = dom.el("details", "newsletter-blocks__revision"); + entry.append(dom.el("summary", "", `rev ${rev.revision} · ${rev.origin} · ${who} · ${formatWhen(rev.createdAt)} · ${fieldsChanged}`)); + for (const change of rev.changes) { + entry.append(dom.el("strong", "", change.field)); + if (rev.before) entry.append(dom.el("pre", "newsletter-blocks__before", change.before || "(empty)")); + entry.append(dom.el("pre", "newsletter-blocks__after", change.after || "(empty)")); + } + target.append(entry); + } + if (!result.revisions.length) target.append(dom.el("p", "dk-hint", "No revisions.")); + } catch (error) { + target.replaceChildren(dom.el("p", "dk-field-error", `History unavailable: ${error.message}`)); + } +} + +function readOnlyValues(dom, block) { + const list = dom.el("dl", "newsletter-blocks__values"); + list.dataset.blockReadonly = ""; + for (const field of block.fields || []) { + const value = block.data?.[field.name]; + if (!value) continue; + list.append(dom.el("dt", "", field.label), dom.el("dd", "", value)); + } + return list; +} + +function deleteHint(block) { + if (block.canDelete) return "Delete this block"; + if (block.sponsor === "primary") return "The main sponsor block is pinned and cannot be deleted"; + if (block.sponsor) return "A secondary sponsor block is removed by removing the slot from its sponsor doc"; + return "This block cannot be deleted"; +} + +function moveHint(block, label) { + if (block.canMove === false) { + return block.sponsor === "primary" ? "The main sponsor block is pinned first and cannot be moved" : "This block cannot be moved"; + } + return label; +} + +/** + * ctx: { dom, request, base, confirmFn, onChange(set, message), onFail(message), onMove(block, body), onDelete(block) } + */ +export function renderBlockCard(ctx, block, index, count) { + const { dom } = ctx; + const form = dom.el("form", "dk-card newsletter-blocks__block"); + form.dataset.blockId = block.id; + if (block.canMove !== false) form.draggable = true; + const head = dom.el("div", "newsletter-blocks__head"); + head.append(dom.el("strong", "", block.label)); + const relayRef = block.relayBlockId ? `Relay #${block.relayBlockId}` : "not in Relay yet"; + head.append(dom.el("span", "dk-mono newsletter-blocks__meta", `${block.type} · ${relayRef} · v${block.version}`)); + const state = pushState(block); + const badge = dom.el("span", `dk-badge ${state === "in-sync" ? "dk-badge--success" : "dk-badge--warning"}`, STATE_LABELS[state]); + badge.dataset.blockState = state === "in-sync" ? "in-sync" : state; + head.append(badge); + if (block.pinned) head.append(dom.el("span", "dk-badge", "Pinned: first content block")); + if (block.updatedByName) head.append(dom.el("span", "dk-hint", `Last change: ${block.updatedByName}, ${formatWhen(block.updatedAt)}`)); + form.append(head); + + const error = dom.el("p", "dk-field-error"); + error.hidden = true; + error.dataset.blockError = ""; + const showError = (message) => { + error.textContent = message; + error.hidden = false; + ctx.onFail(message); + }; + + const actions = dom.el("div", "newsletter-blocks__actions"); + let save = null; + if (block.readOnly) { + form.append(readOnlyValues(dom, block)); + const note = dom.el("p", "dk-hint", "Sponsor block: its content comes only from the sponsor doc and syncs automatically on every doc save."); + form.append(note); + if (block.sponsorDocUrl) { + const link = dom.el("a", "dk-link", "Edit in sponsor doc"); + link.href = block.sponsorDocUrl; + link.dataset.sponsorDocLink = ""; + actions.append(link); + } + } else { + for (const field of block.fields || []) form.append(fieldControl(dom, field, block.data?.[field.name])); + save = dom.button("Save block", "primary", "save"); + save.type = "submit"; + actions.append(save); + } + + const up = dom.button("↑ Up", "secondary", "up"); + const down = dom.button("↓ Down", "secondary", "down"); + const remove = dom.button("Delete", "secondary", "delete"); + const historyBtn = dom.button("History", "secondary", "history"); + up.disabled = block.canMove === false || index === 0; + down.disabled = block.canMove === false || index === count - 1; + up.title = moveHint(block, "Move up"); + down.title = moveHint(block, "Move down"); + remove.disabled = block.canDelete === false; + remove.title = deleteHint(block); + actions.append(up, down, remove, historyBtn); + const history = dom.el("div", "newsletter-blocks__history"); + form.append(error, actions, history); + + const guarded = (run) => async (event) => { + error.hidden = true; + try { + await run(event); + } catch (failure) { + showError(failureText(failure)); + } + }; + up.addEventListener("click", guarded(() => ctx.onMove(block, { direction: "up" }))); + down.addEventListener("click", guarded(() => ctx.onMove(block, { direction: "down" }))); + remove.addEventListener("click", guarded(async () => { + if (!ctx.confirmFn(`Delete "${block.label}"? It is removed from Relay on the next sync.`)) return; + await ctx.onDelete(block); + })); + historyBtn.addEventListener("click", () => showHistory(ctx, block, history)); + form.addEventListener("dragstart", (event) => { + ctx.drag.id = block.id; + event.dataTransfer?.setData?.("text/plain", block.id); + }); + form.addEventListener("dragover", (event) => event.preventDefault()); + form.addEventListener("drop", guarded(async (event) => { + event.preventDefault(); + const dragged = ctx.drag.id; + ctx.drag.id = ""; + if (dragged && dragged !== block.id) await ctx.onMove({ id: dragged }, { to: index }); + })); + form.addEventListener("submit", async (event) => { + event.preventDefault(); + if (!save) return; + save.disabled = true; + error.hidden = true; + try { + const result = await ctx.request(`${ctx.base}/${encodeURIComponent(block.id)}`, { + method: "PUT", + body: JSON.stringify({ version: block.version, data: collectFields(form) }), + }); + ctx.onChange(result.blocks, result.changed ? `Saved ${block.label}. Sync with Relay to publish it there.` : `${block.label}: no changes.`); + } catch (failure) { + showError(failureText(failure)); + save.disabled = false; + } + }); + return form; +} diff --git a/frontend/src/surfaces/operations/newsletter-blocks-dom.js b/frontend/src/surfaces/operations/newsletter-blocks-dom.js new file mode 100644 index 00000000..ec2487b0 --- /dev/null +++ b/frontend/src/surfaces/operations/newsletter-blocks-dom.js @@ -0,0 +1,53 @@ +// Small DOM helpers shared by the newsletter blocks editor modules. + +export const MULTILINE = new Set(["markdown", "lines", "html"]); + +export function formatWhen(iso) { + if (!iso) return ""; + return String(iso).slice(0, 16).replace("T", " "); +} + +export function createDom(documentRef) { + const el = (tag, className, text) => { + const node = (documentRef || globalThis.document).createElement(tag); + if (className) node.className = className; + if (text !== undefined) node.textContent = text; + return node; + }; + const button = (label, variant, action) => { + const node = el("button", `dk-button dk-button--sm${variant ? ` dk-button--${variant}` : ""}`, label); + node.type = "button"; + if (action) node.dataset.blocksAction = action; + return node; + }; + return { el, button }; +} + +/** Server refusal text plus the per-field details of a validation error. */ +export function failureText(failure) { + const fields = failure.payload?.fields; + const detail = fields ? ` (${Object.entries(fields).map(([k, v]) => `${k}: ${v}`).join(", ")})` : ""; + return `${failure.message}${detail}`; +} + +/** Form control for one block field, prefilled from `value`. */ +export function fieldControl(dom, field, value, placeholderDefault = true) { + const wrap = dom.el("label", "dk-label newsletter-blocks__field"); + wrap.append(dom.el("span", "", `${field.label}${field.required ? " *" : ""}`)); + const multiline = MULTILINE.has(field.kind); + const input = dom.el(multiline ? "textarea" : "input", multiline ? "dk-textarea" : "dk-input"); + input.name = field.name; + input.value = value || ""; + if (!multiline) input.type = field.kind === "url" ? "url" : "text"; + if (multiline) input.rows = Math.min(14, Math.max(3, input.value.split("\n").length + 1)); + if (placeholderDefault && field.default) input.placeholder = field.default; + input.dataset.blockField = field.name; + wrap.append(input); + return wrap; +} + +export function collectFields(form) { + const data = {}; + for (const input of form.querySelectorAll("[data-block-field]")) data[input.name] = input.value; + return data; +} diff --git a/frontend/src/surfaces/operations/newsletter-blocks.js b/frontend/src/surfaces/operations/newsletter-blocks.js index 90e43e42..2b8bc5b7 100644 --- a/frontend/src/surfaces/operations/newsletter-blocks.js +++ b/frontend/src/surfaces/operations/newsletter-blocks.js @@ -1,31 +1,21 @@ -// The issue page's "Content blocks" section: every block of the newsletter -// issue (intro, sponsor, event spotlight, course updates, events list, -// recording, article...) as an editable form, with per-block history and the -// two-way Relay sync. Edits save to DataOps (one revision each); "Sync with -// Relay" pushes DataOps edits and pulls Relay edits, and is refused as a whole -// when a block changed on both sides. +// The newsletter issue editor: every block of the issue (intro, sponsor, event +// spotlight, course updates, events list, recording, article...) as an +// editable form, with add / reorder (buttons or drag) / delete, per-block +// history and the two-way Relay sync. Edits save to DataOps (one revision +// each); "Sync with Relay" pushes DataOps changes (edits, new, moved and +// deleted blocks), pulls Relay edits, and is refused as a whole on conflicts. +// Sponsor blocks are read-only here: their content comes from the sponsor doc. -const enc = encodeURIComponent; -const MULTILINE = new Set(["markdown", "lines", "html"]); +import { createAddPanel } from "./newsletter-blocks-add.js"; +import { renderBlockCard } from "./newsletter-blocks-card.js"; +import { createDom, formatWhen } from "./newsletter-blocks-dom.js"; -function formatWhen(iso) { - if (!iso) return ""; - return String(iso).slice(0, 16).replace("T", " "); -} +const enc = encodeURIComponent; -export function createNewsletterBlocksSection({ documentRef, request, workApiUrl }) { - const el = (tag, className, text) => { - const node = (documentRef || globalThis.document).createElement(tag); - if (className) node.className = className; - if (text !== undefined) node.textContent = text; - return node; - }; - const button = (label, variant, action) => { - const node = el("button", `dk-button dk-button--sm${variant ? ` dk-button--${variant}` : ""}`, label); - node.type = "button"; - if (action) node.dataset.blocksAction = action; - return node; - }; +export function createNewsletterBlocksSection({ documentRef, request, workApiUrl, confirmFn }) { + const dom = createDom(documentRef); + const { el, button } = dom; + const confirmUser = confirmFn || ((message) => globalThis.confirm(message)); async function mount(container, issueId) { const base = workApiUrl(`/api/newsletter-issues/${enc(issueId)}/blocks`); @@ -42,12 +32,19 @@ export function createNewsletterBlocksSection({ documentRef, request, workApiUrl container.append(section); let set = null; + const drag = { id: "" }; function say(message, tone = "info") { status.textContent = message; status.dataset.tone = tone; } + function update(next, message) { + set = next; + renderSet(); + say(message, "success"); + } + function renderImport() { body.replaceChildren(); const form = el("form", "newsletter-blocks__import"); @@ -69,7 +66,8 @@ export function createNewsletterBlocksSection({ documentRef, request, workApiUrl targetLabel.append(target); const submit = button("Import blocks from Relay", "primary"); submit.type = "submit"; - form.append(el("p", "dk-hint", "This issue has no blocks in DataOps yet. Import them once from its Relay issue."), keyLabel, targetLabel, submit); + const hint = "This issue has no blocks in DataOps yet. Import them once from its Relay issue."; + form.append(el("p", "dk-hint", hint), keyLabel, targetLabel, submit); form.addEventListener("submit", async (event) => { event.preventDefault(); submit.disabled = true; @@ -79,9 +77,7 @@ export function createNewsletterBlocksSection({ documentRef, request, workApiUrl method: "POST", body: JSON.stringify({ issueKey: key.value.trim(), target: target.value }), }); - set = result.blocks; - say(`Imported ${set.blocks.length} blocks from Relay ${set.relay.target} ${set.relay.issueKey}.`, "success"); - renderSet(); + update(result.blocks, `Imported ${result.blocks.blocks.length} blocks from Relay ${result.blocks.relay.target} ${result.blocks.relay.issueKey}.`); } catch (error) { say(`Import failed: ${error.message}`, "danger"); submit.disabled = false; @@ -120,117 +116,71 @@ export function createNewsletterBlocksSection({ documentRef, request, workApiUrl } } - function fieldControl(block, field) { - const wrap = el("label", "dk-label newsletter-blocks__field"); - wrap.append(el("span", "", `${field.label}${field.required ? " *" : ""}`)); - const multiline = MULTILINE.has(field.kind); - const input = el(multiline ? "textarea" : "input", multiline ? "dk-textarea" : "dk-input"); - input.name = field.name; - input.value = block.data?.[field.name] || ""; - if (!multiline) input.type = field.kind === "url" ? "url" : "text"; - if (multiline) input.rows = Math.min(14, Math.max(3, input.value.split("\n").length + 1)); - if (field.default) input.placeholder = field.default; - input.dataset.blockField = field.name; - wrap.append(input); - return wrap; - } + const cardContext = () => ({ + dom, + request, + base, + drag, + confirmFn: confirmUser, + onChange: update, + onFail: (message) => say(message, "danger"), + onMove: async (block, move) => { + const result = await request(`${base}/${enc(block.id)}/move`, { method: "POST", body: JSON.stringify(move) }); + update(result.blocks, "Block moved. Sync with Relay to reorder it there."); + }, + onDelete: async (block) => { + const result = await request(`${base}/${enc(block.id)}`, { method: "DELETE" }); + update(result.blocks, `Deleted ${block.label}. Sync with Relay to remove it there.`); + }, + }); - async function showHistory(block, target) { - target.replaceChildren(el("p", "dk-hint", "Loading history…")); - try { - const result = await request(`${base}/revisions?block=${enc(String(block.relayBlockId))}`); - target.replaceChildren(); - for (const rev of [...result.revisions].reverse()) { - const who = rev.origin.startsWith("relay") ? `Relay (${rev.relayActor || "?"})` : rev.actorName || "?"; - const entry = el("details", "newsletter-blocks__revision"); - entry.append(el("summary", "", `rev ${rev.revision} · ${rev.origin} · ${who} · ${formatWhen(rev.createdAt)} · ${rev.changes.map((c) => c.field).join(", ") || "no changes"}`)); - for (const change of rev.changes) { - entry.append(el("strong", "", change.field)); - if (rev.before) entry.append(el("pre", "newsletter-blocks__before", change.before || "(empty)")); - entry.append(el("pre", "newsletter-blocks__after", change.after || "(empty)")); - } - target.append(entry); - } - if (!result.revisions.length) target.append(el("p", "dk-hint", "No revisions.")); - } catch (error) { - target.replaceChildren(el("p", "dk-field-error", `History unavailable: ${error.message}`)); + function renderBar() { + const bar = el("div", "newsletter-blocks__bar"); + const pending = set.blocks.filter((block) => block.changedSinceSync).length; + const summary = `Relay ${set.relay.target} · ${set.relay.issueKey} · ${set.blocks.length} blocks`; + bar.append(el("span", "", `${summary}${pending ? ` · ${pending} edited, not synced` : ""}`)); + if (set.relayIssue?.subject) bar.append(el("span", "dk-hint", `Subject: ${set.relayIssue.subject}`)); + if (set.lastSync) bar.append(el("span", "dk-hint", `Last sync ${formatWhen(set.lastSync.at)} by ${set.lastSync.byName || "?"}: ${set.lastSync.summary}`)); + if (set.orderChanged) bar.append(el("span", "dk-badge dk-badge--warning", "Order changed, not synced")); + for (const gone of set.deletedPending || []) { + const note = el("span", "dk-badge dk-badge--warning", `Deleted here, still in Relay until sync: ${gone.label || gone.type}`); + note.dataset.deletedPending = gone.id; + bar.append(note); } - } - - function blockCard(block) { - const form = el("form", "dk-card newsletter-blocks__block"); - form.dataset.blockId = block.id; - const head = el("div", "newsletter-blocks__head"); - head.append(el("strong", "", block.label)); - head.append(el("span", "dk-mono newsletter-blocks__meta", `${block.type} · Relay #${block.relayBlockId} · v${block.version}`)); - const badge = el( - "span", - `dk-badge ${block.changedSinceSync ? "dk-badge--warning" : "dk-badge--success"}`, - block.changedSinceSync ? "Edited, not synced" : "In sync", - ); - badge.dataset.blockState = block.changedSinceSync ? "edited" : "in-sync"; - head.append(badge); - if (block.updatedByName) head.append(el("span", "dk-hint", `Last change: ${block.updatedByName}, ${formatWhen(block.updatedAt)}`)); - form.append(head); - for (const field of block.fields || []) form.append(fieldControl(block, field)); - const error = el("p", "dk-field-error"); - error.hidden = true; - const actions = el("div", "newsletter-blocks__actions"); - const save = button("Save block", "primary", "save"); - save.type = "submit"; - const historyBtn = button("History", "secondary", "history"); - const history = el("div", "newsletter-blocks__history"); - actions.append(save, historyBtn); - form.append(error, actions, history); - historyBtn.addEventListener("click", () => showHistory(block, history)); - form.addEventListener("submit", async (event) => { - event.preventDefault(); - const data = {}; - for (const input of form.querySelectorAll("[data-block-field]")) data[input.name] = input.value; - save.disabled = true; - error.hidden = true; - try { - const result = await request(`${base}/${enc(block.id)}`, { - method: "PUT", - body: JSON.stringify({ version: block.version, data }), - }); - set = result.blocks; - renderSet(); - say(result.changed ? `Saved ${block.label}. Sync with Relay to publish it there.` : `${block.label}: no changes.`, "success"); - } catch (failure) { - const fields = failure.payload?.fields ? ` (${Object.entries(failure.payload.fields).map(([k, v]) => `${k}: ${v}`).join(", ")})` : ""; - error.textContent = `${failure.message}${fields}`; - error.hidden = false; - save.disabled = false; + for (const [slot, state] of Object.entries(set.sponsorSync || {})) { + if (state && state.ok === false) { + const failed = el("span", "dk-field-error", `Sponsor doc sync failed (${slot}): ${state.error || "unknown error"}`); + failed.dataset.sponsorSyncFailed = slot; + bar.append(failed); } - }); - return form; + } + return bar; } function renderSet() { body.replaceChildren(); - const bar = el("div", "newsletter-blocks__bar"); - const pending = set.blocks.filter((block) => block.changedSinceSync).length; - bar.append( - el( - "span", - "", - `Relay ${set.relay.target} · ${set.relay.issueKey} · ${set.blocks.length} blocks${pending ? ` · ${pending} edited, not synced` : ""}`, - ), - ); - if (set.relayIssue?.subject) bar.append(el("span", "dk-hint", `Subject: ${set.relayIssue.subject}`)); - if (set.lastSync) bar.append(el("span", "dk-hint", `Last sync ${formatWhen(set.lastSync.at)} by ${set.lastSync.byName || "?"}: ${set.lastSync.summary}`)); + const bar = renderBar(); const check = button("Check Relay", "secondary", "check"); const sync = button("Sync with Relay", "primary", "sync"); + const addBtn = button("Add block", "secondary", "add"); const report = el("div", "newsletter-blocks__report"); + const add = createAddPanel({ + dom, + request, + base, + onChange: update, + onFail: (message) => say(message, "danger"), + }); check.addEventListener("click", () => runSync(true, report)); sync.addEventListener("click", () => runSync(false, report)); + addBtn.addEventListener("click", () => add.open(set)); const actions = el("div", "newsletter-blocks__actions"); - actions.append(check, sync); + actions.append(addBtn, check, sync); bar.append(actions); - body.append(bar, report); + body.append(bar, add.panel, report); const list = el("div", "newsletter-blocks__list"); - for (const block of set.blocks) list.append(blockCard(block)); + const ctx = cardContext(); + set.blocks.forEach((block, index) => list.append(renderBlockCard(ctx, block, index, set.blocks.length))); body.append(list); } diff --git a/frontend/src/surfaces/operations/newsletter-preview.js b/frontend/src/surfaces/operations/newsletter-preview.js index 82723837..ecd15da0 100644 --- a/frontend/src/surfaces/operations/newsletter-preview.js +++ b/frontend/src/surfaces/operations/newsletter-preview.js @@ -5,6 +5,7 @@ import { formatUserCode, normalizeUserCode, } from "../../dakit/device-code.js"; +import { createNewsletterBlocksSection } from "./newsletter-blocks.js"; export const NEWSLETTER_PREVIEW_CODE_ALPHABET = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ"; export const NEWSLETTER_PREVIEW_CODE_LENGTH = 16; @@ -513,6 +514,7 @@ export function createNewsletterPreviewPage({ { id: "brief", label: "Brief (brief.md)" }, { id: "sources", label: "Sources (sources.md)" }, { id: "raw", label: "Raw Markdown" }, + { id: "blocks", label: "Blocks (edit)" }, ] : []), ]; @@ -684,6 +686,14 @@ export function createNewsletterPreviewPage({ canvas.append(el("p", "dk-hint", "No sources.md content recorded.")); } previewCard.append(canvas); + } else if (activeTab === "blocks") { + // Full block editor: edit, add, move, delete, history, Relay sync. + const blocksHost = el("div", "newsletter-blocks-host"); + blocksHost.dataset.previewCanvas = "blocks"; + previewCard.append(blocksHost); + createNewsletterBlocksSection({ documentRef, request, workApiUrl: (path) => path }) + .mount(blocksHost, issueId) + .catch((error) => console.error("Newsletter blocks failed to render:", error)); } else if (activeTab === "raw") { for (const kind of ["issue", "brief", "sources"]) { const block = el("div", "sponsor-doc-field"); @@ -745,7 +755,7 @@ export function createNewsletterPreviewPage({ const url = new URL(locationRef.href); issueId = extractIssueId(url.pathname); const queryTab = url.searchParams.get("tab"); - if (queryTab === "final" || queryTab === "issue") { + if (queryTab === "final" || queryTab === "issue" || queryTab === "blocks") { activeTab = queryTab; } const queryCode = url.searchParams.get("code"); diff --git a/frontend/src/surfaces/operations/sponsor-doc-newsletter-sync.js b/frontend/src/surfaces/operations/sponsor-doc-newsletter-sync.js new file mode 100644 index 00000000..dbb63285 --- /dev/null +++ b/frontend/src/surfaces/operations/sponsor-doc-newsletter-sync.js @@ -0,0 +1,16 @@ +// Result of the automatic newsletter sync that runs on every sponsor-doc save +// (the issue's sponsor block in DataOps and Relay). A failure is shown loudly +// on the doc page; a success or skip is one quiet line. + +/** A callout for `doc.newsletterSync`, or null when the doc has no sync result. */ +export function renderNewsletterSyncNote(el, sync) { + if (!sync || !sync.status) return null; + const failed = sync.status === "failed"; + const tone = failed ? "danger" : sync.status === "ok" ? "success" : "info"; + const note = el("div", `dk-callout dk-callout--${tone}`); + note.setAttribute("role", failed ? "alert" : "status"); + note.dataset.newsletterSync = sync.status; + const prefix = failed ? "Newsletter sync FAILED: " : "Newsletter sync: "; + note.append(el("div", "dk-callout__body", `${prefix}${sync.message || sync.status}`)); + return note; +} diff --git a/frontend/src/surfaces/operations/sponsor-docs.js b/frontend/src/surfaces/operations/sponsor-docs.js index 259b2559..64120307 100644 --- a/frontend/src/surfaces/operations/sponsor-docs.js +++ b/frontend/src/surfaces/operations/sponsor-docs.js @@ -27,6 +27,7 @@ import { formatUserCode } from "../../dakit/device-code.js"; import { renderSponsorDocGate } from "./sponsor-doc-gate.js"; import { appendSponsorDocRadioField } from "./sponsor-doc-radio.js"; import { appendSponsorDocSelectField } from "./sponsor-doc-select.js"; +import { renderNewsletterSyncNote } from "./sponsor-doc-newsletter-sync.js"; import { mountSponsorDocVisualControls } from "./sponsor-doc-visual.js"; import { appendSponsorDocBulletsField, @@ -813,6 +814,9 @@ export function createSponsorDocPage({ form.append(fb); } + const syncNote = renderNewsletterSyncNote(el, doc?.newsletterSync); + if (syncNote) form.append(syncNote); + form.addEventListener("submit", (event) => { event.preventDefault(); saveChanges(undefined); }); form.append(renderSponsorDocFormActions({ el, diff --git a/frontend/test/newsletter-blocks.test.mjs b/frontend/test/newsletter-blocks.test.mjs index 71a5d8eb..4c0264fa 100644 --- a/frontend/test/newsletter-blocks.test.mjs +++ b/frontend/test/newsletter-blocks.test.mjs @@ -16,7 +16,7 @@ const blockSet = (overrides = {}) => ({ ...overrides, }); -function setup(routes) { +function setup(routes, options = {}) { const documentRef = new FakeDocument(); const calls = []; const request = async (url, options = {}) => { @@ -26,7 +26,7 @@ function setup(routes) { if (!handler) throw Object.assign(new Error(`no route ${method} ${url}`), { status: 404 }); return handler(calls.at(-1)); }; - const section = createNewsletterBlocksSection({ documentRef, request, workApiUrl: (path) => path }); + const section = createNewsletterBlocksSection({ documentRef, request, workApiUrl: (path) => path, ...options }); return { section, calls, container: new FakeElement("div") }; } @@ -88,3 +88,132 @@ test("offers an import from Relay when the issue has no blocks yet", async () => assert.deepEqual(calls.at(-1).body, { issueKey: "weekly-304", target: "dev" }); assert.equal(container.querySelectorAll("[data-block-id]").length, 2); }); + +const rich = () => blockSet({ + orderChanged: true, + deletedPending: [{ id: "rb-9", type: "recording", label: "Recording" }], + blocks: [ + { id: "rb-113", relayBlockId: 113, position: 0, type: "intro", label: "Intro", version: 1, data: { summary: "Hello" }, fields: [field("summary", "markdown", true)], pushState: "in-sync", canMove: true, canDelete: true }, + { id: "rb-114", relayBlockId: 114, position: 1, type: "sponsor", label: "Sponsor (main)", version: 3, data: { title: "Acme" }, fields: [field("title")], sponsor: "primary", readOnly: true, pinned: true, canMove: false, canDelete: false, sponsorDocUrl: "/sponsor-docs/doc-1", pushState: "in-sync" }, + { id: "rb-115", relayBlockId: 115, position: 2, type: "sponsor_secondary", label: "Sponsor (secondary)", version: 1, data: { title: "Beta" }, fields: [field("title")], sponsor: "secondary", readOnly: true, canMove: true, canDelete: false, sponsorDocUrl: "/sponsor-docs/doc-2", pushState: "in-sync" }, + { id: "nb-1", relayBlockId: null, position: 3, type: "recording", label: "Recording", version: 1, data: { title: "Talk" }, fields: [field("title", "text", true)], pushState: "new", canMove: true, canDelete: true }, + ], +}); +const card = (container, id) => container.querySelectorAll("[data-block-id]").find((form) => form.dataset.blockId === id); +const action = (form, name) => form.querySelector(`[data-blocks-action="${name}"]`); + +test("sponsor blocks are read-only with an Edit in sponsor doc link and disabled controls", async () => { + const { section, container } = setup({ [`GET ${BASE}`]: () => ({ blocks: rich() }) }); + await section.mount(container, "iss"); + const main = card(container, "rb-114"); + assert.equal(main.querySelectorAll("[data-block-field]").length, 0); + assert.equal(action(main, "save"), null); + assert.equal(main.querySelector("[data-sponsor-doc-link]").href, "/sponsor-docs/doc-1"); + assert.equal(main.querySelector("[data-sponsor-doc-link]").textContent, "Edit in sponsor doc"); + assert.ok(findByText(main, "Pinned: first content block")); + assert.equal(action(main, "up").disabled, true); + assert.equal(action(main, "down").disabled, true); + assert.equal(action(main, "delete").disabled, true); + const secondary = card(container, "rb-115"); + assert.equal(action(secondary, "delete").disabled, true); + assert.match(action(secondary, "delete").title, /removing the slot/); + assert.equal(action(secondary, "up").disabled, false); + assert.ok(findByText(container, "Order changed, not synced")); + assert.equal(card(container, "nb-1").querySelector("[data-block-state]").textContent, "New, not in Relay"); + assert.ok(container.querySelector("[data-deleted-pending]")); +}); + +test("up and down post a move", async () => { + const { section, calls, container } = setup({ + [`GET ${BASE}`]: () => ({ blocks: rich() }), + [`POST ${BASE}/nb-1/move`]: () => ({ blocks: rich() }), + [`POST ${BASE}/rb-115/move`]: () => ({ blocks: rich() }), + }); + await section.mount(container, "iss"); + await action(card(container, "nb-1"), "up").click(); + assert.deepEqual(calls.at(-1), { method: "POST", url: `${BASE}/nb-1/move`, body: { direction: "up" } }); + await action(card(container, "rb-115"), "down").click(); + assert.deepEqual(calls.at(-1).body, { direction: "down" }); + assert.match(container.querySelector("[data-blocks-status]").textContent, /Block moved/); +}); + +test("dragging a block onto another posts the target index", async () => { + const { section, calls, container } = setup({ + [`GET ${BASE}`]: () => ({ blocks: rich() }), + [`POST ${BASE}/nb-1/move`]: () => ({ blocks: rich() }), + }); + await section.mount(container, "iss"); + const dragged = card(container, "nb-1"); + assert.equal(dragged.draggable, true); + assert.notEqual(card(container, "rb-114").draggable, true); + await dragged.dispatch("dragstart"); + await card(container, "rb-115").dispatch("drop"); + assert.deepEqual(calls.at(-1), { method: "POST", url: `${BASE}/nb-1/move`, body: { to: 2 } }); +}); + +test("a refused move shows the server message in the block and the status", async () => { + const refusal = Object.assign(new Error("The main sponsor block is pinned."), { status: 409, code: "above_pinned_sponsor" }); + const { section, container } = setup({ + [`GET ${BASE}`]: () => ({ blocks: rich() }), + [`POST ${BASE}/rb-113/move`]: () => { throw refusal; }, + }); + await section.mount(container, "iss"); + await action(card(container, "rb-113"), "down").click(); + const status = container.querySelector("[data-blocks-status]"); + assert.equal(status.dataset.tone, "danger"); + assert.match(status.textContent, /pinned/); + const inline = card(container, "rb-113").querySelector("[data-block-error]"); + assert.equal(inline.hidden, false); + assert.match(inline.textContent, /pinned/); +}); + +test("delete asks for confirmation, then deletes", async () => { + let answer = false; + const { section, calls, container } = setup({ + [`GET ${BASE}`]: () => ({ blocks: rich() }), + [`DELETE ${BASE}/nb-1`]: () => ({ blocks: rich() }), + }, { confirmFn: () => answer }); + await section.mount(container, "iss"); + await action(card(container, "nb-1"), "delete").click(); + assert.equal(calls.filter((call) => call.method === "DELETE").length, 0); + answer = true; + await action(card(container, "nb-1"), "delete").click(); + assert.deepEqual(calls.at(-1), { method: "DELETE", url: `${BASE}/nb-1`, body: undefined }); + assert.match(container.querySelector("[data-blocks-status]").textContent, /Deleted Recording/); +}); + +test("adding a block posts the chosen type, defaults, edits and position", async () => { + const types = [ + { type: "recording", label: "Recording", addable: true, fields: [{ ...field("kicker"), default: "RECORDINGS" }, field("title", "text", true)] }, + { type: "sponsor", label: "Sponsor (main)", addable: false, fields: [field("title")] }, + ]; + const { section, calls, container } = setup({ + [`GET ${BASE}`]: () => ({ blocks: rich() }), + [`GET ${BASE}/types`]: () => ({ types }), + [`POST ${BASE}`]: () => ({ block: { id: "nb-2" }, blocks: rich() }), + }); + await section.mount(container, "iss"); + await action(container, "add").click(); + const form = container.querySelector("[data-blocks-add-form]"); + assert.deepEqual(form.querySelector('[name="type"]').children.map((option) => option.value), ["recording"]); + assert.equal(form.querySelector('[name="kicker"]').value, "RECORDINGS"); + form.querySelector('[name="title"]').value = "New talk"; + form.querySelector('[name="position"]').value = "3"; + await form.dispatch("submit"); + assert.deepEqual(calls.at(-1).body, { type: "recording", data: { kicker: "RECORDINGS", title: "New talk" }, position: 3 }); + assert.match(container.querySelector("[data-blocks-status]").textContent, /Block added/); +}); + +test("a failed add shows the server refusal", async () => { + const refusal = Object.assign(new Error("Sponsor blocks come from the sponsor doc."), { status: 409 }); + const types = [{ type: "recording", label: "Recording", addable: true, fields: [field("title")] }]; + const { section, container } = setup({ + [`GET ${BASE}`]: () => ({ blocks: rich() }), + [`GET ${BASE}/types`]: () => ({ types }), + [`POST ${BASE}`]: () => { throw refusal; }, + }); + await section.mount(container, "iss"); + await action(container, "add").click(); + await container.querySelector("[data-blocks-add-form]").dispatch("submit"); + assert.match(container.querySelector("[data-blocks-status]").textContent, /Sponsor blocks come from the sponsor doc/); +}); diff --git a/frontend/test/sponsor-doc-newsletter-sync.test.mjs b/frontend/test/sponsor-doc-newsletter-sync.test.mjs new file mode 100644 index 00000000..a5f9c88f --- /dev/null +++ b/frontend/test/sponsor-doc-newsletter-sync.test.mjs @@ -0,0 +1,28 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { renderNewsletterSyncNote } from "../src/surfaces/operations/sponsor-doc-newsletter-sync.js"; +import { FakeDocument } from "./support/fake-dom.mjs"; + +const documentRef = new FakeDocument(); +const el = (tag, className, text) => { + const node = documentRef.createElement(tag); + node.className = className || ""; + if (text !== undefined) node.textContent = text; + return node; +}; + +test("a failed newsletter sync is a loud alert on the doc page", () => { + const note = renderNewsletterSyncNote(el, { status: "failed", message: "Relay block 114 changed in Relay" }); + assert.equal(note.dataset.newsletterSync, "failed"); + assert.equal(note.getAttribute("role"), "alert"); + assert.match(note.className, /dk-callout--danger/); + assert.match(note.textContent, /Newsletter sync FAILED: Relay block 114 changed in Relay/); +}); + +test("ok and skipped results are quiet lines; no result renders nothing", () => { + const ok = renderNewsletterSyncNote(el, { status: "ok", message: "Updated issue #304 sponsor block" }); + assert.match(ok.className, /dk-callout--success/); + assert.equal(ok.getAttribute("role"), "status"); + assert.match(renderNewsletterSyncNote(el, { status: "skipped", message: "No issue uses this doc" }).className, /dk-callout--info/); + assert.equal(renderNewsletterSyncNote(el, null), null); +}); From 9363453d12012cdf1ac8be9050ed5268e0ea81ed Mon Sep 17 00:00:00 2001 From: Alexey Grigorev Date: Mon, 23 Nov 2026 13:32:32 +0100 Subject: [PATCH 07/12] Block editor styles: use dk space tokens --- frontend/src/styles/planner.css | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/frontend/src/styles/planner.css b/frontend/src/styles/planner.css index 5637a414..578620d7 100644 --- a/frontend/src/styles/planner.css +++ b/frontend/src/styles/planner.css @@ -1264,7 +1264,7 @@ a.calendar-day-timeline-title:hover { .newsletter-blocks__values { display: grid; - gap: var(--space-1, 4px); + gap: var(--dk-space-1); } .newsletter-blocks__values dt { @@ -1279,5 +1279,5 @@ a.calendar-day-timeline-title:hover { .newsletter-blocks__add, .newsletter-blocks__fields { display: grid; - gap: var(--space-3, 12px); + gap: var(--dk-space-3); } From 513bb58fd1afa912fff49c4f526bac4c0add1f18 Mon Sep 17 00:00:00 2001 From: Alexey Grigorev Date: Mon, 23 Nov 2026 13:34:52 +0100 Subject: [PATCH 08/12] Newsletter blocks: add/move/delete, sponsor-block rules, sponsor-doc auto-sync to issue and Relay --- backend/src/newsletter/blocks.ts | 107 +++++- backend/src/newsletter/blocksErrors.ts | 11 + backend/src/newsletter/blocksLayout.ts | 130 +++++++ backend/src/newsletter/blocksOps.ts | 180 ++++++++++ backend/src/newsletter/blocksRelay.ts | 26 ++ backend/src/newsletter/blocksStore.ts | 14 +- backend/src/newsletter/blocksSync.ts | 228 +++++++++---- backend/src/newsletter/sponsorBlocks.ts | 435 ++++++++++++++++++++++++ backend/src/routes/newsletterBlocks.ts | 123 ++++++- backend/src/routes/newsletterIssues.ts | 3 + backend/src/routes/sponsorDocs.ts | 31 +- 11 files changed, 1194 insertions(+), 94 deletions(-) create mode 100644 backend/src/newsletter/blocksErrors.ts create mode 100644 backend/src/newsletter/blocksLayout.ts create mode 100644 backend/src/newsletter/blocksOps.ts create mode 100644 backend/src/newsletter/sponsorBlocks.ts diff --git a/backend/src/newsletter/blocks.ts b/backend/src/newsletter/blocks.ts index 30d034f9..299bca39 100644 --- a/backend/src/newsletter/blocks.ts +++ b/backend/src/newsletter/blocks.ts @@ -16,7 +16,7 @@ * `mailing.services.newsletters.BLOCK_TYPES`, so content that saves here also * saves in Relay (whose block update is strict). */ -import { createHash } from 'crypto'; +import { createHash, randomBytes } from 'crypto'; export type BlockFieldKind = 'text' | 'url' | 'markdown' | 'lines' | 'html'; @@ -213,9 +213,10 @@ export interface BlockSyncBase { } export interface IssueBlock { - /** Stable DataOps id of the block (`rb-` for blocks that came from Relay). */ + /** Stable DataOps id: `rb-` for blocks that came from Relay, `nb-` for blocks added here. */ id: string; - relayBlockId: number; + /** The Relay block this mirrors; null until a block added in DataOps is pushed. */ + relayBlockId: number | null; position: number; type: string; data: BlockData; @@ -227,12 +228,34 @@ export interface IssueBlock { base: BlockSyncBase; } +/** A block deleted in DataOps whose Relay copy is removed on the next sync. */ +export interface DeletedBlock { + id: string; + relayBlockId: number; + type: string; + data: BlockData; + /** Hash both sides last agreed on; a Relay edit since then blocks the delete. */ + baseHash: string; + deletedAt: string; + deletedByName: string | null; +} + +export type SponsorSyncStatus = { at: string; ok: boolean; error?: string; docId: string; summary?: string }; + export interface IssueBlockSet { issueId: string; relay: { target: RelayTarget; issueKey: string }; /** Issue-level fields as last read from Relay (shown, not edited here). */ relayIssue: { subject: string; previewText: string; campaignStatus: string | null; updatedAt: string }; blocks: IssueBlock[]; + /** Blocks deleted here and still present in Relay. */ + deleted?: DeletedBlock[]; + /** Relay block ids in the order both sides last agreed on. */ + orderBase?: number[]; + /** The order was changed in DataOps since the last sync. */ + orderDirty?: boolean; + /** Outcome of the last automatic sponsor-doc sync per slot. */ + sponsorSync?: Partial>; version: number; lastSync: { at: string; byName: string | null; summary: string } | null; createdAt: string; @@ -263,33 +286,56 @@ export interface RelayIssue { // ---------------------------------------------------------------- three-way plan -export type SyncAction = 'in_sync' | 'push' | 'pull' | 'add' | 'remove' | 'conflict'; +export type SyncAction = 'in_sync' | 'push' | 'pull' | 'add' | 'remove' | 'conflict' | 'create' | 'delete'; export interface SyncStep { action: SyncAction; blockId: string | null; - relayBlockId: number; + relayBlockId: number | null; type: string; reason: string; } +export interface OrderStep { + action: 'none' | 'push' | 'pull' | 'conflict'; + reason: string; +} + export interface SyncPlan { steps: SyncStep[]; conflicts: SyncStep[]; + /** Existing Relay blocks to update. */ pushes: SyncStep[]; + /** Blocks added in DataOps, to create in Relay. */ + creates: SyncStep[]; + /** Blocks deleted in DataOps, to delete in Relay. */ + deletes: SyncStep[]; pulls: SyncStep[]; + order: OrderStep; } +const sameList = (a: number[], b: number[]) => a.length === b.length && a.every((value, index) => value === b[index]); + /** * Compare each block against its sync base. Never decides a winner when both * sides changed: that is a conflict, and executing a plan with conflicts is - * refused as a whole. + * refused as a whole. Blocks added in DataOps are created in Relay, blocks + * deleted in DataOps are deleted there (unless Relay edited them since), and + * the block order follows whichever side changed it. */ -export function planSync(blocks: IssueBlock[], relay: RelayIssue): SyncPlan { +export function planSync( + blocks: IssueBlock[], + relay: RelayIssue, + extras: { deleted?: DeletedBlock[]; orderBase?: number[]; orderDirty?: boolean } = {}, +): SyncPlan { const steps: SyncStep[] = []; const relayById = new Map(relay.blocks.map((block) => [block.id, block])); const seen = new Set(); for (const local of blocks) { + if (local.relayBlockId === null) { + steps.push({ action: 'create', blockId: local.id, relayBlockId: null, type: local.type, reason: 'added in DataOps' }); + continue; + } const remote = relayById.get(local.relayBlockId); const localHash = blockHash(local.type, local.data); const localChanged = localHash !== local.base.hash; @@ -319,19 +365,66 @@ export function planSync(blocks: IssueBlock[], relay: RelayIssue): SyncPlan { steps.push({ ...common, action: 'pull', reason: `edited in Relay by ${remote.updated_by || 'unknown'}` }); } } + for (const gone of extras.deleted || []) { + const remote = relayById.get(gone.relayBlockId); + const common = { blockId: gone.id, relayBlockId: gone.relayBlockId, type: gone.type }; + if (!remote) { + steps.push({ ...common, action: 'in_sync', reason: 'deleted in DataOps and already gone from Relay' }); + continue; + } + seen.add(remote.id); + if (blockHash(remote.type, remote.data) !== gone.baseHash) { + steps.push({ + ...common, + action: 'conflict', + reason: `deleted in DataOps but edited in Relay (Relay: ${remote.updated_by || 'unknown'} at ${remote.updated_at})`, + }); + } else { + steps.push({ ...common, action: 'delete', reason: 'deleted in DataOps' }); + } + } for (const remote of relay.blocks) { if (seen.has(remote.id)) continue; steps.push({ action: 'add', blockId: null, relayBlockId: remote.id, type: remote.type, reason: 'new in Relay' }); } + + // Order: compare only the blocks both sides know, so adds and deletes do not count as moves. + const relayOrder = [...relay.blocks].sort((a, b) => a.position - b.position).map((block) => block.id); + const localOrder = [...blocks] + .sort((a, b) => a.position - b.position) + .map((block) => block.relayBlockId) + .filter((id): id is number => id !== null && relayById.has(id)); + const base = extras.orderBase; + const baseKnown = base ? base.filter((id) => relayById.has(id)) : relayOrder; + const relayKnown = relayOrder.filter((id) => (base ? base.includes(id) : true)); + const relayMoved = !sameList(relayKnown, baseKnown); + const localMoved = Boolean(extras.orderDirty); + const localCommon = localOrder.filter((id) => relayOrder.includes(id)); + const relayCommon = relayOrder.filter((id) => localOrder.includes(id)); + let order: OrderStep = { action: 'none', reason: 'same order' }; + if (localMoved && relayMoved && !sameList(localCommon, relayCommon)) { + order = { action: 'conflict', reason: 'blocks were reordered in DataOps and in Relay' }; + } else if (localMoved && !sameList(localCommon, relayCommon)) { + order = { action: 'push', reason: 'reordered in DataOps' }; + } else if (relayMoved && !sameList(localCommon, relayCommon)) { + order = { action: 'pull', reason: 'reordered in Relay' }; + } + if (order.action === 'conflict') { + steps.push({ action: 'conflict', blockId: null, relayBlockId: null, type: 'order', reason: order.reason }); + } return { steps, conflicts: steps.filter((step) => step.action === 'conflict'), pushes: steps.filter((step) => step.action === 'push'), + creates: steps.filter((step) => step.action === 'create'), + deletes: steps.filter((step) => step.action === 'delete'), pulls: steps.filter((step) => step.action === 'pull' || step.action === 'add' || step.action === 'remove'), + order, }; } export const localBlockId = (relayBlockId: number) => `rb-${relayBlockId}`; +export const newBlockId = () => `nb-${randomBytes(5).toString('hex')}`; /** A local block that mirrors `remote` exactly, with the sync base set to it. */ export function blockFromRelay(remote: RelayBlock, now: string, actor: { id: string; name: string | null }, version = 1): IssueBlock { diff --git a/backend/src/newsletter/blocksErrors.ts b/backend/src/newsletter/blocksErrors.ts new file mode 100644 index 00000000..550e7ca9 --- /dev/null +++ b/backend/src/newsletter/blocksErrors.ts @@ -0,0 +1,11 @@ +/** An expected, explainable refusal of a block operation (carries an HTTP status and a stable code). */ +export class BlocksError extends Error { + constructor( + message: string, + public readonly status: number, + public readonly code: string, + public readonly detail: Record = {}, + ) { + super(message); + } +} diff --git a/backend/src/newsletter/blocksLayout.ts b/backend/src/newsletter/blocksLayout.ts new file mode 100644 index 00000000..308e711e --- /dev/null +++ b/backend/src/newsletter/blocksLayout.ts @@ -0,0 +1,130 @@ +/** + * Where blocks may go, and the sponsor-block rules (enforced here, server-side, + * so the UI and the CLI get the same loud refusals): + * + * - The main sponsor block (`sponsor`) is pinned as the first content block: + * it cannot be moved or deleted, and nothing can be placed above it (the + * intro stays on top as the header; nothing else may be moved above the + * sponsor, and blocks above it cannot be moved). + * - Secondary sponsor blocks (`sponsor_secondary`) can be reordered, but not + * deleted directly: they leave when their slot is removed from the sponsor doc. + * - Every sponsor block is content read-only: its content only comes from its + * sponsor document through the automatic sponsor-doc sync. + */ +import type { IssueBlock } from './blocks'; +import { BlocksError } from './blocksErrors'; + +export type SponsorSlotKind = 'primary' | 'secondary'; +export type SponsorDocUrls = Partial>; + +export const SPONSOR_TYPES: Record = { sponsor: 'primary', sponsor_secondary: 'secondary' }; + +export const sponsorSlotOf = (type: string): SponsorSlotKind | null => SPONSOR_TYPES[type] || null; + +export const byPosition = (blocks: IssueBlock[]) => [...blocks].sort((a, b) => a.position - b.position); + +/** Index of the pinned main sponsor block, or -1 when the issue has none. */ +export function pinnedIndex(ordered: IssueBlock[]): number { + return ordered.findIndex((block) => block.type === 'sponsor'); +} + +function docHint(slot: SponsorSlotKind, urls: SponsorDocUrls): Record { + return urls[slot] ? { sponsorDocUrl: urls[slot] } : {}; +} + +function sponsorRefusal(message: string, code: string, slot: SponsorSlotKind, urls: SponsorDocUrls) { + return new BlocksError(message, 409, code, docHint(slot, urls)); +} + +/** Content edits of sponsor blocks come only from the sponsor doc. */ +export function assertEditable(block: IssueBlock, urls: SponsorDocUrls): void { + const slot = sponsorSlotOf(block.type); + if (!slot) return; + throw sponsorRefusal( + `Block ${block.id} is the ${slot === 'primary' ? 'main' : 'secondary'} sponsor block: its content is read-only here and comes only from the sponsor document. Edit it in the sponsor doc; it syncs to this issue and to Relay on save.`, + 'sponsor_block_readonly', + slot, + urls, + ); +} + +export function assertDeletable(block: IssueBlock, urls: SponsorDocUrls): void { + const slot = sponsorSlotOf(block.type); + if (slot === 'primary') { + throw sponsorRefusal( + `Block ${block.id} is the main sponsor block: it is pinned as the first content block and cannot be deleted.`, + 'sponsor_block_pinned', + slot, + urls, + ); + } + if (slot === 'secondary') { + throw sponsorRefusal( + `Block ${block.id} is a secondary sponsor block: it cannot be deleted directly. Remove the slot from the sponsor doc and it leaves the issue on the next doc sync.`, + 'sponsor_block_delete_refused', + slot, + urls, + ); + } +} + +/** + * `toIndex` is the block's final index. Returns the blocks in the new order, or + * throws when the move breaks a sponsor rule. + */ +export function moveWithin(ordered: IssueBlock[], blockId: string, toIndex: number, urls: SponsorDocUrls): IssueBlock[] { + const from = ordered.findIndex((block) => block.id === blockId); + if (from < 0) throw new BlocksError(`No block ${blockId}.`, 404, 'block_not_found'); + const block = ordered[from]; + if (!Number.isInteger(toIndex) || toIndex < 0 || toIndex >= ordered.length) { + throw new BlocksError(`Position ${String(toIndex)} is outside 0..${ordered.length - 1}.`, 400, 'position_invalid'); + } + if (block.type === 'sponsor') { + throw sponsorRefusal( + `Block ${block.id} is the main sponsor block: it is pinned as the first content block and cannot be moved.`, + 'sponsor_block_pinned', + 'primary', + urls, + ); + } + const pin = pinnedIndex(ordered); + if (pin >= 0 && from < pin) { + throw new BlocksError( + `Block ${block.id} sits above the pinned main sponsor block and cannot be moved.`, + 409, + 'above_pinned_sponsor', + docHint('primary', urls), + ); + } + if (pin >= 0 && toIndex <= pin) { + throw new BlocksError( + `Nothing can be placed above the pinned main sponsor block (it is the first content block, at position ${pin}). Move to position ${pin + 1} or later.`, + 409, + 'above_pinned_sponsor', + docHint('primary', urls), + ); + } + const next = ordered.filter((item) => item.id !== blockId); + next.splice(toIndex, 0, block); + return next; +} + +/** Position for a new block: append when omitted; never above the pinned sponsor. */ +export function insertionIndex(ordered: IssueBlock[], position: unknown, urls: SponsorDocUrls): number { + if (position === undefined || position === null || position === '') return ordered.length; + if (!Number.isInteger(position) || (position as number) < 0 || (position as number) > ordered.length) { + throw new BlocksError(`Position ${String(position)} is outside 0..${ordered.length}.`, 400, 'position_invalid'); + } + const pin = pinnedIndex(ordered); + if (pin >= 0 && (position as number) <= pin) { + throw new BlocksError( + `Nothing can be placed above the pinned main sponsor block (it is the first content block, at position ${pin}). Add at position ${pin + 1} or later.`, + 409, + 'above_pinned_sponsor', + docHint('primary', urls), + ); + } + return position as number; +} + +export const renumber = (ordered: IssueBlock[]): IssueBlock[] => ordered.map((block, index) => (block.position === index ? block : { ...block, position: index })); diff --git a/backend/src/newsletter/blocksOps.ts b/backend/src/newsletter/blocksOps.ts new file mode 100644 index 00000000..e8e04af2 --- /dev/null +++ b/backend/src/newsletter/blocksOps.ts @@ -0,0 +1,180 @@ +/** + * Add, move and delete blocks in DataOps (the edit-in-place operations live in + * blocksSync.ts next to the Relay sync). Every operation is one optimistic + * write of the block set plus one revision per affected block; the Relay copy + * follows on the next sync (or at once for sponsor blocks). + */ +import type { DynamoDBDocumentClient } from '@aws-sdk/lib-dynamodb'; +import { + BLOCK_TYPES, + blockHash, + newBlockId, + validateBlockData, + type IssueBlock, + type IssueBlockSet, +} from './blocks'; +import { BlocksError } from './blocksErrors'; +import { + assertDeletable, + byPosition, + insertionIndex, + moveWithin, + renumber, + sponsorSlotOf, + type SponsorDocUrls, +} from './blocksLayout'; +import { appendBlockRevisions, putBlockSet } from './blocksStore'; +import { requireBlockSet, type BlockActor } from './blocksSync'; + +function find(set: IssueBlockSet, blockId: string): IssueBlock { + const block = set.blocks.find((item) => item.id === blockId); + if (!block) throw new BlocksError(`Issue ${set.issueId} has no block ${blockId}.`, 404, 'block_not_found'); + return block; +} + +export async function addBlock( + client: DynamoDBDocumentClient, + issueId: string, + input: { type: unknown; data?: unknown; position?: unknown }, + urls: SponsorDocUrls, + actor: BlockActor, +): Promise<{ set: IssueBlockSet; block: IssueBlock }> { + const type = String(input.type || ''); + const spec = BLOCK_TYPES[type]; + if (!spec) throw new BlocksError(`Unknown block type "${type}". Types: ${Object.keys(BLOCK_TYPES).join(', ')}.`, 400, 'block_type_unknown'); + if (sponsorSlotOf(type)) { + throw new BlocksError( + `${spec.label} blocks cannot be added by hand: sponsor blocks are created from the slot's sponsor document when it is saved.`, + 409, + 'sponsor_block_doc_only', + ); + } + const set = await requireBlockSet(client, issueId); + const ordered = byPosition(set.blocks); + const index = insertionIndex(ordered, input.position, urls); + const given = input.data && typeof input.data === 'object' && !Array.isArray(input.data) ? (input.data as Record) : {}; + const data = validateBlockData(type, { ...spec.defaults, ...given }); + const now = new Date().toISOString(); + const block: IssueBlock = { + id: newBlockId(), + relayBlockId: null, + position: index, + type, + data, + version: 1, + updatedAt: now, + updatedBy: actor.id, + updatedByName: actor.name, + base: { hash: '', relayUpdatedAt: '', syncedAt: '' }, + }; + ordered.splice(index, 0, block); + const next: IssueBlockSet = { + ...set, + blocks: renumber(ordered), + orderDirty: true, + version: set.version + 1, + updatedAt: now, + }; + await putBlockSet(client, next, set.version); + await appendBlockRevisions(client, issueId, [ + { + blockId: block.id, + relayBlockId: null, + blockType: type, + origin: 'add', + createdAt: now, + actorUserId: actor.id, + actorName: actor.name, + detail: `added at position ${index}`, + before: null, + after: data, + }, + ]); + return { set: next, block: next.blocks.find((item) => item.id === block.id) as IssueBlock }; +} + +export async function moveBlock( + client: DynamoDBDocumentClient, + issueId: string, + blockId: string, + input: { to?: unknown; direction?: unknown }, + urls: SponsorDocUrls, + actor: BlockActor, +): Promise<{ set: IssueBlockSet; block: IssueBlock }> { + const set = await requireBlockSet(client, issueId); + const block = find(set, blockId); + const ordered = byPosition(set.blocks); + const from = ordered.findIndex((item) => item.id === block.id); + let to: number; + if (input.direction === 'up' || input.direction === 'down') to = from + (input.direction === 'up' ? -1 : 1); + else if (typeof input.to === 'number') to = input.to; + else throw new BlocksError('Give a direction ("up" or "down") or a target position "to".', 400, 'move_target_missing'); + const moved = renumber(moveWithin(ordered, block.id, to, urls)); + if (to === from) return { set, block }; + const now = new Date().toISOString(); + const next: IssueBlockSet = { ...set, blocks: moved, orderDirty: true, version: set.version + 1, updatedAt: now }; + await putBlockSet(client, next, set.version); + await appendBlockRevisions(client, issueId, [ + { + blockId: block.id, + relayBlockId: block.relayBlockId, + blockType: block.type, + origin: 'move', + createdAt: now, + actorUserId: actor.id, + actorName: actor.name, + detail: `moved from position ${from} to ${to}`, + before: block.data, + after: block.data, + }, + ]); + return { set: next, block: next.blocks.find((item) => item.id === block.id) as IssueBlock }; +} + +export async function deleteBlock( + client: DynamoDBDocumentClient, + issueId: string, + blockId: string, + urls: SponsorDocUrls, + actor: BlockActor, +): Promise<{ set: IssueBlockSet; block: IssueBlock }> { + const set = await requireBlockSet(client, issueId); + const block = find(set, blockId); + assertDeletable(block, urls); + const now = new Date().toISOString(); + const deleted = [...(set.deleted || [])]; + if (block.relayBlockId !== null) { + deleted.push({ + id: block.id, + relayBlockId: block.relayBlockId, + type: block.type, + data: block.data, + baseHash: block.base.hash || blockHash(block.type, block.data), + deletedAt: now, + deletedByName: actor.name, + }); + } + const next: IssueBlockSet = { + ...set, + blocks: renumber(byPosition(set.blocks).filter((item) => item.id !== block.id)), + deleted, + version: set.version + 1, + updatedAt: now, + }; + await putBlockSet(client, next, set.version); + await appendBlockRevisions(client, issueId, [ + { + blockId: block.id, + relayBlockId: block.relayBlockId, + blockType: block.type, + origin: 'delete', + createdAt: now, + actorUserId: actor.id, + actorName: actor.name, + detail: block.relayBlockId === null ? 'deleted (never pushed to Relay)' : 'deleted; the Relay copy is removed on the next sync', + before: block.data, + after: null, + }, + ]); + return { set: next, block }; +} diff --git a/backend/src/newsletter/blocksRelay.ts b/backend/src/newsletter/blocksRelay.ts index a607d854..513838d1 100644 --- a/backend/src/newsletter/blocksRelay.ts +++ b/backend/src/newsletter/blocksRelay.ts @@ -71,6 +71,15 @@ export interface RelayClient { getIssue(issueKey: string): Promise; getBlock(issueKey: string, blockId: number): Promise; putBlock(issueKey: string, blockId: number, type: string, data: Record): Promise; + /** Add a block at `position` (end when omitted). */ + postBlock(issueKey: string, type: string, data: Record, position?: number): Promise; + deleteBlock(issueKey: string, blockId: number): Promise; + /** Move a block to `position` without touching its content. */ + moveBlock(issueKey: string, blockId: number, position: number): Promise; + /** Update issue-level fields (subject, preview_text). */ + putIssueFields(issueKey: string, fields: { subject?: string; preview_text?: string }): Promise; + /** Relay's own block type catalogue (type keys), to prove DataOps' mirror still matches. */ + blockTypeKeys(): Promise; } export function relayBodyBytes(type: string, data: Record): number { @@ -140,5 +149,22 @@ export async function relayClient(target: RelayTarget): Promise { async putBlock(issueKey, blockId, type, data) { return (await call<{ block: RelayBlock }>('PUT', `${issuePath(issueKey)}/blocks/${blockId}`, { type, data })).block; }, + async postBlock(issueKey, type, data, position) { + const body = { type, data, ...(position === undefined ? {} : { position }) }; + return (await call<{ block: RelayBlock }>('POST', `${issuePath(issueKey)}/blocks`, body)).block; + }, + async deleteBlock(issueKey, blockId) { + await call('DELETE', `${issuePath(issueKey)}/blocks/${blockId}`); + }, + async moveBlock(issueKey, blockId, position) { + return (await call<{ block: RelayBlock }>('PUT', `${issuePath(issueKey)}/blocks/${blockId}`, { position })).block; + }, + async putIssueFields(issueKey, fields) { + return (await call<{ issue: RelayIssue }>('PUT', issuePath(issueKey), fields)).issue; + }, + async blockTypeKeys() { + const payload = await call<{ block_types: { type?: string; key?: string }[] }>('GET', '/api/newsletter-block-types'); + return (payload.block_types || []).map((item) => String(item.type || item.key || '')).filter(Boolean); + }, }; } diff --git a/backend/src/newsletter/blocksStore.ts b/backend/src/newsletter/blocksStore.ts index 7405b884..ce6cece0 100644 --- a/backend/src/newsletter/blocksStore.ts +++ b/backend/src/newsletter/blocksStore.ts @@ -12,13 +12,21 @@ import type { DynamoDBDocumentClient } from '@aws-sdk/lib-dynamodb'; import { TABLE_ARTIFACTS } from '../db/tableNames'; import type { BlockData, IssueBlockSet } from './blocks'; -export type BlockRevisionOrigin = 'import' | 'edit' | 'relay-pull' | 'relay-remove'; +export type BlockRevisionOrigin = + | 'import' + | 'edit' + | 'add' + | 'move' + | 'delete' + | 'sponsor-doc' + | 'relay-pull' + | 'relay-remove'; export interface BlockRevision { issueId: string; revision: number; blockId: string; - relayBlockId: number; + relayBlockId: number | null; blockType: string; origin: BlockRevisionOrigin; createdAt: string; @@ -26,6 +34,8 @@ export interface BlockRevision { actorName: string | null; /** Who changed it in Relay, for pulled revisions (Relay's `updated_by`). */ relayActor?: string; + /** Human-readable note, e.g. "moved from position 3 to 5". */ + detail?: string; before: BlockData | null; after: BlockData | null; } diff --git a/backend/src/newsletter/blocksSync.ts b/backend/src/newsletter/blocksSync.ts index ffbcb679..3beb4a64 100644 --- a/backend/src/newsletter/blocksSync.ts +++ b/backend/src/newsletter/blocksSync.ts @@ -16,6 +16,7 @@ import { blockHash, planSync, validateBlockData, + type DeletedBlock, type IssueBlock, type IssueBlockSet, type RelayIssue, @@ -29,6 +30,8 @@ import { putBlockSet, type BlockRevision, } from './blocksStore'; +import { BlocksError } from './blocksErrors'; +import { assertEditable, byPosition, type SponsorDocUrls } from './blocksLayout'; import { MAX_RELAY_BODY_BYTES, RelayError, relayBodyBytes, relayClient } from './blocksRelay'; export interface BlockActor { @@ -36,16 +39,7 @@ export interface BlockActor { name: string | null; } -export class BlocksError extends Error { - constructor( - message: string, - public readonly status: number, - public readonly code: string, - public readonly detail: Record = {}, - ) { - super(message); - } -} +export { BlocksError } from './blocksErrors'; type NewRevision = Omit; @@ -85,6 +79,9 @@ export async function importBlocks( relay: { target: input.target, issueKey: remote.key || input.issueKey }, relayIssue: relayIssueSummary(remote), blocks, + deleted: [], + orderBase: blocks.map((block) => block.relayBlockId as number), + orderDirty: false, version: 1, lastSync: { at: now, byName: actor.name, summary: `imported ${blocks.length} blocks` }, createdAt: now, @@ -128,10 +125,12 @@ export async function editBlock( blockId: string, input: { data: unknown; expectedVersion: unknown }, actor: BlockActor, + urls: SponsorDocUrls = {}, ): Promise<{ set: IssueBlockSet; block: IssueBlock; changed: boolean }> { const set = await requireBlockSet(client, issueId); const block = set.blocks.find((item) => item.id === blockId); if (!block) throw new BlocksError(`Issue ${issueId} has no block ${blockId}.`, 404, 'block_not_found'); + assertEditable(block, urls); if (input.expectedVersion !== block.version) { throw new BlocksError( `Block ${blockId} is at version ${block.version}, not ${String(input.expectedVersion)}: it changed since you opened it. Reload, then edit again.`, @@ -178,8 +177,11 @@ export interface SyncResult { dryRun: boolean; relay: { target: RelayTarget; url: string; issueKey: string }; plan: SyncStep[]; + order: SyncPlan['order']; pushed: number[]; pulled: number[]; + created: number[]; + deleted: number[]; summary: string; set: IssueBlockSet; } @@ -190,22 +192,48 @@ function summarize(plan: SyncPlan): string { return [...counts.entries()].map(([action, count]) => `${count} ${action}`).join(', ') || 'no blocks'; } -/** Three-way sync with Relay. Refuses as a whole on any conflict. */ + +/** Keep only the steps of the given blocks (a scoped sync never touches the rest). */ +function scopePlan(plan: SyncPlan, only: Set, pullIsConflict: boolean): SyncPlan { + const steps = plan.steps + .filter((step) => step.blockId !== null && only.has(step.blockId)) + .map((step): SyncStep => (pullIsConflict && step.action === 'pull' + ? { ...step, action: 'conflict', reason: `${step.reason}; the sponsor doc is the source of truth for this block, so Relay's copy differs from the doc` } + : step)); + return { + steps, + conflicts: steps.filter((step) => step.action === 'conflict'), + pushes: steps.filter((step) => step.action === 'push'), + creates: steps.filter((step) => step.action === 'create'), + deletes: steps.filter((step) => step.action === 'delete'), + pulls: steps.filter((step) => step.action === 'pull' || step.action === 'add' || step.action === 'remove'), + order: { action: 'none', reason: 'scoped sync' }, + }; +} + +/** + * Three-way sync with Relay. Refuses as a whole on any conflict. `only` limits + * the sync to the given DataOps block ids (the automatic sponsor-doc sync), so + * other pending edits and other conflicts are neither pushed nor reported. + */ export async function syncBlocks( client: DynamoDBDocumentClient, issueId: string, - options: { dryRun: boolean }, + options: { dryRun: boolean; only?: string[]; pullIsConflict?: boolean }, actor: BlockActor, ): Promise { const set = await requireBlockSet(client, issueId); const relay = await relayClient(set.relay.target); const remote = await relay.getIssue(set.relay.issueKey); - const plan = planSync(set.blocks, remote); + const full = planSync(set.blocks, remote, { deleted: set.deleted, orderBase: set.orderBase, orderDirty: set.orderDirty }); + const scoped = Boolean(options.only); + const plan = options.only ? scopePlan(full, new Set(options.only), Boolean(options.pullIsConflict)) : full; const where = { target: set.relay.target, url: relay.url, issueKey: set.relay.issueKey }; if (plan.conflicts.length) { throw new BlocksError( - `Sync refused: ${plan.conflicts.length} block(s) changed both in DataOps and in Relay since the last sync. ` + + `Sync refused: ${plan.conflicts.length} change(s) conflict between DataOps and Relay since the last sync ` + + `(${plan.conflicts.map((step) => `${step.type}${step.relayBlockId ? ` #${step.relayBlockId}` : ''}: ${step.reason}`).join('; ')}). ` + 'Nothing was written. Resolve each conflict by making both sides equal (copy one into the other), then sync again.', 409, 'blocks_sync_conflict', @@ -213,7 +241,8 @@ export async function syncBlocks( ); } const campaignStatus = remote.campaign?.status || null; - if (plan.pushes.length && campaignStatus && !EDITABLE_CAMPAIGN_STATUSES.has(campaignStatus)) { + const writes = plan.pushes.length + plan.creates.length + plan.deletes.length + (plan.order.action === 'push' ? 1 : 0); + if (writes && campaignStatus && !EDITABLE_CAMPAIGN_STATUSES.has(campaignStatus)) { throw new BlocksError( `Sync refused: Relay issue ${set.relay.issueKey} has a ${campaignStatus} campaign, so its blocks are no longer edited. Nothing was written.`, 409, @@ -222,7 +251,7 @@ export async function syncBlocks( ); } const localById = new Map(set.blocks.map((block) => [block.id, block])); - for (const step of plan.pushes) { + for (const step of [...plan.pushes, ...plan.creates]) { const block = localById.get(step.blockId as string) as IssueBlock; const bytes = relayBodyBytes(block.type, block.data); if (bytes > MAX_RELAY_BODY_BYTES) { @@ -234,59 +263,120 @@ export async function syncBlocks( ); } } + const empty = { pushed: [], pulled: [], created: [], deleted: [] }; if (options.dryRun) { - return { dryRun: true, relay: where, plan: plan.steps, pushed: [], pulled: [], summary: summarize(plan), set }; + return { dryRun: true, relay: where, plan: plan.steps, order: plan.order, ...empty, summary: summarize(plan), set }; } const now = new Date().toISOString(); + const key = set.relay.issueKey; const remoteById = new Map(remote.blocks.map((block) => [block.id, block])); const blocks = new Map(set.blocks.map((block) => [block.id, { ...block }])); + let tombstones: DeletedBlock[] = [...(set.deleted || [])]; const revisions: NewRevision[] = []; const pushed: number[] = []; const pulled: number[] = []; + const created: number[] = []; + const deleted: number[] = []; let failure: unknown = null; + let wrote = false; + const stamp = (block: IssueBlock, saved: { type: string; data: Record; updated_at: string }) => { + const savedHash = blockHash(saved.type, saved.data); + if (savedHash !== blockHash(block.type, block.data)) { + // Relay normalized the content; record what it actually stored. + revisions.push({ + blockId: block.id, + relayBlockId: block.relayBlockId, + blockType: saved.type, + origin: 'relay-pull', + createdAt: now, + actorUserId: actor.id, + actorName: actor.name, + relayActor: 'relay normalization on push', + before: block.data, + after: { ...saved.data }, + }); + block.data = { ...saved.data }; + block.type = saved.type; + block.version += 1; + } + block.base = { hash: savedHash, relayUpdatedAt: saved.updated_at, syncedAt: now }; + }; - // Pushes first, one block per request; each re-reads the Relay block right - // before writing so an edit made in Relay since the plan is not overwritten. - for (const step of plan.pushes) { - const block = blocks.get(step.blockId as string) as IssueBlock; - const seen = remoteById.get(block.relayBlockId)!; - try { - const fresh = await relay.getBlock(set.relay.issueKey, block.relayBlockId); + try { + // Pushes first, one block per request; each re-reads the Relay block right + // before writing so an edit made in Relay since the plan is not overwritten. + for (const step of plan.pushes) { + const block = blocks.get(step.blockId as string) as IssueBlock; + const blockId = block.relayBlockId as number; + const seen = remoteById.get(blockId)!; + const fresh = await relay.getBlock(key, blockId); if (fresh.updated_at !== seen.updated_at || blockHash(fresh.type, fresh.data) !== blockHash(seen.type, seen.data)) { throw new BlocksError( - `Sync stopped: Relay block ${block.relayBlockId} changed during the sync (by ${fresh.updated_by || 'unknown'} at ${fresh.updated_at}). ` + + `Sync stopped: Relay block ${blockId} changed during the sync (by ${fresh.updated_by || 'unknown'} at ${fresh.updated_at}). ` + `It was not overwritten. ${pushed.length} block(s) pushed before this were saved; sync again to see the conflict.`, 409, 'blocks_sync_conflict', ); } - const saved = await relay.putBlock(set.relay.issueKey, block.relayBlockId, block.type, block.data); - const savedHash = blockHash(saved.type, saved.data); - if (savedHash !== blockHash(block.type, block.data)) { - // Relay normalized the content; record what it actually stored. - revisions.push({ - blockId: block.id, - relayBlockId: block.relayBlockId, - blockType: saved.type, - origin: 'relay-pull', - createdAt: now, - actorUserId: actor.id, - actorName: actor.name, - relayActor: 'relay normalization on push', - before: block.data, - after: { ...saved.data }, - }); - block.data = { ...saved.data }; - block.type = saved.type; - block.version += 1; + const saved = await relay.putBlock(key, blockId, block.type, block.data); + wrote = true; + stamp(block, saved); + remoteById.set(saved.id, saved); + pushed.push(blockId); + } + // Deletes: only when Relay's copy is still what DataOps last saw. + for (const step of plan.deletes) { + const gone = tombstones.find((item) => item.id === step.blockId) as DeletedBlock; + const fresh = await relay.getBlock(key, gone.relayBlockId); + if (blockHash(fresh.type, fresh.data) !== gone.baseHash) { + throw new BlocksError( + `Sync stopped: Relay block ${gone.relayBlockId} was edited in Relay (by ${fresh.updated_by || 'unknown'} at ${fresh.updated_at}) after you deleted it here. It was not deleted.`, + 409, + 'blocks_sync_conflict', + ); } - block.base = { hash: savedHash, relayUpdatedAt: saved.updated_at, syncedAt: now }; + await relay.deleteBlock(key, gone.relayBlockId); + wrote = true; + tombstones = tombstones.filter((item) => item.id !== gone.id); + deleted.push(gone.relayBlockId); + } + // Creates: blocks added in DataOps, at their DataOps position. + const ordered = byPosition([...blocks.values()]); + for (const step of plan.creates) { + const block = blocks.get(step.blockId as string) as IssueBlock; + const saved = await relay.postBlock(key, block.type, block.data, ordered.findIndex((item) => item.id === block.id)); + wrote = true; + block.relayBlockId = saved.id; + stamp(block, saved); remoteById.set(saved.id, saved); - pushed.push(block.relayBlockId); + created.push(saved.id); + } + // Order: make Relay's order match DataOps' (the move only changes position). + if (plan.order.action === 'push' || (plan.creates.length && plan.order.action !== 'pull')) { + const live = (await relay.getIssue(key)).blocks; + const current = [...live].sort((a, b) => a.position - b.position).map((block) => block.id); + const wanted = byPosition([...blocks.values()]) + .map((block) => block.relayBlockId) + .filter((id): id is number => id !== null && current.includes(id)); + for (let index = 0; index < wanted.length; index += 1) { + if (current[index] === wanted[index]) continue; + await relay.moveBlock(key, wanted[index], index); + wrote = true; + current.splice(current.indexOf(wanted[index]), 1); + current.splice(index, 0, wanted[index]); + } + } + } catch (error) { + failure = error; + } + + let finalIssue = remote; + if (wrote || plan.order.action === 'pull') { + try { + finalIssue = await relay.getIssue(key); } catch (error) { - failure = error; - break; + failure = failure || error; } } @@ -294,7 +384,7 @@ export async function syncBlocks( for (const step of plan.steps) { if (step.action === 'pull') { const block = blocks.get(step.blockId as string)!; - const source = remoteById.get(block.relayBlockId)!; + const source = remoteById.get(block.relayBlockId as number)!; revisions.push({ blockId: block.id, relayBlockId: block.relayBlockId, @@ -316,9 +406,9 @@ export async function syncBlocks( updatedByName: actor.name, base: { hash: blockHash(source.type, source.data), relayUpdatedAt: source.updated_at, syncedAt: now }, }); - pulled.push(block.relayBlockId); + pulled.push(source.id); } else if (step.action === 'add') { - const source = remoteById.get(step.relayBlockId)!; + const source = remoteById.get(step.relayBlockId as number)!; const block = blockFromRelay(source, now, actor); blocks.set(block.id, block); revisions.push({ @@ -348,29 +438,35 @@ export async function syncBlocks( before: block.data, after: null, }); - pulled.push(block.relayBlockId); + pulled.push(block.relayBlockId as number); } else if (step.action === 'in_sync') { - const block = blocks.get(step.blockId as string)!; - const source = remoteById.get(block.relayBlockId)!; - block.base = { hash: blockHash(source.type, source.data), relayUpdatedAt: source.updated_at, syncedAt: now }; + const block = blocks.get(step.blockId as string); + const source = step.relayBlockId === null ? undefined : remoteById.get(step.relayBlockId); + if (block && source) block.base = { hash: blockHash(source.type, source.data), relayUpdatedAt: source.updated_at, syncedAt: now }; + else if (!block) tombstones = tombstones.filter((item) => item.id !== step.blockId); } } } - // Block order follows Relay (blocks are added and reordered there). - for (const block of blocks.values()) { - const source = remoteById.get(block.relayBlockId); - if (source) block.position = source.position; - } + // Block order follows Relay once the sync is done; unpushed blocks go last. + const finalOrder = [...finalIssue.blocks].sort((a, b) => a.position - b.position).map((block) => block.id); + const rank = (block: IssueBlock) => { + const at = block.relayBlockId === null ? -1 : finalOrder.indexOf(block.relayBlockId); + return at < 0 ? finalOrder.length + block.position : at; + }; + const sorted = [...blocks.values()].sort((a, b) => rank(a) - rank(b)).map((block, index) => ({ ...block, position: index })); const summary = failure - ? `stopped after pushing ${pushed.length}: ${(failure as Error).message}` - : `${summarize(plan)}; pushed ${pushed.length}, pulled ${pulled.length}`; + ? `stopped after ${pushed.length} push(es), ${created.length} create(s), ${deleted.length} delete(s): ${(failure as Error).message}` + : `${summarize(plan)}; pushed ${pushed.length}, created ${created.length}, deleted ${deleted.length}, pulled ${pulled.length}`; const next: IssueBlockSet = { ...set, - relayIssue: relayIssueSummary(remote), - blocks: [...blocks.values()].sort((a, b) => a.position - b.position), + relayIssue: scoped ? set.relayIssue : relayIssueSummary(finalIssue), + blocks: sorted, + deleted: tombstones, + orderBase: failure || scoped ? set.orderBase : finalOrder, + orderDirty: failure || scoped ? set.orderDirty : false, version: set.version + 1, - lastSync: { at: now, byName: actor.name, summary }, + lastSync: scoped ? set.lastSync : { at: now, byName: actor.name, summary }, updatedAt: now, }; await putBlockSet(client, next, set.version); @@ -379,5 +475,5 @@ export async function syncBlocks( if (failure instanceof BlocksError || failure instanceof RelayError) throw failure; throw new BlocksError(`Sync stopped: ${(failure as Error).message}`, 502, 'blocks_sync_failed'); } - return { dryRun: false, relay: where, plan: plan.steps, pushed, pulled, summary, set: next }; + return { dryRun: false, relay: where, plan: plan.steps, order: plan.order, pushed, pulled, created, deleted, summary, set: next }; } diff --git a/backend/src/newsletter/sponsorBlocks.ts b/backend/src/newsletter/sponsorBlocks.ts new file mode 100644 index 00000000..acc5d469 --- /dev/null +++ b/backend/src/newsletter/sponsorBlocks.ts @@ -0,0 +1,435 @@ +/** + * Automatic sync of a sponsor document into its newsletter issue. + * + * On every sponsor-doc save, the issue's sponsor block for that slot (and the + * Relay copy of it) is rebuilt from the doc: title, intro -> body, bullets, + * closing, ctaText/ctaUrl, graphics -> image_url/image_link. When the doc owns + * the primary slot, subjectLine/previewText also become the Relay issue's + * subject (with the " | DataTalks.Club Weekly" suffix) and preview text. + * + * Sponsor blocks are content read-only in the issue editor, so this is the only + * writer of their content. It never overwrites silently: if the Relay block (or + * subject) was edited in Relay since the last sync and differs from the doc, the + * sync fails loudly (unless `force`), and every failure is recorded on the + * issue, returned to the doc page and raised as a notification. + */ +import type { DynamoDBDocumentClient } from '@aws-sdk/lib-dynamodb'; +import { + BLOCK_TYPES, + BlockValidationError, + blockHash, + newBlockId, + validateBlockData, + type BlockData, + type IssueBlock, + type IssueBlockSet, + type SponsorSyncStatus, +} from './blocks'; +import { BlocksError } from './blocksErrors'; +import { byPosition, renumber, type SponsorSlotKind } from './blocksLayout'; +import { RelayError, relayClient } from './blocksRelay'; +import { appendBlockRevisions, getBlockSet, putBlockSet, BlockSetVersionConflict } from './blocksStore'; +import { syncBlocks, type BlockActor } from './blocksSync'; +import { listNewsletterIssues, type NewsletterIssue } from '../db/newsletterIssues'; +import { createNotification } from '../db/notifications'; +import type { SponsorDoc } from '../db/sponsorDocs'; + +export const SUBJECT_SUFFIX = ' | DataTalks.Club Weekly'; +const BLOCK_TYPE: Record = { primary: 'sponsor', secondary: 'sponsor_secondary' }; + +const text = (value: unknown) => String(value ?? '').trim(); + +/** One bullet per line, list markers stripped. */ +export function normalizeBullets(raw: unknown): string { + return String(raw || '') + .split(/\r?\n/) + .map((line) => line.replace(/^\s*(?:[-*•→▸▪◦]|\d+[.)])\s*/u, '').trim()) + .filter(Boolean) + .join('\n'); +} + +/** Relay block data for a sponsor doc's content; empty fields are omitted. */ +export function sponsorBlockData(doc: Pick): BlockData { + const content = (doc.content || {}) as Record; + const standalone = doc.template === 'newsletter-standalone'; + const body = standalone ? [text(content.intro), text(content.mainBodyOpening)].filter(Boolean).join('\n\n') : text(content.intro); + const ctaText = standalone ? text(content.closingCtaText) || text(content.earlyCtaText) : text(content.ctaText); + const ctaUrl = standalone ? text(content.closingCtaUrl) || text(content.earlyCtaUrl) : text(content.ctaUrl); + const imageUrl = text(content.graphicsUrl); + const data: Record = { + kicker: 'SPONSORED', + title: text(content.title), + image_url: imageUrl, + image_link: imageUrl ? ctaUrl : '', + body, + bullets: normalizeBullets(content.bullets), + closing: text(content.closing), + cta_text: ctaText, + cta_url: ctaUrl, + }; + return Object.fromEntries(Object.entries(data).filter(([, value]) => value)); +} + +export function sponsorSubject(doc: Pick): { subject: string; previewText: string } | null { + const content = (doc.content || {}) as Record; + const line = text(content.subjectLine); + if (!line) return null; + return { subject: `${line}${SUBJECT_SUFFIX}`, previewText: text(content.previewText) }; +} + +export const docIdFromUrl = (url: string | undefined): string => { + const match = /([^/?#]+)\/?(?:[?#].*)?$/.exec(String(url || '').trim()); + return match ? decodeURIComponent(match[1]) : ''; +}; + +/** The slots (of any issue in the sponsor doc's neighbourhood) whose document is `docId`. */ +export async function issueSlotsForDoc( + client: DynamoDBDocumentClient, + doc: Pick, +): Promise<{ issue: NewsletterIssue; slot: SponsorSlotKind }[]> { + const day = 86_400_000; + const anchor = doc.publicationDate ? Date.parse(doc.publicationDate) : Date.now(); + const center = Number.isFinite(anchor) ? anchor : Date.now(); + const issues = await listNewsletterIssues( + client, + new Date(Math.min(center, Date.now()) - 120 * day).toISOString().slice(0, 10), + new Date(Math.max(center, Date.now()) + 365 * day).toISOString().slice(0, 10), + ); + const found: { issue: NewsletterIssue; slot: SponsorSlotKind }[] = []; + for (const issue of issues) { + for (const slot of ['primary', 'secondary'] as const) { + if (docIdFromUrl(issue.slots?.[slot]?.documentUrl) === doc.id) found.push({ issue, slot }); + } + } + return found; +} + +export interface SponsorSyncResult { + status: 'ok' | 'failed' | 'skipped'; + message: string; + issueId: string; + slot: SponsorSlotKind; + at: string; + block?: string; + dryRun?: boolean; + changes?: string[]; +} + +export interface SponsorSyncDeps { + /** Hosts an uploaded `data:` image and returns its public https URL. */ + hostDataImage?: (dataUrl: string) => Promise; +} + +function missingRequired(type: string, data: BlockData): string[] { + return (BLOCK_TYPES[type]?.required || []).filter((name) => !data[name] && !BLOCK_TYPES[type].defaults[name]); +} + +/** Where a newly created sponsor block goes: primary right after the intro, secondary after the primary. */ +function sponsorInsertIndex(ordered: IssueBlock[], slot: SponsorSlotKind): number { + if (slot === 'secondary') { + const primary = ordered.findIndex((block) => block.type === 'sponsor'); + if (primary >= 0) return primary + 1; + } + let index = 0; + while (index < ordered.length && ordered[index].type === 'intro') index += 1; + return index; +} + +async function recordStatus( + client: DynamoDBDocumentClient, + issueId: string, + slot: SponsorSlotKind, + status: SponsorSyncStatus, +): Promise { + for (let attempt = 0; attempt < 3; attempt += 1) { + const set = await getBlockSet(client, issueId); + if (!set) return; + try { + await putBlockSet(client, { ...set, sponsorSync: { ...(set.sponsorSync || {}), [slot]: status }, version: set.version + 1 }, set.version); + return; + } catch (error) { + if (!(error instanceof BlockSetVersionConflict) || attempt === 2) throw error; + } + } +} + +/** Sync one slot of one issue from its sponsor doc. Throws only for unexpected bugs; expected failures are reported in the result. */ +export async function syncSponsorSlot( + client: DynamoDBDocumentClient, + issue: Pick & { issueNumber?: number }, + slot: SponsorSlotKind, + doc: SponsorDoc, + actor: BlockActor, + options: { dryRun?: boolean; force?: boolean } = {}, + deps: SponsorSyncDeps = {}, +): Promise { + const at = new Date().toISOString(); + const base = { issueId: issue.id, slot, at }; + const fail = async (message: string): Promise => { + if (!options.dryRun) { + await recordStatus(client, issue.id, slot, { at, ok: false, error: message, docId: doc.id }).catch(() => undefined); + console.error(JSON.stringify({ event: 'newsletter_sponsor_sync_failed', level: 'ERROR', issueId: issue.id, slot, docId: doc.id, message })); + try { + await createNotification(client, { + type: 'newsletter-sponsor-sync-failed', + message: `Sponsor doc "${doc.title || doc.id}" did not sync to newsletter issue ${issue.issueNumber ? `#${issue.issueNumber}` : issue.id} (${slot} slot): ${message}`, + metadata: { docId: doc.id, issueId: issue.id, slot }, + }); + } catch (notifyError) { + console.error('Failed to persist newsletter sponsor sync alert notification:', notifyError); + } + } + return { ...base, status: 'failed', message }; + }; + const skip = (message: string): SponsorSyncResult => ({ ...base, status: 'skipped', message }); + + const set = await getBlockSet(client, issue.id); + if (!set) { + return skip( + `Issue ${issue.issueNumber ? `#${issue.issueNumber}` : issue.id} has no content blocks in DataOps yet, so nothing was synced. ` + + 'Import them once: dataops newsletter blocks --import .', + ); + } + const type = BLOCK_TYPE[slot]; + let data = sponsorBlockData(doc); + const existing = set.blocks.filter((block) => block.type === type); + if (existing.length > 1) return fail(`Issue has ${existing.length} "${type}" blocks (${existing.map((b) => b.id).join(', ')}); expected one.`); + const current = existing[0]; + if (current?.data.meta) data = { ...data, meta: current.data.meta }; + const missing = missingRequired(type, data); + if (missing.length) { + return skip(`The sponsor doc is not complete enough to publish yet (missing: ${missing.join(', ')}); the issue block was not changed.`); + } + try { + if (/^data:/i.test(data.image_url || '')) { + if (!deps.hostDataImage) return await fail('The doc has an uploaded graphics image but image hosting is unavailable here.'); + data = { ...data, image_url: await deps.hostDataImage(data.image_url) }; + } + data = validateBlockData(type, data); + } catch (error) { + if (error instanceof BlockValidationError) { + return fail(`The sponsor doc content is not valid for a newsletter block: ${error.message}`); + } + return fail(`Preparing the sponsor block failed: ${(error as Error).message}`); + } + + const changes: string[] = []; + let blockId = current?.id || ''; + if (options.dryRun) { + changes.push(current ? (blockHash(type, current.data) === blockHash(type, data) ? 'block unchanged' : 'block would be updated') : 'block would be added'); + } else { + const now = new Date().toISOString(); + const ordered = byPosition(set.blocks); + let next: IssueBlockSet; + if (!current) { + const index = sponsorInsertIndex(ordered, slot); + blockId = newBlockId(); + const block: IssueBlock = { + id: blockId, relayBlockId: null, position: index, type, data, version: 1, updatedAt: now, + updatedBy: actor.id, updatedByName: actor.name, base: { hash: '', relayUpdatedAt: '', syncedAt: '' }, + }; + ordered.splice(index, 0, block); + next = { ...set, blocks: renumber(ordered), orderDirty: true, version: set.version + 1, updatedAt: now }; + await putBlockSet(client, next, set.version); + await appendBlockRevisions(client, issue.id, [{ + blockId, relayBlockId: null, blockType: type, origin: 'sponsor-doc', createdAt: now, actorUserId: actor.id, + actorName: actor.name, detail: `created from sponsor doc ${doc.id}`, before: null, after: data, + }]); + changes.push('block added'); + } else if (blockHash(type, current.data) !== blockHash(type, data)) { + const updated = { ...current, data, version: current.version + 1, updatedAt: now, updatedBy: actor.id, updatedByName: actor.name }; + next = { ...set, blocks: set.blocks.map((block) => (block.id === current.id ? updated : block)), version: set.version + 1, updatedAt: now }; + await putBlockSet(client, next, set.version); + await appendBlockRevisions(client, issue.id, [{ + blockId, relayBlockId: current.relayBlockId, blockType: type, origin: 'sponsor-doc', createdAt: now, + actorUserId: actor.id, actorName: actor.name, detail: `updated from sponsor doc ${doc.id}`, before: current.data, after: data, + }]); + changes.push('block updated'); + } + } + + try { + if (options.force && current?.relayBlockId && !options.dryRun) { + // Explicit overwrite: take Relay's current copy as the base so the push replaces it. + const relay = await relayClient(set.relay.target); + const live = await relay.getBlock(set.relay.issueKey, current.relayBlockId); + const fresh = (await getBlockSet(client, issue.id)) as IssueBlockSet; + const blocks = fresh.blocks.map((block) => (block.id === blockId + ? { ...block, base: { hash: blockHash(live.type, live.data), relayUpdatedAt: live.updated_at, syncedAt: at } } + : block)); + await putBlockSet(client, { ...fresh, blocks, version: fresh.version + 1 }, fresh.version); + } + const result = await syncBlocks(client, issue.id, { dryRun: Boolean(options.dryRun), only: [blockId], pullIsConflict: true }, actor); + if (result.pushed.length || result.created.length) changes.push('Relay block written'); + if (slot === 'primary') { + const wanted = sponsorSubject(doc); + if (wanted) changes.push(...(await syncSubject(client, issue.id, set, wanted, options))); + } + } catch (error) { + if (error instanceof BlocksError || error instanceof RelayError || error instanceof BlockSetVersionConflict) { + return fail(`${error.message}${error instanceof BlocksError && error.code === 'blocks_sync_conflict' ? ' To overwrite Relay with the doc anyway: dataops newsletter sponsor-sync --slot ' + slot + ' --force.' : ''}`); + } + return fail((error as Error).message || 'Unexpected sync error'); + } + const message = changes.length ? changes.join('; ') : 'already in sync with the sponsor doc'; + if (!options.dryRun) await recordStatus(client, issue.id, slot, { at, ok: true, docId: doc.id, summary: message }); + return { ...base, status: 'ok', message, block: blockId, dryRun: options.dryRun, changes }; +} + +/** Subject / preview text from the primary doc, three-way against what DataOps last saw in Relay. */ +async function syncSubject( + client: DynamoDBDocumentClient, + issueId: string, + set: IssueBlockSet, + wanted: { subject: string; previewText: string }, + options: { dryRun?: boolean; force?: boolean }, +): Promise { + const relay = await relayClient(set.relay.target); + const live = await relay.getIssue(set.relay.issueKey); + const lastKnown = set.relayIssue; + const fields: { subject?: string; preview_text?: string } = {}; + const edited = (now: string, known: string, target: string) => now !== known && now !== target; + if (live.subject !== wanted.subject) { + if (edited(live.subject || '', lastKnown.subject, wanted.subject) && !options.force) { + throw new BlocksError( + `Relay subject "${live.subject}" was changed in Relay since the last sync and differs from the sponsor doc ("${wanted.subject}"). Nothing was overwritten.`, + 409, 'blocks_sync_conflict', + ); + } + fields.subject = wanted.subject; + } + if ((live.preview_text || '') !== wanted.previewText && wanted.previewText) { + if (edited(live.preview_text || '', lastKnown.previewText, wanted.previewText) && !options.force) { + throw new BlocksError( + `Relay preview text was changed in Relay since the last sync and differs from the sponsor doc. Nothing was overwritten.`, + 409, 'blocks_sync_conflict', + ); + } + fields.preview_text = wanted.previewText; + } + if (!Object.keys(fields).length) return []; + const status = live.campaign?.status; + if (status && status !== 'draft') { + throw new BlocksError(`Relay issue ${set.relay.issueKey} has a ${status} campaign; its subject is no longer edited.`, 409, 'blocks_campaign_locked'); + } + if (options.dryRun) return ['subject/preview would be updated']; + const saved = await relay.putIssueFields(set.relay.issueKey, fields); + const fresh = (await getBlockSet(client, issueId)) as IssueBlockSet; + await putBlockSet( + client, + { ...fresh, relayIssue: { ...fresh.relayIssue, subject: saved.subject || '', previewText: saved.preview_text || '' }, version: fresh.version + 1 }, + fresh.version, + ); + return ['Relay subject/preview updated']; +} + +/** Sync a saved sponsor doc into every slot of every issue that links it. Never throws; the doc save must not fail because of it. */ +export async function syncSponsorDoc( + client: DynamoDBDocumentClient, + doc: SponsorDoc, + actor: BlockActor, + deps: SponsorSyncDeps = {}, +): Promise { + try { + const linked = await issueSlotsForDoc(client, doc); + const results: SponsorSyncResult[] = []; + for (const { issue, slot } of linked) results.push(await syncSponsorSlot(client, issue, slot, doc, actor, {}, deps)); + return results; + } catch (error) { + console.error(JSON.stringify({ event: 'newsletter_sponsor_sync_crashed', level: 'ERROR', docId: doc.id, message: (error as Error).message })); + try { + await createNotification(client, { + type: 'newsletter-sponsor-sync-failed', + message: `Sponsor doc "${doc.title || doc.id}" could not be synced to the newsletter: ${(error as Error).message}`, + metadata: { docId: doc.id }, + }); + } catch { /* already logged above */ } + return [{ status: 'failed', message: (error as Error).message, issueId: '', slot: 'primary', at: new Date().toISOString() }]; + } +} + +/** + * A secondary sponsor block cannot be deleted by hand; it leaves the issue (and + * Relay) when its slot's sponsor document is removed from the issue. The main + * block is pinned and stays. Never throws: failures are recorded and alerted. + */ +export async function releaseRemovedSponsorBlocks( + client: DynamoDBDocumentClient, + before: Pick, + after: Pick, + actor: BlockActor, +): Promise { + if (!before.slots?.secondary?.documentUrl || after.slots?.secondary?.documentUrl) return null; + const at = new Date().toISOString(); + try { + const set = await getBlockSet(client, before.id); + const block = set?.blocks.find((item) => item.type === 'sponsor_secondary'); + if (!set || !block) return null; + const now = at; + const deleted = [...(set.deleted || [])]; + if (block.relayBlockId !== null) { + deleted.push({ + id: block.id, relayBlockId: block.relayBlockId, type: block.type, data: block.data, + baseHash: block.base.hash || blockHash(block.type, block.data), deletedAt: now, deletedByName: actor.name, + }); + } + const next: IssueBlockSet = { + ...set, + blocks: renumber(byPosition(set.blocks).filter((item) => item.id !== block.id)), + deleted, + version: set.version + 1, + updatedAt: now, + }; + await putBlockSet(client, next, set.version); + await appendBlockRevisions(client, before.id, [{ + blockId: block.id, relayBlockId: block.relayBlockId, blockType: block.type, origin: 'delete', createdAt: now, + actorUserId: actor.id, actorName: actor.name, detail: 'secondary slot removed from the issue; block removed', before: block.data, after: null, + }]); + if (block.relayBlockId !== null) await syncBlocks(client, before.id, { dryRun: false, only: [block.id] }, actor); + return { status: 'ok', message: 'secondary sponsor block removed with its slot', issueId: before.id, slot: 'secondary', at, block: block.id }; + } catch (error) { + const message = (error as Error).message; + console.error(JSON.stringify({ event: 'newsletter_sponsor_release_failed', level: 'ERROR', issueId: before.id, message })); + try { + await createNotification(client, { + type: 'newsletter-sponsor-sync-failed', + message: `Removing the secondary sponsor block of newsletter issue ${before.issueNumber ? `#${before.issueNumber}` : before.id} failed: ${message}`, + metadata: { issueId: before.id, slot: 'secondary' }, + }); + } catch { /* logged above */ } + return { status: 'failed', message, issueId: before.id, slot: 'secondary', at }; + } +} + +export interface DocNewsletterSync { + status: 'ok' | 'failed' | 'skipped'; + message: string; + issueId?: string; + at: string; +} + +/** What the doc page shows: the worst result of a save's sync. */ +export function summarizeSyncResults(results: SponsorSyncResult[]): DocNewsletterSync | null { + if (!results.length) return null; + const pick = results.find((item) => item.status === 'failed') || results.find((item) => item.status === 'ok') || results[0]; + const message = results.length > 1 ? results.map((item) => `${item.slot}: ${item.message}`).join(' | ') : pick.message; + return { status: pick.status, message, issueId: pick.issueId || undefined, at: pick.at }; +} + +/** Last recorded sync outcome for a doc (shown on GET so a failure stays visible after reload). */ +export async function newsletterSyncForDoc(client: DynamoDBDocumentClient, doc: SponsorDoc): Promise { + if (!String(doc.template).startsWith('newsletter-')) return null; + const linked = await issueSlotsForDoc(client, doc); + const found: SponsorSyncResult[] = []; + for (const { issue, slot } of linked) { + const set = await getBlockSet(client, issue.id); + const status = set?.sponsorSync?.[slot]; + if (status && status.docId === doc.id) { + found.push({ + status: status.ok ? 'ok' : 'failed', message: status.ok ? status.summary || 'in sync' : status.error || 'failed', + issueId: issue.id, slot, at: status.at, + }); + } + } + return summarizeSyncResults(found); +} diff --git a/backend/src/routes/newsletterBlocks.ts b/backend/src/routes/newsletterBlocks.ts index be98bcce..55e01e5c 100644 --- a/backend/src/routes/newsletterBlocks.ts +++ b/backend/src/routes/newsletterBlocks.ts @@ -6,6 +6,11 @@ * PUT /blocks/:blockId {data, version}: edit one block (records a revision) * POST /blocks/sync {dryRun}: three-way sync with Relay (409 on conflict) * GET /blocks/revisions every revision, oldest first (?block= filters) + * GET /blocks/types block types (Relay's catalogue) with fields and defaults + * POST /blocks {type, data?, position?}: add a block + * POST /blocks/:blockId/move {direction: up|down} or {to}: reorder + * DELETE /blocks/:blockId delete a block + * POST /blocks/sponsor-sync {slot, dryRun?, force?}: rebuild a sponsor block from its doc * * See ../newsletter/blocksSync.ts for why the sync is two-way. */ @@ -26,18 +31,45 @@ import { type IssueBlockSet, type RelayTarget, } from '../newsletter/blocks'; -import { BlockSetVersionConflict, listBlockRevisions } from '../newsletter/blocksStore'; +import { BlockSetVersionConflict, getBlockSet, listBlockRevisions } from '../newsletter/blocksStore'; import { RelayError } from '../newsletter/blocksRelay'; import { BlocksError, editBlock, importBlocks, requireBlockSet, syncBlocks, type BlockActor } from '../newsletter/blocksSync'; +import { addBlock, deleteBlock, moveBlock } from '../newsletter/blocksOps'; +import { byPosition, pinnedIndex, sponsorSlotOf, type SponsorDocUrls } from '../newsletter/blocksLayout'; +import { docIdFromUrl, syncSponsorSlot } from '../newsletter/sponsorBlocks'; +import { getSponsorDoc } from '../db/sponsorDocs'; +import { savePublicImage } from '../publicImages'; +import { publicImagePayload } from './publicImages'; const blockActor = (actor: VerifiedActor): BlockActor => ({ id: actor.id, name: actor.user?.name || actor.user?.email || null }); -/** The set as the API returns it: labels, field specs and pending-change flags added. */ -export function blockSetView(set: IssueBlockSet) { +/** Host an uploaded `data:image/...` visual and return its public https URL. */ +export function dataImageHost(event: LambdaEvent) { + return async (dataUrl: string): Promise => { + const match = /^data:image\/(?:png|jpe?g|gif|webp);base64,(.+)$/is.exec(dataUrl); + if (!match) throw new Error('The sponsor document graphics is an unsupported data: URL; upload a PNG, JPEG, GIF or WebP.'); + return publicImagePayload(await savePublicImage(Buffer.from(match[1], 'base64')), event).url; + }; +} + +export const sponsorDocUrls = (issue: { slots?: Record }): SponsorDocUrls => ({ + primary: issue.slots?.primary?.documentUrl, + secondary: issue.slots?.secondary?.documentUrl, +}); + +/** The set as the API returns it: labels, field specs, sponsor rules and pending-change flags added. */ +export function blockSetView(set: IssueBlockSet, urls: SponsorDocUrls = {}) { + const ordered = byPosition(set.blocks); + const pin = pinnedIndex(ordered); return { ...set, - blocks: set.blocks.map((block) => { + orderChanged: Boolean(set.orderDirty), + deletedPending: (set.deleted || []).map((gone) => ({ id: gone.id, type: gone.type, label: blockLabel(gone.type), relayBlockId: gone.relayBlockId })), + blocks: ordered.map((block, index) => { const spec = BLOCK_TYPES[block.type]; + const sponsor = sponsorSlotOf(block.type); + const isNew = block.relayBlockId === null; + const changed = isNew || blockHash(block.type, block.data) !== block.base.hash; return { ...block, label: blockLabel(block.type), @@ -48,12 +80,34 @@ export function blockSetView(set: IssueBlockSet) { required: Boolean(spec?.required.includes(name)), default: spec?.defaults[name] || '', })), - changedSinceSync: blockHash(block.type, block.data) !== block.base.hash, + changedSinceSync: changed, + pushState: isNew ? 'new' : changed ? 'edited' : 'in-sync', + sponsor, + readOnly: sponsor !== null, + pinned: sponsor === 'primary', + canMove: sponsor !== 'primary' && !(pin >= 0 && index < pin), + canDelete: sponsor === null, + sponsorDocUrl: sponsor ? urls[sponsor] || null : null, }; }), }; } +export function blockTypesView() { + return Object.entries(BLOCK_TYPES).map(([type, spec]) => ({ + type, + label: spec.label, + addable: sponsorSlotOf(type) === null, + fields: spec.fields.map((name) => ({ + name, + label: FIELD_LABELS[name] || name, + kind: FIELD_KINDS[name] || 'text', + required: spec.required.includes(name), + default: spec.defaults[name] || '', + })), + })); +} + function failure(error: unknown): LambdaResponse { if (error instanceof BlocksError) return json(error.status, { error: error.message, code: error.code, ...error.detail }); if (error instanceof RelayError) return json(error.status, { error: error.message, code: error.code }); @@ -80,10 +134,21 @@ export async function handleNewsletterBlockRoutes( const body = readOnly ? {} : parseJsonObjectEventOrEmpty(event); if (!body) return json(400, { error: 'Invalid JSON' }); + const urls = sponsorDocUrls(issue); + const view = (set: IssueBlockSet) => blockSetView(set, urls); try { if (rest === '' || rest === '/') { + if (method === 'POST') { + const added = await addBlock(client, issue.id, { type: body.type, data: body.data, position: body.position }, urls, actor); + const blocks = view(added.set); + return json(201, { issueId: issue.id, block: blocks.blocks.find((item) => item.id === added.block.id), blocks }); + } + if (method !== 'GET') return json(405, { error: 'Method not allowed' }); + return json(200, { issueId: issue.id, blocks: view(await requireBlockSet(client, issue.id)) }); + } + if (rest === '/types') { if (method !== 'GET') return json(405, { error: 'Method not allowed' }); - return json(200, { issueId: issue.id, blocks: blockSetView(await requireBlockSet(client, issue.id)) }); + return json(200, { issueId: issue.id, types: blockTypesView() }); } if (rest === '/import') { if (method !== 'POST') return json(405, { error: 'Method not allowed' }); @@ -92,12 +157,38 @@ export async function handleNewsletterBlockRoutes( const issueKey = String(body.issueKey || '').trim(); if (!/^[a-z0-9][a-z0-9-]{0,119}$/.test(issueKey)) return json(400, { error: 'issueKey must be a Relay issue key like weekly-304' }); const set = await importBlocks(client, issue.id, { target, issueKey }, actor); - return json(201, { issueId: issue.id, blocks: blockSetView(set) }); + return json(201, { issueId: issue.id, blocks: view(set) }); } if (rest === '/sync') { if (method !== 'POST') return json(405, { error: 'Method not allowed' }); const result = await syncBlocks(client, issue.id, { dryRun: body.dryRun === true }, actor); - return json(200, { issueId: issue.id, ...result, set: undefined, blocks: blockSetView(result.set) }); + return json(200, { issueId: issue.id, ...result, set: undefined, blocks: view(result.set) }); + } + if (rest === '/sponsor-sync') { + if (method !== 'POST') return json(405, { error: 'Method not allowed' }); + const slot = String(body.slot || ''); + if (slot !== 'primary' && slot !== 'secondary') return json(400, { error: 'slot must be primary or secondary', code: 'slot_invalid' }); + const docId = docIdFromUrl(urls[slot]); + if (!docId) return json(422, { error: `The ${slot} slot of this issue has no sponsor document.`, code: 'sponsor_doc_missing' }); + const doc = await getSponsorDoc(client, docId); + if (!doc) return json(404, { error: `Sponsor document ${docId} was not found.`, code: 'sponsor_doc_not_found' }); + const result = await syncSponsorSlot( + client, + issue, + slot, + doc, + actor, + { dryRun: body.dryRun === true, force: body.force === true }, + { hostDataImage: dataImageHost(event) }, + ); + const current = await getBlockSet(client, issue.id); + return json(result.status === 'failed' ? 409 : 200, { + issueId: issue.id, + result, + summary: result.message, + ...(result.status === 'failed' ? { error: result.message, code: 'sponsor_sync_failed' } : {}), + blocks: current ? view(current) : null, + }); } if (rest === '/revisions') { if (method !== 'GET') return json(405, { error: 'Method not allowed' }); @@ -108,12 +199,22 @@ export async function handleNewsletterBlockRoutes( .map((revision) => ({ ...revision, label: blockLabel(revision.blockType), changes: changedFields(revision.before, revision.after) })); return json(200, { issueId: issue.id, relay: set.relay, revisions }); } + const moveMatch = rest.match(/^\/([^/]+)\/move$/); + if (moveMatch) { + if (method !== 'POST') return json(405, { error: 'Method not allowed' }); + const moved = await moveBlock(client, issue.id, decodeURIComponent(moveMatch[1]), { to: body.to, direction: body.direction }, urls, actor); + return json(200, { issueId: issue.id, blocks: view(moved.set) }); + } const blockMatch = rest.match(/^\/([^/]+)$/); if (blockMatch) { - if (method !== 'PUT') return json(405, { error: 'Method not allowed' }); const blockId = decodeURIComponent(blockMatch[1]); - const result = await editBlock(client, issue.id, blockId, { data: body.data, expectedVersion: body.version }, actor); - return json(200, { issueId: issue.id, changed: result.changed, blocks: blockSetView(result.set) }); + if (method === 'DELETE') { + const removed = await deleteBlock(client, issue.id, blockId, urls, actor); + return json(200, { issueId: issue.id, deleted: blockId, blocks: view(removed.set) }); + } + if (method !== 'PUT') return json(405, { error: 'Method not allowed' }); + const result = await editBlock(client, issue.id, blockId, { data: body.data, expectedVersion: body.version }, actor, urls); + return json(200, { issueId: issue.id, changed: result.changed, blocks: view(result.set) }); } return json(404, { error: 'Not found' }); } catch (error) { diff --git a/backend/src/routes/newsletterIssues.ts b/backend/src/routes/newsletterIssues.ts index 058e79e7..3871f8a9 100644 --- a/backend/src/routes/newsletterIssues.ts +++ b/backend/src/routes/newsletterIssues.ts @@ -93,6 +93,7 @@ import { ReportSendError, sendIssueReport } from '../newsletter/reportSend'; import { json, parseJsonObjectEvent } from '../http'; import { handleNewsletterBlockRoutes } from './newsletterBlocks'; import { deleteBlockSet } from '../newsletter/blocksStore'; +import { releaseRemovedSponsorBlocks } from '../newsletter/sponsorBlocks'; const ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/; const KINDS = new Set(['weekly', 'standalone']); @@ -732,6 +733,7 @@ async function updateRoute(id: string, body: Body, event: LambdaEvent, client: D } catch { return json(409, { error: 'Conflicting update' }); } + await releaseRemovedSponsorBlocks(client, existing, next, { id: actor.id, name: actor.user?.name || actor.user?.email || null }); let cardSync = 'unchanged'; let metricsTask = 'none'; let markdownTask = 'none'; @@ -884,6 +886,7 @@ async function writeSlotChange( } catch { return { ok: false, response: json(409, { error: 'Issue changed; reload and retry' }) }; } + await releaseRemovedSponsorBlocks(client, existing, issue, { id: actorId, name: null }); let cardSync = 'unchanged'; try { const synced = await syncIssueSlotTasks(client, existing, issue, actorId); diff --git a/backend/src/routes/sponsorDocs.ts b/backend/src/routes/sponsorDocs.ts index c21a297c..d9420ff2 100644 --- a/backend/src/routes/sponsorDocs.ts +++ b/backend/src/routes/sponsorDocs.ts @@ -57,6 +57,8 @@ import { TeamDirectory } from '../identity/directory'; import { projectCard } from '../identity/projections'; import { recordRequestError } from '../requestErrorLog'; import { createNotification } from '../db/notifications'; +import { newsletterSyncForDoc, summarizeSyncResults, syncSponsorDoc } from '../newsletter/sponsorBlocks'; +import { dataImageHost } from './newsletterBlocks'; import { FileStorageError } from '../storage'; import { savePublicImage } from '../publicImages'; import { extractMultipartImageBuffer, publicImagePayload } from './publicImages'; @@ -1370,11 +1372,12 @@ export async function handleSponsorDocRoutes( return json(404, { error: 'Document not found', code: 'sponsor_doc_not_found' }); } const accessCode = decryptSponsorDocAccessCode(docId, loaded.accessCodeCiphertext); + const newsletterSync = await newsletterSyncForDoc(client, loaded.doc).catch(() => null); return json(200, { - doc: await buildDocResponsePayload(loaded.doc, event, client, { - viewerRole: 'staff', - accessCode, - }), + doc: { + ...(await buildDocResponsePayload(loaded.doc, event, client, { viewerRole: 'staff', accessCode })), + newsletterSync, + }, }); } @@ -1446,11 +1449,19 @@ export async function handleSponsorDocRoutes( await relinkCardToDoc(client, event, updated); } const accessCode = decryptSponsorDocAccessCode(docId, loaded.accessCodeCiphertext); + const newsletterSync = updated && String(updated.template).startsWith('newsletter-') + ? summarizeSyncResults(await syncSponsorDoc( + client, + updated, + { id: access.staffActorId || 'staff', name: access.staffActorName || 'DataOps Staff' }, + { hostDataImage: dataImageHost(event) }, + )) + : null; return json(200, { - doc: await buildDocResponsePayload(updated!, event, client, { - viewerRole: 'staff', - accessCode, - }), + doc: { + ...(await buildDocResponsePayload(updated!, event, client, { viewerRole: 'staff', accessCode })), + newsletterSync, + }, }); } @@ -1473,6 +1484,10 @@ export async function handleSponsorDocRoutes( } try { if (updated && body.timeChoiceIntent !== undefined) await recordGuestPortalTimeChoice(client, updated, body.timeChoiceIntent); } catch (error) { return json(422, { error: (error as Error).message, code: 'guest_time_choice_pending' }); } + if (updated && String(updated.template).startsWith('newsletter-')) { + // The sponsor's own save syncs the issue too; failures are recorded and alerted, never shown to the sponsor. + await syncSponsorDoc(client, updated, { id: 'sponsor-portal', name: updated.sponsorName || 'Sponsor' }, { hostDataImage: dataImageHost(event) }); + } return json(200, { doc: await buildDocResponsePayload(updated!, event, client, { viewerRole: 'sponsor' }), }); From 016a71f12be8115129ea921c18cc4a6aa62eb3aa Mon Sep 17 00:00:00 2001 From: Alexey Grigorev Date: Mon, 23 Nov 2026 13:37:07 +0100 Subject: [PATCH 09/12] Tests: newsletter block add/move/delete, sponsor-block refusals, sponsor-doc auto-sync, slot release --- backend/tests/helpers/fake-relay.ts | 101 +++++ .../tests/newsletter-blocks-structure.test.ts | 351 ++++++++++++++++++ backend/tests/newsletter-blocks.test.ts | 74 +--- 3 files changed, 459 insertions(+), 67 deletions(-) create mode 100644 backend/tests/helpers/fake-relay.ts create mode 100644 backend/tests/newsletter-blocks-structure.test.ts diff --git a/backend/tests/helpers/fake-relay.ts b/backend/tests/helpers/fake-relay.ts new file mode 100644 index 00000000..f98f1e9c --- /dev/null +++ b/backend/tests/helpers/fake-relay.ts @@ -0,0 +1,101 @@ +export type FakeBlock = { id: number; position: number; type: string; data: Record; updated_by: string; updated_at: string }; + +/** An in-memory Relay newsletter API: GET issue, GET/PUT block. */ +export class FakeRelay { + issues = new Map(); + calls: string[] = []; + tick = 0; + /** Runs right before a block GET returns (to simulate a concurrent Relay edit). */ + beforeBlockGet: ((block: FakeBlock) => void) | null = null; + apiKeySeen = ''; + + stamp() { + this.tick += 1; + return `2026-11-23T10:00:${String(this.tick).padStart(2, '0')}+00:00`; + } + + seed(key: string, blocks: Omit[]) { + this.issues.set(key, { + key, + subject: `Subject ${key}`, + campaign: null, + blocks: blocks.map((block) => ({ ...block, updated_by: 'api:dtc-newsletter', updated_at: this.stamp() })), + }); + } + + editInRelay(key: string, id: number, data: Record) { + const block = this.issues.get(key)!.blocks.find((item) => item.id === id)!; + block.data = data; + block.updated_by = 'alexey@datatalks.club'; + block.updated_at = this.stamp(); + } + + nextId = 200; + issueEdits: { subject?: string; preview_text?: string }[] = []; + + private renumber(issue: { blocks: FakeBlock[] }) { + issue.blocks.sort((a, b) => a.position - b.position); + issue.blocks.forEach((block, index) => { block.position = index; }); + } + + fetch = async (url: string | URL | Request, init?: RequestInit): Promise => { + const method = init?.method || 'GET'; + const u = new URL(String(url)); + this.calls.push(`${method} ${u.host}${u.pathname}`); + this.apiKeySeen = String((init?.headers as Record)?.authorization || ''); + const reply = (status: number, body: unknown) => new Response(JSON.stringify(body), { status }); + const match = u.pathname.match(/^\/api\/newsletter-issues\/([^/]+)(\/blocks)?(?:\/(\d+))?$/); + const issue = match && this.issues.get(decodeURIComponent(match[1])); + if (!issue) return reply(404, { errors: { key: 'not_found' } }); + const body = init?.body ? JSON.parse(String(init.body)) : {}; + const payload = () => ({ ...issue, preview_text: this.previews.get(match![1]) || '', updated_at: this.stamp() }); + if (!match![2]) { + if (method === 'PUT') { + this.issueEdits.push(body); + if (typeof body.subject === 'string') issue.subject = body.subject; + if (typeof body.preview_text === 'string') this.previews.set(match![1], body.preview_text); + } + this.renumber(issue); + return reply(200, { issue: payload() }); + } + if (!match![3]) { + if (method !== 'POST') return reply(405, {}); + const block: FakeBlock = { + id: ++this.nextId, position: typeof body.position === 'number' ? body.position - 0.5 : issue.blocks.length, + type: body.type, data: body.data || {}, updated_by: 'api:dtc-newsletter', updated_at: this.stamp(), + }; + issue.blocks.push(block); + this.renumber(issue); + return reply(201, { block }); + } + const block = issue.blocks.find((item) => item.id === Number(match![3])); + if (!block) return reply(404, { errors: { block_id: 'not_found' } }); + if (method === 'GET') { + this.beforeBlockGet?.(block); + return reply(200, { block }); + } + if (method === 'DELETE') { + issue.blocks = issue.blocks.filter((item) => item !== block); + this.renumber(issue); + return reply(200, { deleted: true }); + } + if (body.type) block.type = body.type; + if (body.data) block.data = body.data; + if (body.data || body.type) { + block.updated_by = 'api:dtc-newsletter'; + block.updated_at = this.stamp(); + } + if (typeof body.position === 'number') { + block.position = body.position - 0.5; + this.renumber(issue); + } + return reply(200, { block }); + }; + previews = new Map(); +} + +export const SECRETS: Record = { + 'relay-production.dtc-newsletter-api-key': 'prod-key-123', + 'relay-dev.api-keys': JSON.stringify({ RELAY_API_KEY: 'dev-key-456', RELAY_WEBHOOK: 'x' }), +}; + diff --git a/backend/tests/newsletter-blocks-structure.test.ts b/backend/tests/newsletter-blocks-structure.test.ts new file mode 100644 index 00000000..abf5db45 --- /dev/null +++ b/backend/tests/newsletter-blocks-structure.test.ts @@ -0,0 +1,351 @@ +import { describe, it, before, after, beforeEach } from 'node:test'; +import assert from 'node:assert'; +import { ScanCommand } from '@aws-sdk/lib-dynamodb'; +import type { DynamoDBDocumentClient } from '@aws-sdk/lib-dynamodb'; + +import { getClient } from '../src/db/client'; +import { createTables, startLocal, stopLocal } from '../scripts/local-dynamodb'; +import { buildNewsletterIssue, createNewsletterIssue, getNewsletterIssue } from '../src/db/newsletterIssues'; +import { createSponsorDoc } from '../src/db/sponsorDocs'; +import { TABLE_NOTIFICATIONS } from '../src/db/tableNames'; +import { createUser } from '../src/db/users'; +import { setRelayDepsForTests } from '../src/newsletter/blocksRelay'; +import { releaseRemovedSponsorBlocks } from '../src/newsletter/sponsorBlocks'; +import { humanBearer } from './helpers/human-bearer'; +import { FakeRelay, SECRETS } from './helpers/fake-relay'; + +const DOC_BASE = 'https://ops.dtcdev.click/sponsor-docs/'; + +describe('Newsletter issue blocks: add, move, delete, sponsor rules, sponsor-doc sync', () => { + let client: DynamoDBDocumentClient; + let handler: typeof import('../src/handler').handler; + let token: string; + let userId: string; + let relay: FakeRelay; + let restore: () => void; + let seq = 0; + + 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: 'alexey@datatalks.club', name: 'Alexey', passwordHash: 'x', role: 'admin' }); + userId = user.id; + token = await humanBearer(client, userId); + }); + + after(async () => { + await stopLocal(); + delete process.env.IS_LOCAL; + }); + + beforeEach(() => { + restore?.(); + relay = new FakeRelay(); + restore = setRelayDepsForTests({ + fetchImpl: relay.fetch as typeof fetch, + readSecret: async (name) => { + if (!(name in SECRETS)) throw new Error('missing'); + return SECRETS[name]; + }, + }); + }); + + async function req(method: string, path: string, body?: unknown, query?: Record) { + const res = await handler( + { + httpMethod: method, + path, + headers: { authorization: `Bearer ${token}`, 'x-user-id': userId, host: 'ops.dtcdev.click', 'x-forwarded-proto': 'https' }, + queryStringParameters: query || null, + body: body === undefined ? null : JSON.stringify(body), + }, + {}, + ); + return { status: res.statusCode, body: res.body ? JSON.parse(res.body) : null }; + } + + async function newDoc(template: 'newsletter-main' | 'newsletter-secondary', content: Record) { + seq += 1; + const { doc } = await createSponsorDoc(client, { + cardId: `card-sync-${seq}`, + template, + title: `Doc ${seq}`, + sponsorName: 'Acme', + createdBy: 'test', + content, + }); + return doc; + } + + const { subjectLine: _s, previewText: _p, ...SECONDARY_BASE } = { + title: 'Ship faster', intro: 'Intro copy', bullets: '- one\n- two', closing: 'Bye', + ctaText: 'Try it', ctaUrl: 'https://acme.example/go', graphicsUrl: 'https://acme.example/g.png', + subjectLine: '', previewText: '', + }; + const MAIN = { + title: 'Ship faster', intro: 'Intro copy', bullets: '- one\n- two', closing: 'Bye', + ctaText: 'Try it', ctaUrl: 'https://acme.example/go', graphicsUrl: 'https://acme.example/g.png', + subjectLine: 'Ship faster today', previewText: 'A short preview', + }; + + async function setup(withDocs = true) { + seq += 1; + const main = withDocs ? await newDoc('newsletter-main', MAIN) : null; + const second = withDocs ? await newDoc('newsletter-secondary', { ...SECONDARY_BASE, title: 'Second one' }) : null; + const issue = buildNewsletterIssue( + { + kind: 'weekly', publicationDate: `2027-02-${String(seq % 27 + 1).padStart(2, '0')}`, issueNumber: 700 + seq, status: 'planned', + slots: { + ...(main ? { primary: { sponsor: 'Acme', documentUrl: `${DOC_BASE}${main.id}` } } : {}), + ...(second ? { secondary: { sponsor: 'Beta', documentUrl: `${DOC_BASE}${second.id}` } } : {}), + }, + }, + `issue-struct-${seq}`, + ); + await createNewsletterIssue(client, issue); + const key = `weekly-${900 + seq}`; + relay.seed(key, [ + { id: 1, position: 0, type: 'intro', data: { summary: 'Hello' } }, + { id: 2, position: 1, type: 'sponsor', data: { title: 'Old title', kicker: 'SPONSORED', cta_text: 'Go', cta_url: 'https://old.example/' } }, + { id: 3, position: 2, type: 'sponsor_secondary', data: { title: 'Old second', kicker: 'SPONSORED', cta_url: 'https://old.example/2' } }, + { id: 4, position: 3, type: 'events_list', data: { events: 'Mon · Webinar | Talk | https://x.example/e' } }, + { id: 5, position: 4, type: 'recording', data: { title: 'Recording', cta_url: 'https://x.example/r' } }, + ]); + const imp = await req('POST', `/api/newsletter-issues/${issue.id}/blocks/import`, { target: 'dev', issueKey: key }); + assert.strictEqual(imp.status, 201, JSON.stringify(imp.body)); + return { id: issue.id, key, main, second, base: `/api/newsletter-issues/${issue.id}/blocks` }; + } + + const order = (relayKey: string) => relay.issues.get(relayKey)!.blocks.map((b) => b.id); + const writes = () => relay.calls.filter((c) => !c.startsWith('GET')); + + it('adds a block of a Relay type, edits, reorders and deletes it, and the Relay copy matches after sync', async () => { + const { id, key, base } = await setup(false); + const types = await req('GET', `${base}/types`); + assert.strictEqual(types.status, 200); + assert.ok(types.body.types.find((t: { type: string; addable: boolean }) => t.type === 'alexey_article')?.addable); + assert.strictEqual(types.body.types.find((t: { type: string }) => t.type === 'sponsor').addable, false); + + const added = await req('POST', base, { type: 'alexey_article', position: 4, data: { title: 'My article', cta_url: 'https://alexey.example/a' } }); + assert.strictEqual(added.status, 201, JSON.stringify(added.body)); + assert.strictEqual(added.body.block.pushState, 'new'); + assert.strictEqual(added.body.block.relayBlockId, null); + assert.strictEqual(added.body.block.data.kicker, 'READ'); + const newId = added.body.block.id as string; + assert.match(newId, /^nb-/); + + const edit = await req('PUT', `${base}/${newId}`, { version: 1, data: { title: 'My article v2', cta_url: 'https://alexey.example/a', kicker: 'READ' } }); + assert.strictEqual(edit.status, 200, JSON.stringify(edit.body)); + const up = await req('POST', `${base}/${newId}/move`, { direction: 'up' }); + assert.strictEqual(up.status, 200, JSON.stringify(up.body)); + assert.deepStrictEqual(up.body.blocks.blocks.map((b: { id: string }) => b.id), ['rb-1', 'rb-2', 'rb-3', newId, 'rb-4', 'rb-5']); + assert.strictEqual(up.body.blocks.orderChanged, true); + + const del = await req('DELETE', `${base}/rb-5`); + assert.strictEqual(del.status, 200, JSON.stringify(del.body)); + assert.deepStrictEqual(del.body.blocks.deletedPending.map((b: { id: string }) => b.id), ['rb-5']); + assert.ok(relay.issues.get(key)!.blocks.some((b) => b.id === 5), 'Relay unchanged until sync'); + + const dry = await req('POST', `${base}/sync`, { dryRun: true }); + assert.deepStrictEqual(dry.body.plan.map((s: { action: string }) => s.action).sort(), ['create', 'delete', 'in_sync', 'in_sync', 'in_sync', 'in_sync'].sort()); + assert.deepStrictEqual(writes(), [], 'dry run writes nothing'); + + const sync = await req('POST', `${base}/sync`, {}); + assert.strictEqual(sync.status, 200, JSON.stringify(sync.body)); + assert.strictEqual(sync.body.created.length, 1); + assert.deepStrictEqual(sync.body.deleted, [5]); + const mine = relay.issues.get(key)!.blocks.find((b) => b.type === 'alexey_article')!; + assert.strictEqual(mine.data.title, 'My article v2'); + assert.deepStrictEqual(order(key), [1, 2, 3, mine.id, 4]); + const local = sync.body.blocks.blocks; + assert.deepStrictEqual(local.map((b: { relayBlockId: number }) => b.relayBlockId), order(key)); + assert.ok(local.every((b: { changedSinceSync: boolean }) => !b.changedSinceSync)); + assert.strictEqual(sync.body.blocks.deletedPending.length, 0); + assert.strictEqual(sync.body.blocks.orderChanged, false); + + const origins = (await req('GET', `${base}/revisions`)).body.revisions.map((r: { origin: string }) => r.origin); + assert.deepStrictEqual(origins.slice(5), ['add', 'edit', 'move', 'delete']); + const moveRev = (await req('GET', `${base}/revisions`, undefined, { block: newId })).body.revisions.find((r: { origin: string }) => r.origin === 'move'); + assert.match(moveRev.detail, /moved from position 4 to 3/); + assert.strictEqual((await req('POST', `${base}/sync`, {})).body.plan.every((s: { action: string }) => s.action === 'in_sync'), true); + void id; + }); + + it('moves a block in DataOps and pushes the new order to Relay without touching content', async () => { + const { key, base } = await setup(false); + const moved = await req('POST', `${base}/rb-5/move`, { to: 3 }); + assert.strictEqual(moved.status, 200, JSON.stringify(moved.body)); + const sync = await req('POST', `${base}/sync`, {}); + assert.strictEqual(sync.status, 200, JSON.stringify(sync.body)); + assert.deepStrictEqual(order(key), [1, 2, 3, 5, 4]); + assert.deepStrictEqual(sync.body.pushed, []); + }); + + it('refuses every sponsor-block violation server-side, explicitly, writing nothing', async () => { + const { base, main } = await setup(); + relay.calls = []; + const expectRefusal = async (res: { status: number; body: { code: string; error: string; sponsorDocUrl?: string } }, code: string) => { + assert.strictEqual(res.status, 409, JSON.stringify(res.body)); + assert.strictEqual(res.body.code, code); + assert.ok(res.body.error.length > 30, 'explicit message'); + }; + // Content read-only: main and secondary. + const editMain = await req('PUT', `${base}/rb-2`, { version: 1, data: { title: 'Hand edit', cta_text: 'x', cta_url: 'https://x.example/' } }); + await expectRefusal(editMain, 'sponsor_block_readonly'); + assert.strictEqual(editMain.body.sponsorDocUrl, `${DOC_BASE}${main!.id}`); + assert.match(editMain.body.error, /sponsor doc/i); + await expectRefusal(await req('PUT', `${base}/rb-3`, { version: 1, data: { title: 'Hand edit', cta_url: 'https://x.example/' } }), 'sponsor_block_readonly'); + // Main is pinned: no move, no delete. + await expectRefusal(await req('POST', `${base}/rb-2/move`, { direction: 'down' }), 'sponsor_block_pinned'); + await expectRefusal(await req('POST', `${base}/rb-2/move`, { to: 4 }), 'sponsor_block_pinned'); + await expectRefusal(await req('DELETE', `${base}/rb-2`), 'sponsor_block_pinned'); + // Nothing above the main sponsor: not by move, not by add; blocks above it stay put. + await expectRefusal(await req('POST', `${base}/rb-4/move`, { to: 1 }), 'above_pinned_sponsor'); + await expectRefusal(await req('POST', `${base}/rb-4/move`, { to: 0 }), 'above_pinned_sponsor'); + await expectRefusal(await req('POST', `${base}/rb-1/move`, { direction: 'down' }), 'above_pinned_sponsor'); + await expectRefusal(await req('POST', base, { type: 'alexey_article', position: 1, data: { title: 'T', cta_url: 'https://x.example/' } }), 'above_pinned_sponsor'); + await expectRefusal(await req('POST', base, { type: 'alexey_article', position: 0, data: { title: 'T', cta_url: 'https://x.example/' } }), 'above_pinned_sponsor'); + // Secondary: no direct delete; sponsor blocks cannot be added by hand. + await expectRefusal(await req('DELETE', `${base}/rb-3`), 'sponsor_block_delete_refused'); + await expectRefusal(await req('POST', base, { type: 'sponsor', data: { title: 'T', cta_text: 'x', cta_url: 'https://x.example/' } }), 'sponsor_block_doc_only'); + await expectRefusal(await req('POST', base, { type: 'sponsor_secondary', data: { title: 'T', cta_url: 'https://x.example/' } }), 'sponsor_block_doc_only'); + assert.deepStrictEqual(writes(), [], 'nothing reached Relay'); + const set = (await req('GET', base)).body.blocks; + assert.deepStrictEqual(set.blocks.map((b: { id: string }) => b.id), ['rb-1', 'rb-2', 'rb-3', 'rb-4', 'rb-5']); + assert.ok(set.blocks.every((b: { changedSinceSync: boolean }) => !b.changedSinceSync)); + const flags = Object.fromEntries(set.blocks.map((b: Record) => [b.id, [b.readOnly, b.pinned, b.canMove, b.canDelete]])); + assert.deepStrictEqual(flags, { + 'rb-1': [false, false, false, true], 'rb-2': [true, true, false, false], 'rb-3': [true, false, true, false], + 'rb-4': [false, false, true, true], 'rb-5': [false, false, true, true], + }); + // Secondary may be reordered (below the main sponsor). + const down = await req('POST', `${base}/rb-3/move`, { direction: 'down' }); + assert.strictEqual(down.status, 200, JSON.stringify(down.body)); + assert.deepStrictEqual(down.body.blocks.blocks.map((b: { id: string }) => b.id), ['rb-1', 'rb-2', 'rb-4', 'rb-3', 'rb-5']); + }); + + it('fails a sync loudly when a block was deleted here but edited in Relay, or the order changed on both sides', async () => { + const { key, base } = await setup(false); + await req('DELETE', `${base}/rb-4`); + relay.editInRelay(key, 4, { events: 'Tue · Workshop | Edited in Relay | https://x.example/n' }); + const conflict = await req('POST', `${base}/sync`, {}); + assert.strictEqual(conflict.status, 409); + assert.strictEqual(conflict.body.code, 'blocks_sync_conflict'); + assert.match(conflict.body.error, /deleted in DataOps but edited in Relay/); + assert.ok(relay.issues.get(key)!.blocks.some((b) => b.id === 4), 'not deleted in Relay'); + assert.deepStrictEqual(writes(), []); + + const other = await setup(false); + await req('POST', `${other.base}/rb-5/move`, { to: 3 }); + const live = relay.issues.get(other.key)!; + live.blocks.find((b) => b.id === 1)!.position = 9; + live.blocks.sort((a, b) => a.position - b.position); + live.blocks.forEach((b, i) => { b.position = i; }); + const both = await req('POST', `${other.base}/sync`, {}); + assert.strictEqual(both.status, 409); + assert.match(both.body.error, /reordered in DataOps and in Relay/); + }); + + it('syncs the sponsor doc into the issue block and the Relay block, subject and preview on every doc save', async () => { + const { id, key, main, second, base } = await setup(); + relay.calls = []; + const save = await req('PUT', `/api/sponsor-docs/${main!.id}`, { content: { ...MAIN, title: 'Ship even faster' } }); + assert.strictEqual(save.status, 200, JSON.stringify(save.body)); + assert.strictEqual(save.body.doc.newsletterSync.status, 'ok', JSON.stringify(save.body.doc.newsletterSync)); + const relayBlock = relay.issues.get(key)!.blocks.find((b) => b.id === 2)!; + assert.deepStrictEqual(relayBlock.data, { + kicker: 'SPONSORED', title: 'Ship even faster', image_url: 'https://acme.example/g.png', image_link: 'https://acme.example/go', + body: 'Intro copy', bullets: 'one\ntwo', closing: 'Bye', cta_text: 'Try it', cta_url: 'https://acme.example/go', + }); + assert.strictEqual(relay.issues.get(key)!.subject, 'Ship faster today | DataTalks.Club Weekly'); + assert.strictEqual(relay.previews.get(key), 'A short preview'); + const set = (await req('GET', base)).body.blocks; + assert.strictEqual(set.blocks[1].data.title, 'Ship even faster'); + assert.strictEqual(set.blocks[1].changedSinceSync, false); + assert.strictEqual(set.sponsorSync.primary.ok, true); + const revs = (await req('GET', `${base}/revisions`, undefined, { block: 'rb-2' })).body.revisions; + assert.strictEqual(revs[revs.length - 1].origin, 'sponsor-doc'); + assert.deepStrictEqual(revs[revs.length - 1].changes.map((c: { field: string }) => c.field).includes('title'), true); + // Other blocks and the secondary were not touched by the primary doc's save. + assert.strictEqual(relay.issues.get(key)!.blocks.find((b) => b.id === 3)!.data.title, 'Old second'); + + const again = await req('PUT', `/api/sponsor-docs/${main!.id}`, { content: { ...MAIN, title: 'Ship even faster' } }); + assert.strictEqual(again.body.doc.newsletterSync.status, 'ok'); + assert.strictEqual(relay.issueEdits.length, 1, 'unchanged subject is not rewritten'); + + const sec = await req('PUT', `/api/sponsor-docs/${second!.id}`, { content: { ...SECONDARY_BASE, title: 'Second one' } }); + assert.strictEqual(sec.body.doc.newsletterSync.status, 'ok', JSON.stringify(sec.body.doc.newsletterSync)); + assert.strictEqual(relay.issues.get(key)!.blocks.find((b) => b.id === 3)!.data.title, 'Second one'); + assert.strictEqual(relay.issues.get(key)!.subject, 'Ship faster today | DataTalks.Club Weekly', 'only the primary doc owns the subject'); + void id; + }); + + it('fails the doc sync loudly (never overwrites Relay), alerts, and can be forced explicitly', async () => { + const { id, key, main, base } = await setup(); + relay.editInRelay(key, 2, { kicker: 'SPONSORED', title: 'Orin hand edit', cta_text: 'Go', cta_url: 'https://old.example/' }); + const save = await req('PUT', `/api/sponsor-docs/${main!.id}`, { content: MAIN }); + assert.strictEqual(save.status, 200, 'the doc save itself succeeds'); + assert.strictEqual(save.body.doc.newsletterSync.status, 'failed'); + assert.match(save.body.doc.newsletterSync.message, /Sync refused|conflict|differs/i); + assert.strictEqual(relay.issues.get(key)!.blocks.find((b) => b.id === 2)!.data.title, 'Orin hand edit'); + const sets = (await req('GET', base)).body.blocks; + assert.strictEqual(sets.sponsorSync.primary.ok, false); + const reload = await req('GET', `/api/sponsor-docs/${main!.id}`); + assert.strictEqual(reload.body.doc.newsletterSync.status, 'failed', 'the failure stays visible after reload'); + const alerts = (await client.send(new ScanCommand({ TableName: TABLE_NOTIFICATIONS }))).Items! + .filter((item) => item.type === 'newsletter-sponsor-sync-failed'); + assert.ok(alerts.length >= 1); + assert.match(String(alerts[0].message), /did not sync/); + + const forced = await req('POST', `${base}/sponsor-sync`, { slot: 'primary', force: true }); + assert.strictEqual(forced.status, 200, JSON.stringify(forced.body)); + assert.strictEqual(relay.issues.get(key)!.blocks.find((b) => b.id === 2)!.data.title, 'Ship faster'); + void id; + }); + + it('skips with a visible reason when the issue has no blocks or the doc is incomplete, and a Relay outage is a loud failure', async () => { + const bare = await setup(true); + // Unimported issue: a new issue linked to a new doc. + seq += 1; + const doc = await newDoc('newsletter-main', MAIN); + const issue = buildNewsletterIssue( + { kind: 'weekly', publicationDate: '2027-03-01', issueNumber: 800 + seq, status: 'planned', slots: { primary: { sponsor: 'Acme', documentUrl: `${DOC_BASE}${doc.id}` } } }, + `issue-bare-${seq}`, + ); + await createNewsletterIssue(client, issue); + const saved = await req('PUT', `/api/sponsor-docs/${doc.id}`, { content: MAIN }); + assert.strictEqual(saved.body.doc.newsletterSync.status, 'skipped'); + assert.match(saved.body.doc.newsletterSync.message, /no content blocks in DataOps yet/); + + const incomplete = await req('PUT', `/api/sponsor-docs/${bare.main!.id}`, { content: { ...MAIN, title: '', ctaText: '' } }); + assert.strictEqual(incomplete.body.doc.newsletterSync.status, 'skipped'); + assert.match(incomplete.body.doc.newsletterSync.message, /missing: title, cta_text/); + assert.strictEqual(relay.issues.get(bare.key)!.blocks.find((b) => b.id === 2)!.data.title, 'Old title'); + + restore(); + restore = setRelayDepsForTests({ + fetchImpl: (async () => { throw Object.assign(new Error('aborted'), { name: 'TimeoutError' }); }) as typeof fetch, + readSecret: async (name) => SECRETS[name], + }); + const down = await req('PUT', `/api/sponsor-docs/${bare.main!.id}`, { content: { ...MAIN, title: 'Outage test' } }); + assert.strictEqual(down.status, 200); + assert.strictEqual(down.body.doc.newsletterSync.status, 'failed'); + assert.match(down.body.doc.newsletterSync.message, /timed out after 15s/); + }); + + it('removes the secondary sponsor block (here and in Relay) when its slot leaves the issue; the main block stays', async () => { + const { id, key, base } = await setup(); + const before = (await getNewsletterIssue(client, id))!; + const after = { ...before, slots: { primary: before.slots.primary, secondary: { ...before.slots.secondary, documentUrl: undefined } } }; + const released = await releaseRemovedSponsorBlocks(client, before, after, { id: userId, name: 'Alexey' }); + assert.strictEqual(released?.status, 'ok', JSON.stringify(released)); + assert.ok(!relay.issues.get(key)!.blocks.some((b) => b.id === 3), 'removed from Relay'); + const set = (await req('GET', base)).body.blocks; + assert.deepStrictEqual(set.blocks.map((b: { id: string }) => b.id), ['rb-1', 'rb-2', 'rb-4', 'rb-5']); + const none = await releaseRemovedSponsorBlocks(client, before, { ...before, slots: { ...before.slots, primary: undefined } }, { id: userId, name: 'Alexey' }); + assert.strictEqual(none, null, 'the pinned main block is not removed with its slot'); + }); +}); diff --git a/backend/tests/newsletter-blocks.test.ts b/backend/tests/newsletter-blocks.test.ts index 23364d02..73aebf1b 100644 --- a/backend/tests/newsletter-blocks.test.ts +++ b/backend/tests/newsletter-blocks.test.ts @@ -10,67 +10,7 @@ import { setRelayDepsForTests } from '../src/newsletter/blocksRelay'; import { blockHash, planSync, validateBlockData, type IssueBlock, type RelayIssue } from '../src/newsletter/blocks'; import { humanBearer } from './helpers/human-bearer'; -type FakeBlock = { id: number; position: number; type: string; data: Record; updated_by: string; updated_at: string }; - -/** An in-memory Relay newsletter API: GET issue, GET/PUT block. */ -class FakeRelay { - issues = new Map(); - calls: string[] = []; - tick = 0; - /** Runs right before a block GET returns (to simulate a concurrent Relay edit). */ - beforeBlockGet: ((block: FakeBlock) => void) | null = null; - apiKeySeen = ''; - - stamp() { - this.tick += 1; - return `2026-11-23T10:00:${String(this.tick).padStart(2, '0')}+00:00`; - } - - seed(key: string, blocks: Omit[]) { - this.issues.set(key, { - key, - subject: `Subject ${key}`, - campaign: null, - blocks: blocks.map((block) => ({ ...block, updated_by: 'api:dtc-newsletter', updated_at: this.stamp() })), - }); - } - - editInRelay(key: string, id: number, data: Record) { - const block = this.issues.get(key)!.blocks.find((item) => item.id === id)!; - block.data = data; - block.updated_by = 'alexey@datatalks.club'; - block.updated_at = this.stamp(); - } - - fetch = async (url: string | URL | Request, init?: RequestInit): Promise => { - const method = init?.method || 'GET'; - const u = new URL(String(url)); - this.calls.push(`${method} ${u.host}${u.pathname}`); - this.apiKeySeen = String((init?.headers as Record)?.authorization || ''); - const match = u.pathname.match(/^\/api\/newsletter-issues\/([^/]+)(?:\/blocks\/(\d+))?$/); - const issue = match && this.issues.get(decodeURIComponent(match[1])); - if (!issue) return new Response(JSON.stringify({ errors: { key: 'not_found' } }), { status: 404 }); - const payload = () => ({ ...issue, preview_text: '', updated_at: this.stamp() }); - if (!match![2]) return new Response(JSON.stringify({ issue: payload() }), { status: 200 }); - const block = issue.blocks.find((item) => item.id === Number(match![2])); - if (!block) return new Response(JSON.stringify({ errors: { block_id: 'not_found' } }), { status: 404 }); - if (method === 'GET') { - this.beforeBlockGet?.(block); - return new Response(JSON.stringify({ block }), { status: 200 }); - } - const body = JSON.parse(String(init?.body || '{}')); - block.type = body.type; - block.data = body.data; - block.updated_by = 'api:dtc-newsletter'; - block.updated_at = this.stamp(); - return new Response(JSON.stringify({ block }), { status: 200 }); - }; -} - -const SECRETS: Record = { - 'relay-production.dtc-newsletter-api-key': 'prod-key-123', - 'relay-dev.api-keys': JSON.stringify({ RELAY_API_KEY: 'dev-key-456', RELAY_WEBHOOK: 'x' }), -}; +import { FakeRelay, SECRETS } from './helpers/fake-relay'; describe('Newsletter issue blocks (/api/newsletter-issues/:id/blocks)', () => { let client: DynamoDBDocumentClient; @@ -187,9 +127,9 @@ describe('Newsletter issue blocks (/api/newsletter-issues/:id/blocks)', () => { assert.strictEqual(block.version, 2); assert.strictEqual(block.changedSinceSync, true); assert.strictEqual((await req('PUT', path, { version: 1, data: { summary: 'x' } })).body.code, 'block_version_conflict'); - const bad = await req('PUT', `/api/newsletter-issues/${id}/blocks/rb-114`, { version: 1, data: { title: 'T', cta_text: 'Go', cta_url: 'not a url', bogus: 'x' } }); + const bad = await req('PUT', `/api/newsletter-issues/${id}/blocks/rb-115`, { version: 1, data: { events: 'a | b | not a url', bogus: 'x' } }); assert.strictEqual(bad.status, 400); - assert.deepStrictEqual(bad.body.fields, { 'data.bogus': 'unknown_field', 'data.cta_url': 'invalid_url' }); + assert.deepStrictEqual(bad.body.fields, { 'data.bogus': 'unknown_field', 'data.events.0': 'invalid_url' }); const revisions = (await req('GET', `/api/newsletter-issues/${id}/blocks/revisions`, undefined, { block: '113' })).body.revisions; assert.deepStrictEqual(revisions.map((r: { origin: string }) => r.origin), ['import', 'edit']); @@ -245,19 +185,19 @@ describe('Newsletter issue blocks (/api/newsletter-issues/:id/blocks)', () => { it('does not overwrite a Relay edit made between planning and pushing', async () => { const { id } = await imported(); - await req('PUT', `/api/newsletter-issues/${id}/blocks/rb-114`, { version: 1, data: { title: 'New', cta_text: 'Go', cta_url: 'https://x.example/a' } }); + await req('PUT', `/api/newsletter-issues/${id}/blocks/rb-115`, { version: 1, data: { events: 'Thu · Talk | New | https://x.example/a' } }); relay.beforeBlockGet = (block) => { - block.data = { ...block.data, title: 'Concurrent Relay edit' }; + block.data = { ...block.data, events: 'Concurrent Relay edit' }; block.updated_at = relay.stamp(); relay.beforeBlockGet = null; }; const res = await req('POST', `/api/newsletter-issues/${id}/blocks/sync`, {}); assert.strictEqual(res.status, 409); assert.match(res.body.error, /changed during the sync/); - assert.strictEqual(relay.issues.get('weekly-304')!.blocks[1].data.title, 'Concurrent Relay edit'); + assert.strictEqual(relay.issues.get('weekly-304')!.blocks[2].data.events, 'Concurrent Relay edit'); const next = await req('POST', `/api/newsletter-issues/${id}/blocks/sync`, { dryRun: true }); assert.strictEqual(next.status, 409); - assert.strictEqual(next.body.conflicts[0].relayBlockId, 114); + assert.strictEqual(next.body.conflicts[0].relayBlockId, 115); }); it('refuses to push into a Relay issue whose campaign left draft, and surfaces Relay failures', async () => { From 1e9a0db09b36e318f42ef407480fc22e8b37ffcf Mon Sep 17 00:00:00 2001 From: Alexey Grigorev Date: Mon, 23 Nov 2026 13:38:16 +0100 Subject: [PATCH 10/12] Blocks types: optional check against Relay's live block catalogue --- backend/src/routes/newsletterBlocks.ts | 14 ++++++++++++-- backend/tests/helpers/fake-relay.ts | 2 ++ backend/tests/newsletter-blocks-structure.test.ts | 4 ++++ 3 files changed, 18 insertions(+), 2 deletions(-) diff --git a/backend/src/routes/newsletterBlocks.ts b/backend/src/routes/newsletterBlocks.ts index 55e01e5c..23718fc6 100644 --- a/backend/src/routes/newsletterBlocks.ts +++ b/backend/src/routes/newsletterBlocks.ts @@ -32,7 +32,7 @@ import { type RelayTarget, } from '../newsletter/blocks'; import { BlockSetVersionConflict, getBlockSet, listBlockRevisions } from '../newsletter/blocksStore'; -import { RelayError } from '../newsletter/blocksRelay'; +import { RelayError, relayClient } from '../newsletter/blocksRelay'; import { BlocksError, editBlock, importBlocks, requireBlockSet, syncBlocks, type BlockActor } from '../newsletter/blocksSync'; import { addBlock, deleteBlock, moveBlock } from '../newsletter/blocksOps'; import { byPosition, pinnedIndex, sponsorSlotOf, type SponsorDocUrls } from '../newsletter/blocksLayout'; @@ -148,7 +148,17 @@ export async function handleNewsletterBlockRoutes( } if (rest === '/types') { if (method !== 'GET') return json(405, { error: 'Method not allowed' }); - return json(200, { issueId: issue.id, types: blockTypesView() }); + const types = blockTypesView(); + if (event.queryStringParameters?.check !== 'relay') return json(200, { issueId: issue.id, types }); + // Prove DataOps' mirror of Relay's block catalogue still matches the live one. + const set = await requireBlockSet(client, issue.id); + const live = await (await relayClient(set.relay.target)).blockTypeKeys(); + const here = types.map((item) => item.type); + return json(200, { + issueId: issue.id, + types, + relayCheck: { target: set.relay.target, missingInRelay: here.filter((t) => !live.includes(t)), missingInDataOps: live.filter((t) => !here.includes(t)) }, + }); } if (rest === '/import') { if (method !== 'POST') return json(405, { error: 'Method not allowed' }); diff --git a/backend/tests/helpers/fake-relay.ts b/backend/tests/helpers/fake-relay.ts index f98f1e9c..34f1942a 100644 --- a/backend/tests/helpers/fake-relay.ts +++ b/backend/tests/helpers/fake-relay.ts @@ -31,6 +31,7 @@ export class FakeRelay { } nextId = 200; + typeKeys = ['intro', 'sponsor', 'sponsor_secondary', 'alexey_article', 'events_list', 'recording']; issueEdits: { subject?: string; preview_text?: string }[] = []; private renumber(issue: { blocks: FakeBlock[] }) { @@ -44,6 +45,7 @@ export class FakeRelay { this.calls.push(`${method} ${u.host}${u.pathname}`); this.apiKeySeen = String((init?.headers as Record)?.authorization || ''); const reply = (status: number, body: unknown) => new Response(JSON.stringify(body), { status }); + if (u.pathname === '/api/newsletter-block-types') return reply(200, { block_types: this.typeKeys.map((type) => ({ type })) }); const match = u.pathname.match(/^\/api\/newsletter-issues\/([^/]+)(\/blocks)?(?:\/(\d+))?$/); const issue = match && this.issues.get(decodeURIComponent(match[1])); if (!issue) return reply(404, { errors: { key: 'not_found' } }); diff --git a/backend/tests/newsletter-blocks-structure.test.ts b/backend/tests/newsletter-blocks-structure.test.ts index abf5db45..ce5b3e03 100644 --- a/backend/tests/newsletter-blocks-structure.test.ts +++ b/backend/tests/newsletter-blocks-structure.test.ts @@ -129,6 +129,10 @@ describe('Newsletter issue blocks: add, move, delete, sponsor rules, sponsor-doc assert.ok(types.body.types.find((t: { type: string; addable: boolean }) => t.type === 'alexey_article')?.addable); assert.strictEqual(types.body.types.find((t: { type: string }) => t.type === 'sponsor').addable, false); + const check = await req('GET', `${base}/types`, undefined, { check: 'relay' }); + assert.deepStrictEqual(check.body.relayCheck.missingInRelay.includes('sponsor'), false); + assert.ok(check.body.relayCheck.missingInDataOps.length === 0); + const added = await req('POST', base, { type: 'alexey_article', position: 4, data: { title: 'My article', cta_url: 'https://alexey.example/a' } }); assert.strictEqual(added.status, 201, JSON.stringify(added.body)); assert.strictEqual(added.body.block.pushState, 'new'); From 8f3bdb5e20810bf1d28ce4fc33c3e97ed3a4d1e1 Mon Sep 17 00:00:00 2001 From: Alexey Grigorev Date: Mon, 23 Nov 2026 13:42:49 +0100 Subject: [PATCH 11/12] Allow anonymous page module graph to load the newsletter blocks and sponsor-sync modules --- backend/src/newsletter/markdownPreview.ts | 1 + backend/src/routes/sponsorDocs.ts | 1 + 2 files changed, 2 insertions(+) diff --git a/backend/src/newsletter/markdownPreview.ts b/backend/src/newsletter/markdownPreview.ts index 47935081..5c8bc18b 100644 --- a/backend/src/newsletter/markdownPreview.ts +++ b/backend/src/newsletter/markdownPreview.ts @@ -93,6 +93,7 @@ export function isAnonymousNewsletterPreviewAsset(method: string, path: string): || path === '/src/core/guarded-fetch.js' || path === '/src/core/dates.js' || path === '/src/surfaces/operations/newsletter-preview.js' + || /^\/src\/surfaces\/operations\/newsletter-blocks(?:-[a-z]+)?\.js$/.test(path) || path === '/src/styles/newsletter-preview.css' || path === '/src/styles/sponsor-docs.css' || path.startsWith('/src/dakit/') diff --git a/backend/src/routes/sponsorDocs.ts b/backend/src/routes/sponsorDocs.ts index d9420ff2..b5ffe31f 100644 --- a/backend/src/routes/sponsorDocs.ts +++ b/backend/src/routes/sponsorDocs.ts @@ -323,6 +323,7 @@ export function isAnonymousSponsorDocAsset(method: string, path: string): boolea || path === '/src/surfaces/operations/sponsor-doc-select.js' || path === '/src/surfaces/operations/sponsor-doc-radio.js' || path === '/src/surfaces/operations/sponsor-doc-bullets.js' + || path === '/src/surfaces/operations/sponsor-doc-newsletter-sync.js' || path === '/src/surfaces/operations/sponsor-doc-visual.js' || path === '/src/surfaces/operations/sponsor-doc-email-card.js' || path === '/src/surfaces/operations/sponsor-doc-event-time.js' From ce4510830d421a69759fff6c7a3d147525f9429e Mon Sep 17 00:00:00 2001 From: Alexey Grigorev Date: Mon, 23 Nov 2026 13:57:33 +0100 Subject: [PATCH 12/12] e2e: newsletter preview now has a Blocks tab --- backend/e2e/newsletter-preview-overflow.spec.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/e2e/newsletter-preview-overflow.spec.js b/backend/e2e/newsletter-preview-overflow.spec.js index 1a996b76..111afc70 100644 --- a/backend/e2e/newsletter-preview-overflow.spec.js +++ b/backend/e2e/newsletter-preview-overflow.spec.js @@ -91,7 +91,7 @@ test('newsletter preview wraps long URLs and inline code on every tab; shareable await page.setExtraHTTPHeaders({}); await page.goto(`${server.baseURL}/newsletter-issues/${issue.id}/preview`); await expect(page.locator('[data-preview-staff-bar]')).toBeVisible(); - await expect(page.locator('[data-preview-tab]')).toHaveCount(5); + await expect(page.locator('[data-preview-tab]')).toHaveCount(6); for (const tab of ['issue', 'final', 'brief', 'sources', 'raw']) { await page.locator(`[data-preview-tab="${tab}"]`).click(); if (tab === 'raw') {