Skip to content

High performance, self-hosted, newsletter and mailing list manager with a modern dashboard. Single binary app.

36.0 KB
Raw Blame
import { test, expect } from '@playwright/test';
import { confirm, openMenu, resetDB, selectList, getMail, psql } from '../helpers.js';

const CAMPAIGNS = '/admin/campaigns';
const expression = 'Hello {{ .Subscriber.Name }} from {{ .Subscriber.Attribs.city }}';
const rendered = 'Hello Demo Subscriber from Bengaluru';
const rows = (page) => page.locator('tbody tr[data-campaign-id]');
const row = (page, name) => rows(page).filter({ has: page.getByRole('link', { name, exact: true }) });
const campaignNames = (page) => rows(page).locator('td.name > .avatar > .avatar-label > div > a.unstyled');
const timestampHeading = (page) => page.locator('.cy-timestamp .timestamp-sort > a');
const tab = (page, name) => page.getByRole('tab', { name, exact: true });
const button = (scope, name) => scope.getByRole('button', { name, exact: true });

async function data(response) {
  expect(response.ok(), await response.text()).toBeTruthy();
  return (await response.json()).data;
}

async function create(page, overrides = {}) {
  return data(await page.request.post('/api/campaigns', { data: {
    name: 'Campaign', subject: 'Campaign subject', type: 'regular',
    content_type: 'html', body: `<p>${expression}</p>`, lists: [1], ...overrides,
  } }));
}

async function campaign(page, id) {
  return data(await page.request.get(`/api/campaigns/${id}`));
}

async function save(page, id, action = () => button(page, 'Save changes').click()) {
  const [response] = await Promise.all([
    page.waitForResponse((r) => r.url().endsWith(`/api/campaigns/${id}`) && r.request().method() === 'PUT'),
    action(),
  ]);
  return data(response);
}

async function menu(page, name, action) {
  const item = row(page, name).getByRole('menuitem', { name: action, exact: true });
  if (!(await item.isVisible())) await openMenu(row(page, name));
  await item.click();
}

async function switchFormat(page, format, accept = true) {
  const settings = page.locator('button[popovertarget="content-settings"]');
  await settings.click();
  await page.locator('#content-settings select[name="content_type"]').selectOption(format);
  if (accept) await confirm(page);
  else await button(page.locator('dialog[open]'), 'Cancel').click();
  await settings.click();
}

async function editorReady(page) {
  await expect(page.locator('.editor-body')).not.toHaveClass(/is-loading/);
}

async function visualDocument(page, document) {
  await editorReady(page);
  // Seed the builder through its public document API; serialization runs in the real iframe.
  await page.locator('visual-editor').evaluate((el, doc) => el.render(doc), document);
}

async function fillBody(page, format, text) {
  await editorReady(page);
  if (format === 'visual') {
    await visualDocument(page, {
      root: { type: 'EmailLayout', data: { childrenIds: ['text'] } },
      text: { type: 'Text', data: { props: { text: 'Write your message' }, style: {} } },
    });
    const frame = page.frameLocator('#visual-editor');
    await frame.getByText('Write your message', { exact: true }).click();
    await frame.getByRole('textbox', { name: 'Content', exact: true }).fill(text);
    await expect(frame.locator('td').getByText(text, { exact: true })).toBeVisible();
  } else if (format === 'richtext') {
    await page.locator('richtext-editor [contenteditable="true"]').fill(text);
  } else if (format === 'plain') {
    await page.locator('textarea[name="content"]').fill(text);
  } else {
    await page.locator('.editor-body .cm-content').fill(format === 'html' ? `<strong>${text}</strong>` : `**${text}**`);
  }
}

async function delivered(subject) {
  let mail;
  await expect.poll(async () => {
    mail = (await getMail()).find((m) => m.Content.Headers.Subject?.[0] === subject);
    return !!mail;
  }, { timeout: 20000 }).toBeTruthy();
  return mail;
}

async function preview(page, text) {
  await button(page, 'Preview').click();
  await expect(page.frameLocator('.preview-modal iframe').locator('body')).toContainText(text);
  await button(page.locator('.preview-modal'), 'Close').click();
}

test.beforeEach(async ({ browser }) => {
  await resetDB(browser);
});

test('shows the seeded campaign and previews it from the listing', async ({ page }) => {
  await page.goto(CAMPAIGNS);
  await expect(rows(page)).toHaveCount(1);
  await expect(rows(page)).toContainText('Draft');
  await expect(rows(page).locator('.lists')).toContainText('Default list');
  await openMenu(rows(page));
  await rows(page).getByRole('menuitem', { name: 'Preview', exact: true }).click();
  await expect(page.frameLocator('.preview-modal iframe').locator('body')).toContainText('Hi');
  await button(page.locator('.preview-modal'), 'Close').click();
  await expect(page.locator('.preview-modal iframe')).not.toHaveAttribute('src');
});

for (const format of ['richtext', 'html', 'markdown', 'plain', 'visual']) {
  for (const lists of [['Default list'], ['Default list', 'Opt-in list']]) {
    test(`creates, edits and previews ${format} with ${lists.length} list(s)`, async ({ page }) => {
      await page.goto(CAMPAIGNS);
      await page.getByRole('link', { name: 'New', exact: true }).click();
      await expect(tab(page, 'Content')).toHaveAttribute('aria-disabled', 'true');
      await page.getByLabel('Name', { exact: true }).fill(`New ${format}`);
      await page.getByLabel('Subject', { exact: true }).fill(`Subject ${format}`);
      await page.locator('input[name="from_email"]').fill('Sender <[email protected]>');
      await page.getByRole('combobox', { name: 'Format', exact: true }).selectOption(format);
      for (const name of lists) await selectList(page.locator('fieldset').filter({ has: page.locator('#campaign-lists') }), name);
      for (const tag of ['news', 'monthly']) {
        await page.getByPlaceholder('Tags', { exact: true }).fill(tag);
        await page.getByPlaceholder('Tags', { exact: true }).press('Enter');
      }
      await page.getByRole('switch', { name: 'Custom headers', exact: true }).check();
      await page.locator('textarea[name="headers"]').fill('[{"X-Custom":"value"}]');
      await button(page, 'Continue').click();
      await expect(page).toHaveURL(/\/campaigns\/\d+#tab=content$/);
      const id = Number(new URL(page.url()).pathname.split('/').pop());
      await expect(tab(page, 'Content')).toHaveAttribute('aria-selected', 'true');
      await fillBody(page, format, expression);
      await save(page, id);
      await page.reload();
      await editorReady(page);
      const saved = await campaign(page, id);
      expect(saved).toMatchObject({ name: `New ${format}`, subject: `Subject ${format}`, status: 'draft',
        content_type: format, from_email: 'Sender <[email protected]>',
        headers: [{ 'X-Custom': 'value' }], send_at: null, altbody: null });
      expect(saved.tags.sort()).toEqual(['monthly', 'news']);
      expect(saved.lists.map((l) => l.id).sort()).toEqual(lists.length === 1 ? [1] : [1, 2]);
      expect(saved.body).toContain(expression);
      if (format === 'visual') expect(JSON.parse(saved.body_source).text.data.props.text).toBe(expression);
      await preview(page, rendered);
      await page.goto(CAMPAIGNS);
      await expect(row(page, `New ${format}`)).toContainText(`Subject ${format}`);
      await expect(row(page, `New ${format}`).locator('.lists a.avatar-label')).toHaveCount(lists.length);
    });
  }
}

test('edits metadata, schedules in local time, unschedules and clears the schedule', async ({ page }) => {
  const c = await create(page, { lists: [2], tags: ['old'] });
  await page.goto(`${CAMPAIGNS}/${c.id}`);
  await page.getByLabel('Name', { exact: true }).fill('Scheduled newsletter');
  await page.getByLabel('Subject', { exact: true }).fill('Updated subject');
  await page.locator('input[name="from_email"]').fill('New <[email protected]>');
  const listField = page.locator('fieldset').filter({ has: page.locator('#campaign-lists') });
  await listField.locator('.badge').hover();
  await button(listField, 'Remove Opt-in list').click();
  await selectList(listField, 'Default list');
  const tags = page.getByPlaceholder('Tags', { exact: true });
  await tags.press('Backspace');
  await tags.fill('new-tag');
  await tags.press('Enter');
  await page.getByRole('switch', { name: 'Custom headers', exact: true }).check();
  await page.locator('textarea[name="headers"]').fill('[{"X-Custom":"Custom-Value"}]');
  await page.getByRole('switch', { name: 'Send later', exact: true }).check();
  const when = `${new Date().getFullYear() + 1}-06-15T09:30`;
  await page.locator('input[name="send_at"]').fill(when);
  const iso = await page.evaluate((value) => new Date(value).toISOString(), when);
  await expect(button(page, 'Start campaign')).toHaveCount(0);
  await tab(page, 'Content').click();
  await switchFormat(page, 'plain');
  await fillBody(page, 'plain', 'Scheduled body');
  await tab(page, 'Campaign').click();
  await button(page, 'Schedule campaign').click();
  await confirm(page);
  await expect(page).toHaveURL(/\/admin\/campaigns$/);
  await expect(row(page, 'Scheduled newsletter')).toContainText('Scheduled');
  const saved = await campaign(page, c.id);
  expect(saved).toMatchObject({ status: 'scheduled', name: 'Scheduled newsletter', subject: 'Updated subject',
    from_email: 'New <[email protected]>', content_type: 'plain', body: 'Scheduled body', altbody: null,
    tags: ['new-tag'], headers: [{ 'X-Custom': 'Custom-Value' }] });
  expect(new Date(saved.send_at).toISOString()).toBe(iso);
  expect(saved.lists.map((l) => l.id)).toEqual([1]);
  await page.goto(`${CAMPAIGNS}/${c.id}`);
  await expect(page.locator('input[name="send_at"]')).toHaveValue(when);
  await button(page, 'Unschedule').click();
  await confirm(page);
  await expect(page.locator('header .status-draft')).toBeVisible();
  await page.getByRole('switch', { name: 'Send later', exact: true }).uncheck();
  await save(page, c.id);
  expect((await campaign(page, c.id)).send_at).toBeNull();
  await expect(button(page, 'Start campaign')).toBeVisible();
});

test('converts formats and cancels conversion without losing content', async ({ page }) => {
  const c = await create(page, { content_type: 'richtext' });
  await page.goto(`${CAMPAIGNS}/${c.id}#tab=content`);
  await editorReady(page);
  await switchFormat(page, 'plain', false);
  await expect(page.locator('richtext-editor')).toBeVisible();
  for (const format of ['html', 'markdown', 'plain']) {
    await switchFormat(page, format);
    await editorReady(page);
    await save(page, c.id);
    expect(await campaign(page, c.id)).toMatchObject({ content_type: format });
    await preview(page, rendered);
    await page.reload();
  }
});

test('previews and test-sends unsaved content without modifying the draft', async ({ page }) => {
  const c = await create(page, { content_type: 'plain', body: 'Saved body', subject: 'Preview test' });
  await page.goto(`${CAMPAIGNS}/${c.id}#tab=content`);
  await fillBody(page, 'plain', 'Unsaved hello {{ .Subscriber.Name }}');
  await button(page, 'Preview').click();
  await expect(page.frameLocator('.preview-modal iframe').locator('body')).toContainText('Unsaved hello Demo Subscriber');
  await button(page.locator('.preview-modal'), 'Close').click();
  await button(page.locator('.page-header'), 'Send test message').click();
  await page.locator('#campaign-test input[type="email"]').fill('[email protected]');
  await page.locator('#campaign-test input[type="email"]').press('Enter');
  await button(page.locator('#campaign-test'), 'Send').click();
  expect(JSON.stringify(await delivered('Preview test'))).toContain('Unsaved hello');
  expect(await campaign(page, c.id)).toMatchObject({ status: 'draft', body: 'Saved body' });
});

test('generates, persists and removes alternate text; plain format clears it', async ({ page }) => {
  const c = await create(page, { body: '<p>Alternate message</p>' });
  await page.goto(`${CAMPAIGNS}/${c.id}#tab=content`);
  await editorReady(page);
  const toggle = page.getByRole('tabpanel').filter({ has: page.locator('.editor-body') }).getByRole('switch');
  await toggle.check();
  const alt = page.getByRole('textbox', { name: 'Add alternate plain text message', exact: true });
  await expect(alt).toHaveValue('Alternate message');
  await alt.fill('Custom alternate');
  await save(page, c.id);
  await page.reload();
  await expect(alt).toHaveValue('Custom alternate');
  await toggle.uncheck();
  await confirm(page);
  await save(page, c.id);
  expect((await campaign(page, c.id)).altbody).toBeNull();
  await toggle.check();
  await switchFormat(page, 'plain');
  await save(page, c.id);
  expect((await campaign(page, c.id)).altbody).toBeNull();
});

test('persists attributes and archive settings with keyboard save', async ({ page }) => {
  const c = await create(page);
  await page.goto(`${CAMPAIGNS}/${c.id}`);
  await tab(page, 'Attributes').click();
  await page.getByRole('textbox', { name: 'Attributes', exact: true }).fill('{"edition":42}');
  await tab(page, 'Archive').click();
  await page.getByRole('switch').filter({ visible: true }).check();
  await page.locator('input[name="archive_slug"]').fill('newsletter-edition-42');
  await page.locator('textarea[name="archive_meta"]').fill('{"name":"Archive reader","attribs":{"city":"Mumbai"}}');
  await save(page, c.id, () => page.locator('textarea[name="archive_meta"]').press('ControlOrMeta+s'));
  await page.reload();
  await expect(page.locator('input[name="archive_slug"]')).toHaveValue('newsletter-edition-42');
  await button(page.getByRole('tabpanel').filter({ has: page.locator('input[name="archive_slug"]') }), 'Preview').click();
  await expect(page.frameLocator('.preview-modal iframe').locator('body')).toContainText('Hello Archive reader from Mumbai');
  await button(page.locator('.preview-modal'), 'Close').click();
  expect(await campaign(page, c.id)).toMatchObject({ attribs: { edition: 42 }, archive: true,
    archive_slug: 'newsletter-edition-42', archive_meta: { name: 'Archive reader', attribs: { city: 'Mumbai' } } });
});

test('rejects malformed JSON without overwriting saved metadata', async ({ page }) => {
  const c = await create(page, { headers: [{ 'X-Custom': 'saved' }], attribs: { edition: 1 } });
  await page.goto(`${CAMPAIGNS}/${c.id}`);
  for (const [name, field, valid] of [
    ['Campaign', 'textarea[name="headers"]', '[{"X-Custom":"saved"}]'],
    ['Attributes', 'textarea[aria-labelledby="campaign-attribs-label"]', '{"edition":1}'],
  ]) {
    await tab(page, name).click();
    await page.locator(field).fill('{broken');
    await button(page, 'Save changes').click();
    await expect(page.locator('output[data-variant="danger"]').last()).toContainText(/JSON|SyntaxError/);
    expect(await campaign(page, c.id)).toMatchObject({ headers: [{ 'X-Custom': 'saved' }], attribs: { edition: 1 } });
    await page.locator(field).fill(valid);
    await save(page, c.id);
  }
});

test('clones full content into a draft and cancels cloning and deletion', async ({ page }) => {
  const c = await create(page, { tags: ['clone'], headers: [{ 'X-Custom': 'copy' }],
    attribs: { edition: 2 }, altbody: 'Alternative', lists: [1, 2] });
  await page.goto(CAMPAIGNS);
  page.once('dialog', (dialog) => dialog.dismiss());
  await menu(page, c.name, 'Clone');
  await expect(rows(page)).toHaveCount(2);
  page.once('dialog', (dialog) => dialog.accept('Cloned newsletter'));
  await menu(page, c.name, 'Clone');
  await expect(page).toHaveURL(/\/campaigns\/\d+$/);
  const id = Number(new URL(page.url()).pathname.split('/').pop());
  const clone = await campaign(page, id);
  for (const key of ['subject', 'body', 'content_type', 'altbody', 'headers', 'attribs', 'tags']) expect(clone[key]).toEqual(c[key]);
  expect(clone).toMatchObject({ name: 'Cloned newsletter', status: 'draft' });
  expect(clone.uuid).not.toBe(c.uuid);
  expect(clone.lists.map((l) => l.id)).toEqual([1, 2]);
  await page.goto(CAMPAIGNS);
  await menu(page, clone.name, 'Delete');
  await button(page.locator('dialog[open]'), 'Cancel').click();
  await expect(row(page, clone.name)).toBeVisible();
  await menu(page, clone.name, 'Delete');
  await confirm(page);
  await expect(row(page, clone.name)).toHaveCount(0);
  await expect(row(page, c.name)).toBeVisible();
});

test('searches and filters campaigns through SSR navigation', async ({ page }) => {
  await data(await page.request.delete('/api/campaigns?all=true'));
  for (const name of ['Bravo', 'Alpha', 'Charlie']) await create(page, { name, tags: [name === 'Charlie' ? 'other' : 'news'] });
  const scheduled = await create(page, { name: 'Scheduled', send_at: new Date(Date.now() + 86400000).toISOString() });
  await data(await page.request.put(`/api/campaigns/${scheduled.id}/status`, { data: { status: 'scheduled' } }));
  await page.goto(CAMPAIGNS);
  await page.getByRole('textbox', { name: 'Search', exact: true }).fill('Alpha');
  await page.getByRole('textbox', { name: 'Search', exact: true }).press('Enter');
  await expect(rows(page)).toHaveCount(1);
  await expect(row(page, 'Alpha')).toBeVisible();
  await page.goto(CAMPAIGNS);
  await row(page, 'Alpha').getByRole('link', { name: '#news', exact: true }).click();
  await expect(rows(page)).toHaveCount(2);
  await expect(page).toHaveURL(/[?&]tag=news/);
  await page.getByRole('textbox', { name: 'Search', exact: true }).fill('Alpha');
  await page.getByRole('textbox', { name: 'Search', exact: true }).press('Enter');
  await expect(rows(page)).toHaveCount(1);
  await expect(page).toHaveURL(/[?&]tag=news/);
  await page.locator('.page-title').getByRole('link', { name: 'Remove', exact: true }).click();
  await expect(page).not.toHaveURL(/[?&]tag=/);
  await expect(row(page, 'Alpha')).toBeVisible();
  await page.goto(CAMPAIGNS);
  await row(page, 'Alpha').getByTitle('Filter Draft', { exact: true }).click();
  await expect(page).toHaveURL(/[?&]status=draft/);
  await expect(rows(page)).toHaveCount(3);
});

async function selectTimestamp(page, label) {
  await page.locator('[popovertarget="camp-timestamp-sort"]').click();
  await page.locator('#camp-timestamp-sort').getByRole('menuitem', { name: label, exact: true }).click();
}

// Give each timestamp a distinct order so falling back to created_at cannot pass.
async function createSortableCampaigns(page) {
  const fixtures = [
    { name: 'Sort Alpha', created_at: '2021-01-12', started_at: '2022-02-13', updated_at: '2023-03-12', send_at: '2022-01-11' },
    { name: 'Sort Bravo', created_at: '2021-01-13', started_at: '2022-02-11', updated_at: '2023-03-11', send_at: '2022-01-13' },
    { name: 'Sort Charlie', created_at: '2021-01-11', started_at: '2022-02-12', updated_at: '2023-03-13', send_at: '2022-01-12' },
  ];
  for (const fixture of fixtures) {
    const c = await create(page, { name: fixture.name, tags: ['sort-test'] });
    // Historical start/end dates cannot be set through the campaign API.
    psql(`UPDATE campaigns SET status = 'finished',
      created_at = '${fixture.created_at}T12:00:00Z', started_at = '${fixture.started_at}T12:00:00Z',
      updated_at = '${fixture.updated_at}T12:00:00Z', send_at = '${fixture.send_at}T12:00:00Z'
      WHERE id = ${c.id}`);
  }
  return fixtures;
}

const sortFilters = { query: 'Sort', tag: 'sort-test', status: 'finished', type: 'regular', per_page: '10' };
const sortURL = (params = {}) => `${CAMPAIGNS}?${new URLSearchParams({ ...sortFilters, ...params })}`;

async function expectCampaignSort(page, field, order, names) {
  await expect(page).toHaveURL((url) =>
    Object.entries({ ...sortFilters, order_by: field, order }).every(([key, value]) => url.searchParams.get(key) === value)
      && !url.searchParams.has('page'));
  await expect(campaignNames(page)).toHaveText(names);
}

test('sorts campaigns by name in both directions', async ({ page }) => {
  await createSortableCampaigns(page);
  await page.goto(sortURL({ page: '2' }));
  const heading = page.locator('.cy-name').getByRole('link', { name: 'Name', exact: true });
  await heading.click();
  await expectCampaignSort(page, 'name', 'asc', ['Sort Alpha', 'Sort Bravo', 'Sort Charlie']);
  await heading.click();
  await expectCampaignSort(page, 'name', 'desc', ['Sort Charlie', 'Sort Bravo', 'Sort Alpha']);
});

for (const { field, label, names } of [
  { field: 'created_at', label: 'Created', names: ['Sort Charlie', 'Sort Alpha', 'Sort Bravo'] },
  { field: 'started_at', label: 'Started', names: ['Sort Bravo', 'Sort Charlie', 'Sort Alpha'] },
  { field: 'updated_at', label: 'Ended', names: ['Sort Bravo', 'Sort Alpha', 'Sort Charlie'] },
  { field: 'send_at', label: 'Scheduled', names: ['Sort Alpha', 'Sort Charlie', 'Sort Bravo'] },
]) {
  test(`sorts campaigns by ${label} through the timestamp dropdown`, async ({ page }) => {
    const fixtures = await createSortableCampaigns(page);
    await page.goto(sortURL());
    const defaultCells = await rows(page).locator('td.timestamp').allTextContents();
    await page.goto(sortURL({ page: '2' }));

    await selectTimestamp(page, label);
    await expectCampaignSort(page, field, 'asc', names);
    await expect(timestampHeading(page)).toHaveText(label);
    await expect(timestampHeading(page)).toHaveAttribute('data-sorted', 'asc');
    for (const fixture of fixtures) {
      const cell = row(page, fixture.name).locator('td.timestamp');
      const date = new Date(`${fixture[field]}T12:00:00Z`);
      const month = date.toLocaleString('en-GB', { month: 'short', timeZone: 'UTC' });
      await expect(cell).toHaveAttribute('data-label', label);
      await expect(cell).toContainText(`${date.getUTCDate()} ${month} ${date.getUTCFullYear()}`);
      await expect(cell.locator('span')).toHaveCount(1);
      await expect(cell.locator('span')).not.toHaveAttribute('title', /Created:|Started:|Ended:|Scheduled:/);
    }

    // Re-selecting the option and clicking its heading both toggle direction.
    await selectTimestamp(page, label);
    await expectCampaignSort(page, field, 'desc', [...names].reverse());
    await expect(timestampHeading(page)).toHaveAttribute('data-sorted', 'desc');
    await timestampHeading(page).click();
    await expectCampaignSort(page, field, 'asc', names);
    await page.reload();
    await expect(timestampHeading(page)).toHaveText(label);

    await page.goto(sortURL({ order_by: field, order: 'asc', page: '2' }));
    await selectTimestamp(page, 'All');
    await expect(page).toHaveURL((url) =>
      Object.entries(sortFilters).every(([key, value]) => url.searchParams.get(key) === value)
        && ['order_by', 'order', 'page'].every((key) => !url.searchParams.has(key)));
    await expect(timestampHeading(page)).toHaveText('Timestamps');
    await expect(campaignNames(page)).toHaveText(['Sort Bravo', 'Sort Alpha', 'Sort Charlie']);
    await expect(rows(page).locator('td.timestamp')).toHaveText(defaultCells.map((text) => text.trim()));
    await expect(rows(page).locator('td.timestamp > span').first()).toHaveAttribute('title', /Created:.*\nScheduled:.*\nStarted:.*\nEnded:/);
  });
}

test('shows missing campaign timestamps as a dash and restores the default view', async ({ page }) => {
  const c = await create(page, { name: 'Unsent campaign' });
  await page.goto(`${CAMPAIGNS}?query=Unsent`);
  const cell = row(page, c.name).locator('td.timestamp');
  const defaultText = await cell.textContent();
  for (const label of ['Started', 'Ended', 'Scheduled']) {
    await selectTimestamp(page, label);
    await expect(timestampHeading(page)).toHaveText(label);
    await expect(cell).toHaveText('—');
  }
  await selectTimestamp(page, 'Created');
  await expect(cell.locator('span')).toBeVisible();
  await selectTimestamp(page, 'All');
  await expect(timestampHeading(page)).toHaveText('Timestamps');
  await expect(cell).toHaveText(defaultText.trim());
});

for (const { label, all, filter, unrelated } of [
  { label: 'selected IDs', all: false, filter: 'query=Bulk' },
  { label: 'all matching pages', all: true, filter: 'query=Bulk' },
  { label: 'all tagged campaigns', all: true, filter: 'tag=target', unrelated: [{ tags: ['other'] }] },
  { label: 'all campaigns with a status', all: true, filter: 'status=draft', unrelated: [{ status: 'scheduled' }] },
  { label: 'all campaigns of a type', all: true, filter: 'type=regular', unrelated: [{ type: 'optin', lists: [2] }] },
  {
    label: 'all campaigns matching combined filters', all: true,
    filter: 'query=Bulk&tag=target&tag=news&status=draft&type=regular',
    unrelated: [
      { name: 'Other' }, { tags: ['target'] }, { status: 'scheduled' }, { type: 'optin', lists: [2] },
    ],
  },
]) {
  test(`bulk deletes ${label} and preserves other campaigns`, async ({ page }) => {
    const preserved = [];
    if (unrelated) {
      await data(await page.request.delete('/api/campaigns?all=true'));
      for (const { status, ...overrides } of unrelated) {
        const c = await create(page, {
          name: 'Bulk unrelated', tags: ['target', 'news'],
          ...(status ? { send_at: new Date(Date.now() + 86400000).toISOString() } : {}),
          ...overrides,
        });
        if (status) await data(await page.request.put(`/api/campaigns/${c.id}/status`, { data: { status } }));
        preserved.push(c.id);
      }
    }
    for (let i = 0; i < (all ? 22 : 3); i += 1) {
      await create(page, { name: `Bulk ${i}`, tags: ['target', 'news'] });
    }
    await page.goto(`${CAMPAIGNS}?${filter}`);
    await page.locator('thead input[type="checkbox"]').check();
    await page.locator('button[popovertarget="camp-bulk-actions"]').click();
    if (all) await page.getByRole('menuitem', { name: /Select all/ }).click();
    await page.getByRole('menuitem', { name: /^Delete/ }).click();
    await confirm(page);
    await expect(rows(page)).toHaveCount(0);
    await expect(page.locator('.empty-state')).toBeVisible();
    await page.goto(CAMPAIGNS);
    await expect(rows(page)).toHaveCount(unrelated ? preserved.length : 1);
    if (unrelated) {
      expect(await rows(page).evaluateAll((els) => els.map((el) => Number(el.dataset.campaignId)).sort((a, b) => a - b)))
        .toEqual(preserved.sort((a, b) => a - b));
    }
  });
}

test('bulk deletion handles no matches, explicit IDs and unfiltered requests', async ({ page }) => {
  const c = await create(page, { tags: ['target'] });
  const ids = async () => (await data(await page.request.get('/api/campaigns'))).results.map((r) => r.id).sort((a, b) => a - b);
  const before = await ids();
  await data(await page.request.delete('/api/campaigns?all=true&tag=missing'));
  expect(await ids()).toEqual(before);
  await data(await page.request.delete(`/api/campaigns?id=${c.id}&tag=missing&status=paused&type=optin`));
  expect(await ids()).toEqual(before.filter((id) => id !== c.id));
  await data(await page.request.delete('/api/campaigns?all=true'));
  expect(await ids()).toEqual([]);
});

test('bulk deletion respects list permissions as well as filters', async ({ page, browser }) => {
  const permitted = await create(page, { tags: ['target'], lists: [1] });
  const forbidden = await create(page, { tags: ['target'], lists: [2] });
  const unrelated = await create(page, { tags: ['other'], lists: [1] });
  const role = await data(await page.request.post('/api/roles/users', { data: {
    name: 'Campaign manager', permissions: ['campaigns:get', 'campaigns:manage'],
  } }));
  const listRole = await data(await page.request.post('/api/roles/lists', { data: {
    name: 'Default list manager', lists: [{ id: 1, permissions: ['list:get', 'list:manage'] }],
  } }));
  const user = await data(await page.request.post('/api/users', { data: {
    username: 'bulk-manager', type: 'api', status: 'enabled', user_role_id: role.id, list_role_id: listRole.id,
  } }));
  const context = await browser.newContext({
    storageState: { cookies: [], origins: [] },
    extraHTTPHeaders: { Authorization: `Basic ${Buffer.from(`${user.username}:${user.password}`).toString('base64')}` },
  });
  try {
    await data(await context.request.delete('/api/campaigns?all=true&tag=target'));
  } finally {
    await context.close();
  }
  const remaining = (await data(await page.request.get('/api/campaigns'))).results.map((c) => c.id);
  expect(remaining).not.toContain(permitted.id);
  expect(remaining).toContain(forbidden.id);
  expect(remaining).toContain(unrelated.id);
});

test('uploads an attachment, persists it and delivers it when starting from the editor', async ({ page }) => {
  const c = await create(page, { subject: 'Attachment delivery' });
  await page.goto(`${CAMPAIGNS}/${c.id}`);
  await tab(page, 'Attachments').click();
  await button(page, 'Add attachments').click();
  const picker = page.frameLocator('.media-picker-modal iframe');
  await picker.locator('button[popovertarget="media-upload"]').click();
  await picker.locator('input[type="file"]').setInputFiles({ name: 'campaign-example.json', mimeType: 'application/json', buffer: Buffer.from('{"hello":"attachment"}') });
  await picker.locator('button[type="submit"]').filter({ hasText: 'Upload' }).click();
  await picker.locator('a.thumb').and(picker.getByTitle('campaign-example.json', { exact: true })).click();
  await expect(page.locator('.media-picker-modal')).not.toBeVisible();
  await save(page, c.id);
  await page.reload();
  await expect(page.locator('.attachments .filename')).toHaveText('campaign-example.json');
  expect((await campaign(page, c.id)).media).toHaveLength(1);
  await tab(page, 'Campaign').click();
  await button(page, 'Start campaign').click();
  await confirm(page);
  await expect(page).toHaveURL(/\/admin\/campaigns$/);
  expect(JSON.stringify(await delivered(c.subject))).toContain('campaign-example.json');
  await expect.poll(async () => (await campaign(page, c.id)).status, { timeout: 20000 }).toBe('finished');
  await page.reload();
  await expect(row(page, c.name)).toContainText('Finished');
  await page.goto(`${CAMPAIGNS}/${c.id}`);
  await expect(page.getByLabel('Name', { exact: true })).toBeDisabled();
  await expect(button(page, 'Start campaign')).toHaveCount(0);
  await tab(page, 'Archive').click();
  await page.getByRole('switch').filter({ visible: true }).check();
  await page.locator('input[name="archive_slug"]').fill('delivered-newsletter');
  const [response] = await Promise.all([
    page.waitForResponse((r) => r.url().endsWith(`/api/campaigns/${c.id}/archive`) && r.request().method() === 'PUT'),
    button(page, 'Save changes').click(),
  ]);
  await data(response);
  expect(await campaign(page, c.id)).toMatchObject({ status: 'finished', archive: true, archive_slug: 'delivered-newsletter' });
});

test('starts, pauses, resumes and cancels from the listing', async ({ page }) => {
  // Keep sending long enough to change status at the default rate of 10 messages/s.
  const list = await data(await page.request.post('/api/lists', { data: { name: 'Slow audience', type: 'private', optin: 'single' } }));
  for (let i = 0; i < 150; i += 1) {
    await data(await page.request.post('/api/subscribers', { data: {
      email: `lifecycle-${i}@example.com`, name: `Reader ${i}`, status: 'enabled', lists: [list.id],
    } }));
  }
  const c = await create(page, { lists: [list.id] });
  await page.goto(CAMPAIGNS);
  for (const [action, status] of [['Start campaign', 'running'], ['Pause', 'paused'], ['Send', 'running'], ['Cancel', 'cancelled']]) {
    await menu(page, c.name, action);
    await confirm(page);
    await expect(row(page, c.name)).toHaveClass(`status-${status}`);
    expect((await campaign(page, c.id)).status).toBe(status);
  }
  await openMenu(row(page, c.name));
  await expect(row(page, c.name).getByRole('menuitem', { name: 'Start campaign', exact: true })).toHaveCount(0);
});

for (const format of ['richtext', 'visual']) {
  for (const embed of [true, false]) {
    test(`${format} image ${embed ? 'embeds as MIME/CID' : 'stays a URL'} after reload`, async ({ page }) => {
      const c = await create(page, { content_type: format, body: '', subject: `${format} image ${embed}` });
      const media = await data(await page.request.post('/api/media', { multipart: { file: {
        name: 'campaign-pixel.png', mimeType: 'image/png',
        buffer: Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC', 'base64'),
      } } }));
      await page.goto(`${CAMPAIGNS}/${c.id}#tab=content`);
      await editorReady(page);
      if (format === 'richtext') {
        await button(page, 'Image').click();
        const dialog = page.locator('richtext-editor dialog[open]');
        await button(dialog, 'Media').click();
        await page.frameLocator('.media-picker-modal iframe').getByRole('link', { name: media.filename, exact: true }).click();
        await expect(dialog.locator('input[name="src"]')).toHaveValue(media.url);
        await dialog.getByRole('checkbox', { name: 'Embed', exact: true }).setChecked(embed);
        await button(dialog, 'Insert').click();
        await expect(page.locator('richtext-editor [contenteditable] img')).toHaveAttribute('src', media.url);
      } else {
        await visualDocument(page, {
          root: { type: 'EmailLayout', data: { childrenIds: ['image'] } },
          image: { type: 'Image', data: { props: { url: media.url, embed: false }, style: {} } },
        });
        const frame = page.frameLocator('#visual-editor');
        await frame.locator('#visual-editor-container img').click();
        await frame.getByRole('checkbox').setChecked(embed);
      }
      await save(page, c.id);
      await page.reload();
      await editorReady(page);
      if (format === 'richtext') {
        await page.locator('richtext-editor [contenteditable] img').click();
        await button(page, 'Image').click();
        await expect(page.locator('richtext-editor dialog[open]').getByRole('checkbox', { name: 'Embed', exact: true })).toBeChecked({ checked: embed });
        await button(page.locator('richtext-editor dialog[open]'), 'Close').click();
      } else {
        const frame = page.frameLocator('#visual-editor');
        await frame.locator('#visual-editor-container img').click();
        await expect(frame.getByRole('checkbox')).toBeChecked({ checked: embed });
      }
      await tab(page, 'Campaign').click();
      await button(page, 'Start campaign').click();
      await confirm(page);
      const raw = JSON.stringify(await delivered(c.subject));
      expect(raw.includes('image/png')).toBe(embed);
      expect(raw.includes('cid:')).toBe(embed);
      expect(raw.includes('Content-Id')).toBe(embed);
    });
  }
}

for (const tracked of [true, false]) {
  test(`richtext link tracking follows the URL (${tracked ? 'on' : 'off'}) and persists toggles`, async ({ page }) => {
    const url = 'https://example.com/docs?edition=42#intro';
    const href = (track) => `${url}${track ? '@TrackLink' : ''}`;
    const c = await create(page, { content_type: 'richtext', body:
      `<p><a href="${href(tracked)}">Documentation</a> <a href="${href(!tracked)}">Other link</a></p>` });
    await page.goto(`${CAMPAIGNS}/${c.id}#tab=content`);
    await editorReady(page);

    // Existing links must override the remembered preference for newly inserted links.
    await page.evaluate((value) => localStorage.setItem('trackLink', String(value)), !tracked);
    const link = page.locator('richtext-editor [contenteditable]').getByRole('link', { name: 'Documentation', exact: true });
    const dialog = page.locator('richtext-editor dialog[open]');
    const checkbox = dialog.getByRole('checkbox', { name: 'Track link?', exact: true });
    await link.click();
    await button(page, 'Link').click();
    await expect(dialog.locator('input[name="url"]')).toHaveValue(url);
    await expect(checkbox).toBeChecked({ checked: tracked });
    await button(dialog, 'Close').click();

    // Reusing the URL dialog for another link must recompute the checkbox state.
    await page.locator('richtext-editor [contenteditable]').getByRole('link', { name: 'Other link', exact: true }).click();
    await button(page, 'Link').click();
    await expect(checkbox).toBeChecked({ checked: !tracked });
    await button(dialog, 'Close').click();
    await link.click();
    await button(page, 'Link').click();
    await expect(checkbox).toBeChecked({ checked: tracked });
    await checkbox.setChecked(!tracked);
    await button(dialog, 'Apply').click();
    await expect(link).toHaveAttribute('href', href(!tracked));
    await save(page, c.id);
    expect((await campaign(page, c.id)).body).toContain(`href="${href(!tracked)}"`);
    await page.reload();
    await editorReady(page);
    await link.click();
    await button(page, 'Link').click();
    await expect(dialog.locator('input[name="url"]')).toHaveValue(url);
    await expect(checkbox).toBeChecked({ checked: !tracked });
    await button(dialog, 'Close').click();
  });
}