marketingPushStrategy.e2e.js 12 KB
import path from "path";
import { expect, test } from "@playwright/test";
import { createLoggedInPage, getBaseUrl } from "./helpers/auth.js";

const BASE_URL = getBaseUrl();
const IMAGE_FIXTURE = path.resolve(process.cwd(), "public", "header-man.jpg");

const LOGIN_ACCOUNT = "glsadmin";
const LOGIN_PASSWORD = "123456";
const RECORD_DETAIL_STRATEGY_NAME = "测试发送策略";

function getUniqueStrategyName(prefix = "E2E营销推送策略") {
	return `${prefix}-${Date.now()}`;
}

async function waitForNetworkStable(page) {
	await page.waitForLoadState("networkidle");
	await page.waitForTimeout(500);
}

async function waitForMetaResponse(page) {
	const response = await page.waitForResponse((resp) => {
		const request = resp.request();
		const postData = request.postData() || "";
		return request.method() === "POST"
			&& postData.includes("method=dj.api.smartcarlife.sop.strategy.meta");
	}, { timeout: 60000 });
	expect(response.ok()).toBeTruthy();
	return response;
}

async function waitForModifyPageReady(page) {
	await expect(page.locator(".wrapper")).toBeVisible({ timeout: 30000 });
	await expect(page.locator(".box").first()).toContainText("基础信息", { timeout: 30000 });
	await expect(page.locator(".footer")).toBeVisible({ timeout: 30000 });
	await page.waitForFunction(() => {
		const wrapper = document.querySelector(".wrapper");
		if (!wrapper) {
			return false;
		}
		return wrapper.querySelectorAll("input, textarea, .el-select, .el-radio").length > 0;
	}, null, { timeout: 60000 });
}

async function gotoStrategyList(page) {
	await page.goto(`${BASE_URL}/#/marketing-push-strategy`);
	await waitForNetworkStable(page);
	await expect(page.locator(".show-search")).toBeVisible();
	await expect(page.locator(".d2-table")).toBeVisible();
}

async function selectElementOption(page, trigger, optionText) {
	await trigger.click();
	const dropdown = page.locator(".el-select-dropdown:visible").last();
	await expect(dropdown).toBeVisible();
	if (optionText) {
		const targetOption = dropdown.locator(".el-select-dropdown__item").filter({ hasText: optionText }).first();
		await expect(targetOption).toBeVisible({ timeout: 10000 });
		await targetOption.click();
	} else {
		await dropdown.locator(".el-select-dropdown__item:not(.is-disabled)").first().click();
	}
	await page.waitForTimeout(300);
}

async function waitForSuccessMessage(page, text = "操作成功") {
	await expect(page.locator(".el-message .el-message__content").filter({ hasText: text }).last()).toBeVisible({ timeout: 20000 });
}

async function filterByStrategyName(page, strategyName) {
	const nameInput = page.locator(".show-search input").first();
	await nameInput.fill(strategyName);
	await page.getByRole("button", { name: "查询" }).click();
	await waitForNetworkStable(page);
}

async function resetSearchForm(page) {
	await page.getByRole("button", { name: "重置" }).click();
	await waitForNetworkStable(page);
}

async function getStrategyRow(page, strategyName) {
	return page.locator(".el-table__body tr").filter({ hasText: strategyName }).first();
}

async function waitForStrategyRow(page, strategyName, options = {}) {
	const {
		attempts = 10,
		interval = 2000,
	} = options;

	for (let index = 0; index < attempts; index += 1) {
		await filterByStrategyName(page, strategyName);
		const row = await getStrategyRow(page, strategyName);
		if (await row.count()) {
			return row;
		}
		await page.waitForTimeout(interval);
	}

	throw new Error(`未查询到策略: ${strategyName}`);
}

async function clickRowAction(row, actionText) {
	const actionCell = row.locator("td").last();
	const buttonAction = actionCell.locator("button").filter({ hasText: actionText }).first();
	if (await buttonAction.count()) {
		await buttonAction.click({ force: true });
		return;
	}

	await actionCell.evaluate((cell, text) => {
		const target = Array.from(cell.querySelectorAll("*")).find((node) => {
			return node.textContent && node.textContent.trim() === text;
		});
		if (!target) {
			throw new Error(`未找到操作: ${text}`);
		}
		target.click();
	}, actionText);
}

async function fillMinimalWebpageStrategyForm(page, strategyName) {
	const baseBox = page.locator(".box").nth(0);
	const strategyNameInput = page.getByPlaceholder("请输入策略名称");
	await expect(strategyNameInput).toBeVisible({ timeout: 20000 });
	await strategyNameInput.fill(strategyName);
	await baseBox.getByText("不限门店", { exact: true }).click();
	await selectElementOption(page, baseBox.locator(".el-select").first(), "客户新车交付后");
	await expect(baseBox).toContainText("策略将面向已完成首次触客的一销潜客");

	const step2Box = page.locator(".box").nth(1);
	await selectElementOption(page, step2Box.locator(".el-select").nth(0), "到达特定日期时间");
	await selectElementOption(page, step2Box.locator(".el-select").nth(1), null);

	const step3Box = page.locator(".box").nth(2);
	const branch = step3Box.locator(".branch-item-wrapper").first();
	await selectElementOption(page, branch.locator(".actions-item-wrapper .el-select").first(), "向客户群发送消息");
	await branch.getByText("网页", { exact: true }).click();
	await expect(branch.getByText("网页未设置", { exact: true })).toBeVisible();
	await branch.getByRole("button", { name: "编辑", exact: true }).click();

	const dialog = page.locator(".el-dialog__wrapper:visible").filter({ hasText: "编辑网页内容" }).last();
	await expect(dialog).toBeVisible();
	await dialog.getByPlaceholder("请输入网页标题").fill(`${strategyName}-网页`);
	await dialog.getByPlaceholder("请输入网页描述").fill("E2E网页描述");

	const uploadInput = dialog.locator("input[type='file']").last();
	await uploadInput.setInputFiles(IMAGE_FIXTURE);

	const materialItem = dialog.locator(".material-item-wrapper").first();
	await expect(materialItem).toBeVisible({ timeout: 120000 });
	await expect(dialog.locator(".page-config-wrapper")).not.toContainText("上传中", { timeout: 120000 });

	await dialog.getByRole("button", { name: "确定" }).click();
	await expect(dialog).toBeHidden({ timeout: 15000 });
	await expect(branch.getByText("网页已设置", { exact: true })).toBeVisible();
}

async function submitStrategy(page) {
	await page.getByRole("button", { name: "提交" }).click();
	await waitForSuccessMessage(page);
	await page.waitForURL(/#\/marketing-push-strategy$/);
	await waitForNetworkStable(page);
}

async function openFirstRecordDetail(page) {
	const row = await waitForStrategyRow(page, RECORD_DETAIL_STRATEGY_NAME, {
		attempts: 8,
		interval: 1500,
	});
	await clickRowAction(row, "执行记录");

	const recordDialogWrapper = page.locator(".el-dialog__wrapper").filter({ hasText: "查看执行记录" }).last();
	await expect(recordDialogWrapper).toBeVisible({ timeout: 15000 });
	await waitForNetworkStable(page);

	await expect(recordDialogWrapper).toContainText("查看策略详情", { timeout: 15000 });
	const visibleDialogCount = await page.locator(".el-dialog__wrapper:visible").count();
	const detailButton = recordDialogWrapper.locator("button:visible").filter({ hasText: "查看策略详情" }).first();
	await expect(detailButton).toBeVisible({ timeout: 15000 });
	await detailButton.click({ force: true });

	await expect(page.locator(".el-dialog__wrapper:visible")).toHaveCount(visibleDialogCount + 1, { timeout: 15000 });
	const detailDialog = page.locator(".el-dialog__wrapper:visible").filter({
		has: page.locator(".strategy-detail-dialog"),
	}).last();
	await expect(detailDialog).toBeVisible({ timeout: 15000 });
	await expect(detailDialog).toContainText("查看策略详情", { timeout: 15000 });
	await expect(detailDialog.locator(".strategy-detail-dialog")).toBeVisible({ timeout: 15000 });
	return { recordDialog: recordDialogWrapper, detailDialog };
}

test.describe.serial("营销推送策略 E2E", () => {
	let sharedPage;
	let createdStrategyName = "";
	let editedStrategyName = "";

	test.beforeAll(async ({ browser }) => {
		sharedPage = await createLoggedInPage(browser, {
			account: LOGIN_ACCOUNT,
			password: LOGIN_PASSWORD,
			timeout: 20000,
			navigationTimeout: 60000,
		});
		await sharedPage.waitForTimeout(500);
	});

	test.afterAll(async () => {
		await sharedPage.context().close();
	});

	test("应支持列表查询与重置", async () => {
		await gotoStrategyList(sharedPage);

		const searchInput = sharedPage.locator(".show-search input").first();
		await searchInput.fill("营销");
		await sharedPage.getByRole("button", { name: "查询" }).click();
		await waitForNetworkStable(sharedPage);

		await sharedPage.getByRole("button", { name: "重置" }).click();
		await waitForNetworkStable(sharedPage);
		await expect(searchInput).toHaveValue("");
	});

	test("应支持新增网页消息策略,并完成修改、启停和删除", async () => {
		test.slow();
		createdStrategyName = getUniqueStrategyName();
		editedStrategyName = `${createdStrategyName}-已编辑`;

		await gotoStrategyList(sharedPage);
		const metaResponsePromise = waitForMetaResponse(sharedPage);
		await sharedPage.getByText("新增策略", { exact: true }).click();
		await sharedPage.waitForURL(/#\/marketing-push-strategy\/modify\?editType=add/);
		await metaResponsePromise;
		await waitForModifyPageReady(sharedPage);

		await fillMinimalWebpageStrategyForm(sharedPage, createdStrategyName);
		await submitStrategy(sharedPage);

		await filterByStrategyName(sharedPage, createdStrategyName);
		const createdRow = await getStrategyRow(sharedPage, createdStrategyName);
		await expect(createdRow).toBeVisible();

		const editMetaResponsePromise = waitForMetaResponse(sharedPage);
		await clickRowAction(createdRow, "修改");
		await sharedPage.waitForURL(/#\/marketing-push-strategy\/modify\?editType=edit/);
		await editMetaResponsePromise;
		await waitForModifyPageReady(sharedPage);

		const baseBox = sharedPage.locator(".box").nth(0);
		await baseBox.locator("input").first().fill(editedStrategyName);
		await submitStrategy(sharedPage);

		const editedRow = await waitForStrategyRow(sharedPage, createdStrategyName, {
			attempts: 20,
			interval: 2500,
		});
		await expect(editedRow).toBeVisible();

		await editedRow.locator(".el-switch").click();
		await waitForSuccessMessage(sharedPage);
		await waitForNetworkStable(sharedPage);

		await filterByStrategyName(sharedPage, createdStrategyName);
		const rowAfterStatusChange = await getStrategyRow(sharedPage, createdStrategyName);
		await expect(rowAfterStatusChange).toBeVisible();
		const strategyNameForDelete = ((await rowAfterStatusChange.locator("td").nth(1).textContent()) || "").trim();

		await clickRowAction(rowAfterStatusChange, "删除");
		const confirmDialog = sharedPage.locator(".el-message-box:visible").last();
		await expect(confirmDialog).toBeVisible({ timeout: 10000 });
		await expect(confirmDialog).toContainText(`确定要删除策略"${strategyNameForDelete}"吗?`);
		await confirmDialog.getByRole("button", { name: "确定" }).click();
		await waitForSuccessMessage(sharedPage);
		await waitForNetworkStable(sharedPage);

		await filterByStrategyName(sharedPage, editedStrategyName);
		await expect(await getStrategyRow(sharedPage, editedStrategyName)).toHaveCount(0);
	});

	test("应支持查看执行记录与策略详情", async () => {
		test.slow();
		test.setTimeout(120000);
		await gotoStrategyList(sharedPage);
		await resetSearchForm(sharedPage);
		await filterByStrategyName(sharedPage, RECORD_DETAIL_STRATEGY_NAME);
		const { recordDialog, detailDialog } = await openFirstRecordDetail(sharedPage);

		await expect(recordDialog).toContainText("执行时间");
		await expect(recordDialog).toContainText("执行结果");
		await expect(recordDialog).toContainText("描述");

		await expect(detailDialog).toContainText("基础信息");
		await expect(detailDialog).toContainText("目标客户");
		await expect(detailDialog).toContainText("触发条件");
		await expect(detailDialog).toContainText("执行动作");

		await detailDialog.getByRole("button", { name: "关闭" }).click();
		await expect(detailDialog).toBeHidden({ timeout: 10000 });
		await recordDialog.getByRole("button", { name: "关闭" }).click();
		await expect(recordDialog).toBeHidden({ timeout: 10000 });
	});
});