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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
97 changes: 97 additions & 0 deletions backend/e2e/sponsor-doc-utm-save.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
// Regression (t2909u): clicking the "Add UTM" suggestion on a sponsor doc changed
// ctaUrl in the page only; nothing reached the server until a manual Save, so
// the value was lost. The page now autosaves every edit, including
// helper-filled values and image uploads, and a failed save is loud.
const { test, expect } = require("@playwright/test");
const { createDocsCacheRoot } = require("./helpers/docs-content-root");
const { startOwnedTestServer, stopOwnedTestServer } = require("./helpers/isolated-capability-server");

// 1x1 PNG
const VALID_PNG = Buffer.from(
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+X2ZkAAAAASUVORK5CYII=",
"base64",
);

let server;
test.use({ screenshot: "off", trace: "off", video: "off" });

test.beforeAll(async () => {
server = await startOwnedTestServer({ environment: { DTC_CACHE_ROOT: createDocsCacheRoot("sponsor-doc-autosave") } });
});
test.afterAll(async () => { await stopOwnedTestServer(server); });

async function openSponsorDoc(page, request, title) {
const tplRes = await request.post(`${server.baseURL}/__e2e__/template-fixtures`, {
data: { name: `Autosave ${title}`, type: "newsletter", sourcePath: `workflow-templates/autosave-${title}.yaml`, taskDefinitions: [] },
});
expect(tplRes.status()).toBe(201);
const { template } = await tplRes.json();
const cardRes = await request.post(`${server.baseURL}/api/cards`, {
data: { templateId: template.id, title: `Autosave ${title}`, anchorDate: "2026-12-14" },
});
expect(cardRes.status()).toBe(201);
const { card } = await cardRes.json();
const docRes = await request.post(`${server.baseURL}/api/sponsor-docs`, {
data: { cardId: card.id, template: "newsletter-main", sponsorName: "Acme Corp", autoSendEmail: false },
});
expect(docRes.status()).toBe(201);
const { doc } = await docRes.json();
// Save a plain ctaUrl first, exactly like the reported doc.
const putRes = await request.put(`${server.baseURL}/api/sponsor-docs/${doc.id}`, {
data: { content: { ...(doc.content || {}), ctaUrl: "https://maven.com/example/product-shipping" } },
});
expect(putRes.status()).toBe(200);
await page.setExtraHTTPHeaders({ "x-sponsor-doc-anonymous": "true" });
await page.goto(`${server.baseURL}/sponsor-docs/${doc.id}?code=${encodeURIComponent(doc.accessCode)}`);
await expect(page.locator('[data-sponsor-view="editor"]')).toBeVisible();
return doc;
}

const status = (page) => page.locator("[data-sponsor-save-status]");

test("clicking the UTM suggestion autosaves ctaUrl; reload shows it", async ({ page, request }) => {
test.setTimeout(60_000);
await openSponsorDoc(page, request, "utm");
await expect(status(page)).toHaveAttribute("data-sponsor-save-state", "saved");
const putDone = page.waitForResponse((res) => res.request().method() === "PUT" && /\/api\/sponsor-docs\//.test(res.url()));
await page.locator('[data-sponsor-action="apply-utm-suggestion"][data-sponsor-utm-field="ctaUrl"]').click();
expect((await putDone).status()).toBe(200);
await expect(status(page)).toHaveAttribute("data-sponsor-save-state", "saved");
await expect(status(page)).toContainText("All changes saved");
await page.reload();
await expect(page.locator("#sponsor-field-ctaUrl")).toHaveValue(/^https:\/\/maven\.com\/example\/product-shipping\?.*utm_source=/);
});

test("typing and an image upload autosave without a Save click", async ({ page, request }) => {
test.setTimeout(60_000);
await openSponsorDoc(page, request, "typing");
await page.locator("#sponsor-field-title").fill("Autosaved headline");
await expect(status(page)).toHaveAttribute("data-sponsor-save-state", "saved", { timeout: 10_000 });
await page.locator('[data-sponsor-visual-upload="graphicsUrl"]').setInputFiles({ name: "banner.png", mimeType: "image/png", buffer: VALID_PNG });
await expect(page.locator('img[data-sponsor-visual-image="graphicsUrl"]')).toBeVisible();
await expect(status(page)).toHaveAttribute("data-sponsor-save-state", "saved", { timeout: 10_000 });
await page.reload();
await expect(page.locator("#sponsor-field-title")).toHaveValue("Autosaved headline");
await expect(page.locator("#sponsor-field-graphicsUrl")).toHaveValue(/\/api\/public-images\/[0-9a-f-]+\.png$/);
});

test("a failed autosave shows a loud NOT SAVED error, reports it, and Retry saves", async ({ page, request }) => {
test.setTimeout(60_000);
await openSponsorDoc(page, request, "failure");
const reports = [];
page.on("request", (req) => { if (req.url().endsWith("/api/client-errors")) reports.push(req.postDataJSON()); });
const failPut = (route) => (route.request().method() === "PUT"
? route.fulfill({ status: 500, json: { error: "boom" } })
: route.continue());
await page.route("**/api/sponsor-docs/*", failPut);
await page.locator("#sponsor-field-title").fill("Will fail first");
await expect(status(page)).toHaveAttribute("data-sponsor-save-state", "error", { timeout: 10_000 });
await expect(status(page)).toHaveAttribute("role", "alert");
await expect(status(page)).toContainText("NOT SAVED");
await expect.poll(() => reports.length).toBeGreaterThan(0);
await page.unroute("**/api/sponsor-docs/*", failPut);
await page.locator('[data-sponsor-action="retry-save"]').click();
await expect(status(page)).toHaveAttribute("data-sponsor-save-state", "saved", { timeout: 10_000 });
await page.reload();
await expect(page.locator("#sponsor-field-title")).toHaveValue("Will fail first");
});
2 changes: 2 additions & 0 deletions backend/src/docs/frontend-assets.json
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,9 @@
"src/surfaces/operations/contract-sign.js",
"src/surfaces/operations/index.js",
"src/surfaces/operations/newsletter-preview.js",
"src/surfaces/operations/sponsor-doc-autosave.js",
"src/surfaces/operations/sponsor-doc-bullets.js",
"src/surfaces/operations/sponsor-doc-files.js",
"src/surfaces/operations/sponsor-doc-visual.js",
"src/surfaces/operations/sponsor-doc-email-card.js",
"src/surfaces/operations/sponsor-doc-event-time.js",
Expand Down
2 changes: 2 additions & 0 deletions backend/src/routes/sponsorDocs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -347,6 +347,8 @@ export function isAnonymousSponsorDocAsset(method: string, path: string): boolea
|| path === '/src/surfaces/operations/sponsor-doc-radio.js'
|| path === '/src/surfaces/operations/sponsor-doc-bullets.js'
|| path === '/src/surfaces/operations/sponsor-doc-visual.js'
|| path === '/src/surfaces/operations/sponsor-doc-autosave.js'
|| path === '/src/surfaces/operations/sponsor-doc-files.js'
|| path === '/src/surfaces/operations/sponsor-doc-email-card.js'
|| path === '/src/surfaces/operations/sponsor-doc-event-time.js'
|| path === '/src/surfaces/operations/sponsor-doc-guest-schedule.js'
Expand Down
2 changes: 2 additions & 0 deletions backend/tests/sponsor-docs.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1068,6 +1068,8 @@ describe('Sponsor Content Docs API (/api/sponsor-docs)', () => {

it('keeps podcast run sheet, episode brief, research, and hostContext isolated from guests while serving them to staff', async () => {
assert.equal(isAnonymousSponsorDocAsset('GET', '/src/surfaces/operations/sponsor-doc-podcast.js'), true);
assert.equal(isAnonymousSponsorDocAsset('GET', '/src/surfaces/operations/sponsor-doc-autosave.js'), true);
assert.equal(isAnonymousSponsorDocAsset('GET', '/src/surfaces/operations/sponsor-doc-files.js'), true);

const card = await createCard(client, {
...templateLink(),
Expand Down
218 changes: 218 additions & 0 deletions frontend/src/surfaces/operations/sponsor-doc-autosave.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,218 @@
import { reportClientFailure } from "../../core/guarded-fetch.js";

/** Debounce between the last edit and the automatic save. */
export const SPONSOR_DOC_AUTOSAVE_DELAY_MS = 1200;

// The guest time choice is confirmed with its own "Save time choice" button
// (it records a booking intent), so autosave keeps its saved value.
const EXPLICIT_SAVE_KEYS = ["slotChoice"];

export function notSavedMessage(err) {
return `NOT SAVED: ${err?.message || "Failed to save changes."} Your edits are still in this form.`;
}

/**
* 5xx, timeouts and network errors are already reported by the request layer;
* report the rest (4xx) too so no failed save goes unnoticed.
*/
export function reportSaveFailure(err) {
if (typeof err?.status === "number" && err.status < 500) {
reportClientFailure({ surface: "sponsor-doc", check: "PUT /api/sponsor-docs", status: err.status, message: String(err.message || "") });
}
}

/**
* Autosave for the sponsor doc page: every edit (typing, helper buttons,
* uploads, selects) is saved after a short debounce, without re-rendering the
* form, and the visible status line shows saving / saved / NOT SAVED.
* `baseline` is the content last persisted.
*/
export function createSponsorDocAutosave({
el,
actionBtn,
root,
request,
announce,
ctx,
delayMs = SPONSOR_DOC_AUTOSAVE_DELAY_MS,
}) {
let baseline = null;
let timer = null;
let inFlight = null;
let state = "saved";
let error = "";

function savedContent() {
const content = ctx.savableContent();
for (const key of EXPLICIT_SAVE_KEYS) {
if (!baseline || !(key in baseline)) delete content[key];
else content[key] = baseline[key];
}
return content;
}

function markClean(content = ctx.savableContent()) {
baseline = { ...content };
}

function forgetBaseline() {
baseline = null;
}

function isDirty() {
if (!ctx.doc() || !baseline) return false;
const draft = savedContent();
const keys = new Set([...Object.keys(baseline), ...Object.keys(draft)]);
for (const key of keys) {
if (String(baseline[key] ?? "") !== String(draft[key] ?? "")) return true;
}
return false;
}

function setSaved() {
state = "saved";
error = "";
}

function setError(message) {
state = "error";
error = message;
}

function fillStatus(node) {
const tone = { saved: "success", pending: "warning", saving: "info", error: "danger" }[state] || "info";
node.className = `dk-callout dk-callout--${tone} sponsor-doc-save-status`;
node.dataset.sponsorSaveStatus = "";
node.dataset.sponsorSaveState = state;
node.setAttribute("role", state === "error" ? "alert" : "status");
const body = el("div", "dk-callout__body");
if (state === "error") {
body.append(el("span", "", `${error} `));
body.append(actionBtn("dk-button dk-button--secondary dk-button--sm", "Retry save", "retry-save", () => run()));
} else if (state === "saving") {
body.textContent = "Saving…";
} else if (state === "pending") {
body.textContent = "Unsaved changes · saving automatically…";
} else {
const label = ctx.savedLabel();
body.textContent = label ? `All changes saved · ${label}` : "Changes save automatically.";
}
node.replaceChildren(body);
}

function statusNode() {
const node = el("div");
fillStatus(node);
return node;
}

function refresh() {
for (const node of root?.querySelectorAll?.("[data-sponsor-save-status]") || []) fillStatus(node);
}

function clearTimer() {
if (timer) clearTimeout(timer);
timer = null;
}

function schedule(delay = delayMs) {
if (!ctx.editing()) return;
if (!isDirty()) {
if (state === "pending") state = "saved";
refresh();
return;
}
if (state !== "error" && state !== "saving") state = "pending";
clearTimer();
timer = setTimeout(() => {
timer = null;
run();
}, delay);
refresh();
}

async function run() {
clearTimer();
if (inFlight) {
await inFlight;
return run();
}
if (!ctx.editing()) return undefined;
if (ctx.busy()) {
// A manual save / submit is running; it sends the same content.
schedule();
return undefined;
}
if (!isDirty()) {
if (state !== "error") state = "saved";
refresh();
return undefined;
}
const content = savedContent();
const docId = ctx.docId();
state = "saving";
refresh();
inFlight = (async () => {
try {
const code = ctx.accessCode();
const payload = await request(`/api/sponsor-docs/${encodeURIComponent(docId)}`, {
method: "PUT",
headers: code ? { "x-sponsor-doc-code": code } : {},
body: JSON.stringify({ content }),
});
if (ctx.docId() !== docId || !ctx.doc()) return;
ctx.setDoc(payload.doc);
markClean(content);
setSaved();
announce("All changes saved.");
} catch (err) {
setError(notSavedMessage(err));
if (err?.fields && typeof err.fields === "object") {
ctx.setFieldErrors(err.fields);
for (const key of Object.keys(err.fields)) {
root?.querySelector?.(`[data-sponsor-field="${key}"]`)?.setAttribute?.("aria-invalid", "true");
}
}
reportSaveFailure(err);
announce(error);
} finally {
inFlight = null;
}
})();
await inFlight;
// Edits made while the request was in flight get their own save.
if (state === "saved" && isDirty()) schedule();
else refresh();
return undefined;
}

/** Before a manual save: drop the pending timer and let a running save finish. */
async function settle() {
clearTimer();
if (inFlight) await inFlight;
}

/** Save now if a save is pending (tab hidden / page unloading). */
function flush() {
if (timer) run();
}

/** Save on every edit event; warn before leaving with unsaved work; flush on tab hide. */
function attach(documentRef) {
root.addEventListener("input", () => schedule());
root.addEventListener("change", () => schedule());
globalThis.addEventListener?.("beforeunload", (event) => {
if (!ctx.editing() || !(isDirty() || inFlight || ctx.busy())) return;
flush();
event.preventDefault();
event.returnValue = "";
});
documentRef.addEventListener?.("visibilitychange", () => {
if (documentRef.visibilityState === "hidden") flush();
});
}

return {
attach, clearTimer, fillStatus, flush, forgetBaseline, markClean, run, schedule, setError, setSaved, settle, statusNode,
};
}
4 changes: 4 additions & 0 deletions frontend/src/surfaces/operations/sponsor-doc-email-card.js
Original file line number Diff line number Diff line change
Expand Up @@ -335,6 +335,7 @@ export function attachSoftUtmSuggestion({
updateCount,
updateLivePreview,
announce,
onApplied,
}) {
const shouldSuggest = Boolean(fieldDef.suggestNewsletterUtm)
|| fieldDef.key === "ctaUrl"
Expand Down Expand Up @@ -369,6 +370,9 @@ export function attachSoftUtmSuggestion({
syncUtmSuggestion();
updateLivePreview();
announce?.(`Added ${DEFAULT_NEWSLETTER_UTM_SOURCE} UTM parameters to ${fieldDef.label}.`);
// Helper-filled values are real edits: tell the page (dirty indicator, autosave).
control.dispatchEvent(new Event("input", { bubbles: true }));
onApplied?.(fieldDef.key, nextUrl);
},
);
applyBtn.dataset.sponsorUtmField = fieldDef.key;
Expand Down
29 changes: 29 additions & 0 deletions frontend/src/surfaces/operations/sponsor-doc-files.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/** Read an uploaded image file as a data: URL (browser File or test double). */
function bytesToDataUrl(bytes, mimeType = "image/png") {
let binary = "";
for (let i = 0; i < bytes.length; i += 0x8000) {
binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
}
const base64 = typeof globalThis.btoa === "function"
? globalThis.btoa(binary)
: globalThis.Buffer ? globalThis.Buffer.from(bytes).toString("base64") : "";
return `data:${mimeType || "image/png"};base64,${base64}`;
}

export async function readVisualFileAsDataUrl(file) {
if (!file) return "";
if (typeof file.dataUrl === "string" && file.dataUrl) return file.dataUrl;
if (typeof file.arrayBuffer === "function") {
const buffer = await file.arrayBuffer();
return bytesToDataUrl(new Uint8Array(buffer), file.type || "image/png");
}
if (typeof globalThis.FileReader === "function") {
return new Promise((resolve, reject) => {
const reader = new globalThis.FileReader();
reader.onload = () => resolve(String(reader.result || ""));
reader.onerror = () => reject(new Error("Could not read image file"));
reader.readAsDataURL(file);
});
}
return "";
}
Loading