Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

26.5 KB
Raw Blame
import { expect, type Page, test } from '@playwright/test'
import {
  adminRequest,
  FIXTURE_BULK_CHANNEL_NAME,
  FIXTURE_PROMO_COUNTRY,
  FIXTURE_PROMO_CUSTOMER_FIRST_NAME,
  FIXTURE_PROMO_CUSTOMER_FULL_NAME,
  FIXTURE_PROMO_CUSTOMER_GROUP,
  FIXTURE_PROMO_PRODUCT,
  FIXTURE_PROMO_TAXON,
  gotoIndex,
  login,
  rowButton,
  saveCustomFieldWithPage,
  withCustomFieldDefinition,
} from './helpers'

async function startNewPromotion(page: Page, storeId: string, name: string) {
  await page.getByRole('button', { name: /new promotion/i }).click()
  await expect(page).toHaveURL(new RegExp(`/${storeId}/promotions/new`), { timeout: 15_000 })
  await expect(page.getByRole('heading', { name: /^new promotion$/i })).toBeVisible({
    timeout: 15_000,
  })
  await page.locator('#name').fill(name)
  // Kind defaults to "Coupon code"; switch to automatic so we don't have to
  // generate a code each time.
  await page.locator('#kind').click()
  await page.getByRole('option', { name: /automatic/i }).click()
}

async function pickRule(page: Page, ruleLabel: RegExp) {
  await page.getByRole('button', { name: /^add rule$/i }).click()
  await expect(page.getByRole('heading', { name: /^add rule$/i })).toBeVisible()
  await page.getByRole('button', { name: ruleLabel }).click()
}

async function pickAction(page: Page, actionLabel: RegExp) {
  await page.getByRole('button', { name: /^add action$/i }).click()
  await expect(page.getByRole('heading', { name: /^add action$/i })).toBeVisible()
  await page.getByRole('button', { name: actionLabel }).click()
}

async function cancelEditor(page: Page) {
  await page
    .getByRole('dialog')
    .getByRole('button', { name: /^cancel$/i })
    .click()
}

async function saveEditor(page: Page) {
  // Zero-config rule/action editors label the confirm button "Add"; the rest use "Save".
  await page
    .getByRole('dialog')
    .getByRole('button', { name: /^(save|add)$/i })
    .click()
}

// Base UI's Combobox closes the dropdown on select; don't press Escape because
// the keydown bubbles up to the Sheet and dismisses the entire editor.
async function pickAutocompleteOption(page: Page, placeholderRegex: RegExp, optionLabel: string) {
  const input = page.getByRole('dialog').getByPlaceholder(placeholderRegex)
  await input.fill(optionLabel)
  await page
    .getByRole('option', { name: new RegExp(optionLabel, 'i') })
    .first()
    .click()
}

async function submitCreate(page: Page, name: string) {
  await page.getByRole('button', { name: /^create promotion$/i }).click()
  await expect(page.getByRole('heading', { name })).toBeVisible({ timeout: 15_000 })
}

// Starts a whole-order adjustment on the Tiered Percent calculator and adds
// one row per `[threshold, value]` pair, in the order given.
async function addTieredPercentAction(page: Page, tiers: [string, string][]) {
  await pickAction(page, /^create whole-order adjustment\b/i)
  const calculatorSelect = page.locator('#calculator-type')
  await expect(calculatorSelect).toBeEnabled({ timeout: 10_000 })
  await calculatorSelect.click()
  await page.getByRole('option', { name: /^tiered percent$/i }).click()

  const dialog = page.getByRole('dialog')
  for (const [index, [threshold, value]] of tiers.entries()) {
    await dialog.getByRole('button', { name: /^add tier$/i }).click()
    await dialog
      .getByLabel(/^order total/i)
      .nth(index)
      .fill(threshold)
    await dialog
      .getByLabel(/^discount$/i)
      .nth(index)
      .fill(value)
  }
}

async function openAdjustmentAction(page: Page, calculator: RegExp) {
  await page
    .locator('div.items-stretch')
    .filter({ hasText: /create whole-order adjustment/i })
    .first()
    .getByRole('button')
    .first()
    .click()
  await expect(page.getByRole('heading', { name: /^create whole-order adjustment$/i })).toBeVisible(
    { timeout: 5_000 },
  )
  await expect(page.locator('#calculator-type')).toContainText(calculator, { timeout: 10_000 })
}

// The server keeps each number as an exact decimal, so 100 reads back as
// "100.0"; compare the numbers rather than their text.
const decimal = (n: string) => new RegExp(`^${n}(\\.0+)?$`)

async function expectTiers(page: Page, tiers: [string, string][]) {
  const dialog = page.getByRole('dialog')
  await expect(dialog.getByLabel(/^order total/i)).toHaveCount(tiers.length)
  for (const [index, [threshold, value]] of tiers.entries()) {
    await expect(dialog.getByLabel(/^order total/i).nth(index)).toHaveValue(decimal(threshold))
    await expect(dialog.getByLabel(/^discount$/i).nth(index)).toHaveValue(decimal(value))
  }
}

const PROMOTIONS_PATH = (storeId: string) => `/${storeId}/promotions`
const CTA = /new promotion/i

test.describe('promotions', () => {
  test('lists promotions', async ({ page }) => {
    const creds = await login(page)
    await gotoIndex(page, PROMOTIONS_PATH(creds.store_id), CTA)
  })

  test('creates an automatic promotion with a rule and an action', async ({ page }) => {
    const creds = await login(page)
    await gotoIndex(page, PROMOTIONS_PATH(creds.store_id), CTA)

    const name = `E2E Promo ${Date.now()}`

    await startNewPromotion(page, creds.store_id, name)

    // No-preference rule + action: confirm in the editor so the row is appended.
    await pickRule(page, /^first order\b/i)
    await expect(page.getByRole('heading', { name: /^first order$/i })).toBeVisible({
      timeout: 5_000,
    })
    await saveEditor(page)

    await pickAction(page, /^free shipping\b/i)
    await saveEditor(page)

    await submitCreate(page, name)

    // Creating replaces the new-form route in history; back goes to the list,
    // not the stale create form (which would duplicate on re-save).
    await page.getByRole('button', { name: /^back$/i }).click()
    await expect(page).toHaveURL(new RegExp(`/${creds.store_id}/promotions(?:\\?|$)`), {
      timeout: 15_000,
    })
    await expect(page.getByRole('heading', { name: /^new promotion$/i })).toHaveCount(0)
    await expect(rowButton(page, name)).toBeVisible({ timeout: 15_000 })
  })

  test('cancelling a rule or action editor does not add a row', async ({ page }) => {
    const creds = await login(page)
    await gotoIndex(page, PROMOTIONS_PATH(creds.store_id), CTA)

    const name = `E2E Promo Cancel ${Date.now()}`
    await startNewPromotion(page, creds.store_id, name)

    await pickRule(page, /^first order\b/i)
    await expect(page.getByRole('heading', { name: /^first order$/i })).toBeVisible({
      timeout: 5_000,
    })
    await cancelEditor(page)
    await expect(page.getByText(/^first order$/i)).toHaveCount(0)

    await pickAction(page, /^free shipping\b/i)
    await cancelEditor(page)
    await expect(page.getByText(/^free shipping$/i)).toHaveCount(0)
  })

  test('removes a rule and an action while editing', async ({ page }) => {
    const creds = await login(page)
    await gotoIndex(page, PROMOTIONS_PATH(creds.store_id), CTA)

    const name = `E2E Promo Edit ${Date.now()}`

    await startNewPromotion(page, creds.store_id, name)

    await pickRule(page, /^first order\b/i)
    await saveEditor(page)

    await pickAction(page, /^free shipping\b/i)
    await saveEditor(page)

    await submitCreate(page, name)

    await expect(page.getByText(/^first order$/i).first()).toBeVisible()
    await expect(page.getByText(/^free shipping$/i).first()).toBeVisible()

    // Rule/action rows are flex containers holding an edit button (with the
    // rule label) and a trash button. Scope by the row's class so we don't
    // pick up unrelated buttons in ancestor wrappers.
    const ruleRow = page.locator('div.items-stretch').filter({ hasText: 'First order' }).first()
    await ruleRow.getByRole('button').last().click()
    await expect(page.getByRole('heading', { name: /remove rule\?/i })).toBeVisible()
    await page
      .getByRole('dialog')
      .getByRole('button', { name: /^remove$/i })
      .click()
    await expect(page.getByText(/^first order$/i)).toHaveCount(0, { timeout: 5_000 })

    const actionRow = page.locator('div.items-stretch').filter({ hasText: 'Free shipping' }).first()
    await actionRow.getByRole('button').last().click()
    await expect(page.getByRole('heading', { name: /remove action\?/i })).toBeVisible()
    await page
      .getByRole('dialog')
      .getByRole('button', { name: /^remove$/i })
      .click()
    await expect(page.getByText(/^free shipping$/i)).toHaveCount(0, { timeout: 5_000 })

    await page.getByRole('button', { name: /^save$/i }).click()
  })

  // Each test below exercises one custom rule/action editor end-to-end: the
  // editor opens, the resource picker resolves a fixture record (seeded in
  // global-setup.ts), and Save round-trips through the server.

  test('creates a promotion with a Country rule', async ({ page }) => {
    const creds = await login(page)
    await gotoIndex(page, PROMOTIONS_PATH(creds.store_id), CTA)

    const name = `E2E Country Promo ${Date.now()}`
    await startNewPromotion(page, creds.store_id, name)

    await pickRule(page, /^country\b/i)
    await expect(page.getByRole('heading', { name: /^country$/i })).toBeVisible({
      timeout: 5_000,
    })
    await pickAutocompleteOption(page, /search countries/i, FIXTURE_PROMO_COUNTRY)
    await saveEditor(page)

    await expect(page.getByText(FIXTURE_PROMO_COUNTRY).first()).toBeVisible({ timeout: 5_000 })

    await submitCreate(page, name)
  })

  // Both rules keep prefixed ids in their preferences; reloading proves they
  // were saved and read back as the records they name.
  test('creates a promotion with Channel and Market rules', async ({ page }) => {
    const creds = await login(page)
    await gotoIndex(page, PROMOTIONS_PATH(creds.store_id), CTA)

    const name = `E2E Channel Market Promo ${Date.now()}`
    await startNewPromotion(page, creds.store_id, name)

    await pickRule(page, /^channel\(s\)/i)
    await expect(page.getByRole('heading', { name: /^channel\(s\)$/i })).toBeVisible({
      timeout: 5_000,
    })
    await pickAutocompleteOption(page, /search sales channels/i, FIXTURE_BULK_CHANNEL_NAME)
    await saveEditor(page)

    await pickRule(page, /^market\(s\)/i)
    await expect(page.getByRole('heading', { name: /^market\(s\)$/i })).toBeVisible({
      timeout: 5_000,
    })
    await pickAutocompleteOption(page, /search markets/i, 'Europe')
    await saveEditor(page)

    await submitCreate(page, name)

    await page.reload()
    await expect(page.getByText(FIXTURE_BULK_CHANNEL_NAME).first()).toBeVisible({
      timeout: 15_000,
    })
    await expect(page.getByText('Europe', { exact: true }).first()).toBeVisible()
  })

  test('creates a promotion with a Product rule', async ({ page }) => {
    const creds = await login(page)
    await gotoIndex(page, PROMOTIONS_PATH(creds.store_id), CTA)

    const name = `E2E Product Promo ${Date.now()}`
    await startNewPromotion(page, creds.store_id, name)

    // Rule labels come from `Spree.t("promotion_rule_types.*.name")`.
    await pickRule(page, /^product\(s\)/i)
    await expect(page.getByRole('heading', { name: /^product\(s\)$/i })).toBeVisible({
      timeout: 5_000,
    })
    // The match-policy options render as `<FieldLabel>` cards wrapping a
    // Base UI radio. Click the visible card title to pick "all".
    await page.getByText(/^all of these products$/i).click()
    await pickAutocompleteOption(page, /search products by name/i, FIXTURE_PROMO_PRODUCT)
    await saveEditor(page)

    await expect(page.getByText(FIXTURE_PROMO_PRODUCT).first()).toBeVisible({ timeout: 5_000 })

    await submitCreate(page, name)
  })

  test('creates a promotion with a Category rule', async ({ page }) => {
    const creds = await login(page)
    await gotoIndex(page, PROMOTIONS_PATH(creds.store_id), CTA)

    const name = `E2E Category Promo ${Date.now()}`
    await startNewPromotion(page, creds.store_id, name)

    // Class is `Spree::Promotion::Rules::Taxon`; the translated label is
    // "Categories" per the 6.0 Taxon→Category rename.
    await pickRule(page, /^categories\b/i)
    await expect(page.getByRole('heading', { name: /^categories$/i })).toBeVisible({
      timeout: 5_000,
    })
    await page.getByText(/^any of these categories$/i).click()
    await pickAutocompleteOption(page, /search categories/i, FIXTURE_PROMO_TAXON)
    await saveEditor(page)

    await expect(page.getByText(FIXTURE_PROMO_TAXON).first()).toBeVisible({ timeout: 5_000 })

    await submitCreate(page, name)
  })

  test('creates a promotion with a Customer rule', async ({ page }) => {
    const creds = await login(page)
    await gotoIndex(page, PROMOTIONS_PATH(creds.store_id), CTA)

    const name = `E2E Customer Promo ${Date.now()}`
    await startNewPromotion(page, creds.store_id, name)

    // Class is `Rules::User`; translated label is "Customers" because the
    // rule keys off `Spree::Order#user_id`.
    await pickRule(page, /^customers\b/i)
    await expect(page.getByRole('heading', { name: /^customers$/i })).toBeVisible({
      timeout: 5_000,
    })

    // `Spree.customer_class.search` matches first_name/last_name (LIKE) and email
    // (exact). Search by first name; the row summary renders `full_name`.
    await pickAutocompleteOption(
      page,
      /search customers by name or email/i,
      FIXTURE_PROMO_CUSTOMER_FIRST_NAME,
    )
    await saveEditor(page)

    await expect(page.getByText(FIXTURE_PROMO_CUSTOMER_FULL_NAME).first()).toBeVisible({
      timeout: 5_000,
    })

    await submitCreate(page, name)
  })

  test('creates a promotion with a Customer Group rule', async ({ page }) => {
    const creds = await login(page)
    await gotoIndex(page, PROMOTIONS_PATH(creds.store_id), CTA)

    const name = `E2E Group Promo ${Date.now()}`
    await startNewPromotion(page, creds.store_id, name)

    await pickRule(page, /^customer group\(s\)/i)
    await expect(page.getByRole('heading', { name: /^customer group\(s\)$/i })).toBeVisible({
      timeout: 5_000,
    })
    await pickAutocompleteOption(page, /search customer groups/i, FIXTURE_PROMO_CUSTOMER_GROUP)
    await saveEditor(page)

    await expect(page.getByText(FIXTURE_PROMO_CUSTOMER_GROUP).first()).toBeVisible({
      timeout: 5_000,
    })

    await submitCreate(page, name)
  })

  test('creates a promotion with a Currency rule defaulting to store currency', async ({
    page,
  }) => {
    const creds = await login(page)
    await gotoIndex(page, PROMOTIONS_PATH(creds.store_id), CTA)

    const name = `E2E Currency Promo ${Date.now()}`
    await startNewPromotion(page, creds.store_id, name)

    // The Currency rule has a single `:currency` preference with no schema
    // default. The picker should seed it from the store's default currency so
    // saving the editor (without touching the dropdown) round-trips a real
    // value — not an empty `preferences: {}` that the server quietly accepts
    // but the merchant never sees in the rule preview.
    await pickRule(page, /^currency\b/i)
    await expect(page.getByRole('heading', { name: /^currency$/i })).toBeVisible({
      timeout: 5_000,
    })
    await saveEditor(page)

    // Row summary renders `Currency: USD` (humanized key + uppercased ISO).
    await expect(page.getByText(/currency:\s*USD/i).first()).toBeVisible({ timeout: 5_000 })

    await submitCreate(page, name)

    // Reopen the saved promotion's rule editor and confirm the currency
    // persisted server-side, not just in client memory.
    await expect(page.getByText(/currency:\s*USD/i).first()).toBeVisible({ timeout: 5_000 })
  })

  test('reopens a Create Adjustment action on the configured calculator', async ({ page }) => {
    const creds = await login(page)
    await gotoIndex(page, PROMOTIONS_PATH(creds.store_id), CTA)

    const name = `E2E Adjustment Edit ${Date.now()}`
    await startNewPromotion(page, creds.store_id, name)

    await pickAction(page, /^create whole-order adjustment\b/i)
    await expect(
      page.getByRole('heading', { name: /^create whole-order adjustment$/i }),
    ).toBeVisible({ timeout: 5_000 })

    const calculatorSelect = page.locator('#calculator-type')
    await expect(calculatorSelect).toBeEnabled({ timeout: 10_000 })
    await calculatorSelect.click()
    await page.getByRole('option', { name: /^flat rate$/i }).click()
    await saveEditor(page)

    await submitCreate(page, name)

    await openAdjustmentAction(page, /flat rate/i)
  })

  test('creates a promotion with a Create Adjustment action', async ({ page }) => {
    const creds = await login(page)
    await gotoIndex(page, PROMOTIONS_PATH(creds.store_id), CTA)

    const name = `E2E Adjustment Promo ${Date.now()}`
    await startNewPromotion(page, creds.store_id, name)

    await pickAction(page, /^create whole-order adjustment\b/i)
    await expect(
      page.getByRole('heading', { name: /^create whole-order adjustment$/i }),
    ).toBeVisible({ timeout: 5_000 })

    // Calculator defaults to the first entry once the catalog arrives; wait
    // for the trigger to enable before saving.
    await expect(page.locator('#calculator-type')).toBeEnabled({ timeout: 10_000 })
    await saveEditor(page)

    await expect(page.getByText(/^create whole-order adjustment$/i).first()).toBeVisible()

    await submitCreate(page, name)
  })

  // Money goes to the API as an exact decimal string; each value must read
  // back as typed after the promotion is saved and reloaded.
  test('keeps item total comparisons and exact amounts after reload', async ({ page }) => {
    const creds = await login(page)
    await gotoIndex(page, PROMOTIONS_PATH(creds.store_id), CTA)

    const name = `E2E Money Promo ${Date.now()}`
    await startNewPromotion(page, creds.store_id, name)

    await pickRule(page, /^item total\b/i)
    const ruleDialog = page.getByRole('dialog')
    await ruleDialog.locator('#preference-amount_min').fill('50.25')
    await ruleDialog.locator('#preference-amount_max').fill('250.75')

    const minimumComparison = ruleDialog.locator('#preference-operator_min')
    await minimumComparison.click()
    await page
      .getByRole('option', { name: /greater than or equal to \(includes the minimum\)/i })
      .click()
    await expect(minimumComparison).toContainText(/greater than or equal to/i)

    const maximumComparison = ruleDialog.locator('#preference-operator_max')
    await maximumComparison.click()
    await page
      .getByRole('option', { name: /less than or equal to \(includes the maximum\)/i })
      .click()
    await expect(maximumComparison).toContainText(/less than or equal to/i)

    await expect(ruleDialog.getByText(/^minimum comparison$/i)).toBeVisible()
    await expect(ruleDialog.getByText(/^maximum comparison$/i)).toBeVisible()
    await expect(
      ruleDialog.getByText(/for free shipping on item totals of 150 or more/i),
    ).toBeVisible()
    await saveEditor(page)

    await pickAction(page, /^create whole-order adjustment\b/i)
    const calculatorSelect = page.locator('#calculator-type')
    await expect(calculatorSelect).toBeEnabled({ timeout: 10_000 })
    await calculatorSelect.click()
    await page.getByRole('option', { name: /^flat rate$/i }).click()
    await page.getByRole('dialog').locator('#preference-amount').fill('12.50')
    await saveEditor(page)

    await submitCreate(page, name)
    await page.reload()
    await expect(page.getByRole('heading', { name })).toBeVisible({ timeout: 15_000 })

    await openAdjustmentAction(page, /flat rate/i)
    // A money preference is written to its calculator's currency, so the
    // amount keeps its cents.
    await expect(page.getByRole('dialog').locator('#preference-amount')).toHaveValue('12.50')
    await cancelEditor(page)

    await page
      .locator('div.items-stretch')
      .filter({ hasText: /^item total/i })
      .first()
      .getByRole('button')
      .first()
      .click()
    const savedRuleDialog = page.getByRole('dialog')
    await expect(savedRuleDialog.locator('#preference-amount_min')).toHaveValue('50.25', {
      timeout: 5_000,
    })
    await expect(savedRuleDialog.locator('#preference-amount_max')).toHaveValue('250.75')
    await expect(savedRuleDialog.locator('#preference-operator_min')).toContainText(
      /greater than or equal to/i,
    )
    await expect(savedRuleDialog.locator('#preference-operator_max')).toContainText(
      /less than or equal to/i,
    )
    await expect(savedRuleDialog.getByText(/^minimum comparison$/i)).toBeVisible()
    await expect(savedRuleDialog.getByText(/^maximum comparison$/i)).toBeVisible()
  })

  test('keeps a flat percent discount exactly', async ({ page }) => {
    const creds = await login(page)
    await gotoIndex(page, PROMOTIONS_PATH(creds.store_id), CTA)

    const name = `E2E Percent Promo ${Date.now()}`
    await startNewPromotion(page, creds.store_id, name)

    await pickAction(page, /^create whole-order adjustment\b/i)
    const calculatorSelect = page.locator('#calculator-type')
    await expect(calculatorSelect).toBeEnabled({ timeout: 10_000 })
    await calculatorSelect.click()
    await page.getByRole('option', { name: /^flat percent$/i }).click()
    await page.getByRole('dialog').locator('#preference-flat_percent').fill('7.5')
    await saveEditor(page)

    await submitCreate(page, name)
    await page.reload()
    await expect(page.getByRole('heading', { name })).toBeVisible({ timeout: 15_000 })

    await openAdjustmentAction(page, /flat percent/i)
    await expect(page.getByRole('dialog').locator('#preference-flat_percent')).toHaveValue('7.5')
  })

  test('saves the tiers of a tiered calculator, lowest threshold first', async ({ page }) => {
    const creds = await login(page)
    await gotoIndex(page, PROMOTIONS_PATH(creds.store_id), CTA)

    const name = `E2E Tiers Promo ${Date.now()}`
    await startNewPromotion(page, creds.store_id, name)

    // Entered out of order: the saved tiers come back sorted by threshold.
    await addTieredPercentAction(page, [
      ['250', '15'],
      ['100', '10'],
    ])
    await saveEditor(page)
    await expect(page.getByText(/tiered percent · tiers: 2/i).first()).toBeVisible({
      timeout: 5_000,
    })

    await submitCreate(page, name)

    await openAdjustmentAction(page, /tiered percent/i)
    await expectTiers(page, [
      ['100', '10'],
      ['250', '15'],
    ])
  })

  test('edits and removes tiers on a saved promotion', async ({ page }) => {
    const creds = await login(page)
    await gotoIndex(page, PROMOTIONS_PATH(creds.store_id), CTA)

    const name = `E2E Tiers Edit ${Date.now()}`
    await startNewPromotion(page, creds.store_id, name)
    await addTieredPercentAction(page, [
      ['100', '10'],
      ['250', '15'],
    ])
    await saveEditor(page)
    await submitCreate(page, name)

    await openAdjustmentAction(page, /tiered percent/i)
    const dialog = page.getByRole('dialog')
    await dialog
      .getByRole('button', { name: /^remove tier$/i })
      .first()
      .click()
    await dialog
      .getByLabel(/^discount$/i)
      .first()
      .fill('20')
    await saveEditor(page)

    await page.getByRole('button', { name: /^save$/i }).click()
    await expect(page.getByText(/promotion saved/i).first()).toBeVisible({ timeout: 15_000 })

    // Read back from the server, not from the form's memory.
    await page.reload()
    await expect(page.getByRole('heading', { name })).toBeVisible({ timeout: 15_000 })
    await openAdjustmentAction(page, /tiered percent/i)
    await expectTiers(page, [['250', '20']])
  })

  test('refuses a tier discount above 100 percent', async ({ page }) => {
    const creds = await login(page)
    await gotoIndex(page, PROMOTIONS_PATH(creds.store_id), CTA)

    const name = `E2E Tiers Invalid ${Date.now()}`
    await startNewPromotion(page, creds.store_id, name)
    await addTieredPercentAction(page, [['100', '150']])
    await saveEditor(page)

    await page.getByRole('button', { name: /^create promotion$/i }).click()
    await expect(page.getByText(/between 0% and 100%/i).first()).toBeVisible({ timeout: 15_000 })
    await expect(page.getByRole('heading', { name: /^new promotion$/i })).toBeVisible()
  })

  test('creates a promotion with a Create Item Adjustments action', async ({ page }) => {
    const creds = await login(page)
    await gotoIndex(page, PROMOTIONS_PATH(creds.store_id), CTA)

    const name = `E2E Item Adjustments Promo ${Date.now()}`
    await startNewPromotion(page, creds.store_id, name)

    await pickAction(page, /^create per-line-item adjustment\b/i)
    await expect(
      page.getByRole('heading', { name: /^create per-line-item adjustment$/i }),
    ).toBeVisible({ timeout: 5_000 })

    await expect(page.locator('#calculator-type')).toBeEnabled({ timeout: 10_000 })
    await saveEditor(page)

    await expect(page.getByText(/^create per-line-item adjustment$/i).first()).toBeVisible()

    await submitCreate(page, name)
  })

  test('creates a promotion with a Create Line Items action', async ({ page }) => {
    const creds = await login(page)
    await gotoIndex(page, PROMOTIONS_PATH(creds.store_id), CTA)

    const name = `E2E Line Items Promo ${Date.now()}`
    await startNewPromotion(page, creds.store_id, name)

    await pickAction(page, /^create line items\b/i)
    await expect(page.getByRole('heading', { name: /^create line items$/i })).toBeVisible({
      timeout: 5_000,
    })

    await pickAutocompleteOption(page, /search variants by name or sku/i, FIXTURE_PROMO_PRODUCT)
    await saveEditor(page)

    await expect(page.getByText(/1 variants/i).first()).toBeVisible({ timeout: 5_000 })

    await submitCreate(page, name)
  })

  test('deletes a promotion', async ({ page }) => {
    const creds = await login(page)
    await gotoIndex(page, PROMOTIONS_PATH(creds.store_id), CTA)

    const name = `E2E Promo Delete ${Date.now()}`

    await startNewPromotion(page, creds.store_id, name)
    await submitCreate(page, name)

    // Delete lives in the header's more-actions menu, away from Save.
    await page.getByRole('button', { name: /more actions/i }).click()
    await page.getByRole('menuitem', { name: /^delete$/i }).click()
    await expect(page.getByRole('heading', { name: /delete promotion\?/i })).toBeVisible()
    await page
      .getByRole('dialog')
      .getByRole('button', { name: /^delete$/i })
      .click()

    await expect(page).toHaveURL(new RegExp(`/${creds.store_id}/promotions(?:\\?|$)`), {
      timeout: 15_000,
    })
    await expect(rowButton(page, name)).toHaveCount(0, { timeout: 15_000 })
  })

  test('saves a promotion custom field with the page Save', async ({ page }) => {
    const creds = await login(page)
    await withCustomFieldDefinition(page, creds, 'promotion', async (label) => {
      const promotion = await adminRequest<{ id: string }>(page, creds, 'post', '/promotions', {
        name: `E2E Custom Field Promo ${Date.now()}`,
        kind: 'automatic',
      })
      await page.goto(`${PROMOTIONS_PATH(creds.store_id)}/${promotion.id}`)
      await saveCustomFieldWithPage(page, label, 'Spring campaign')
    })
  })
})