提交“

This commit is contained in:
wuzilong committed 2026-10-19 18:28:02 +08:00
1 parent 5d9fb5ce19
commit 9177e1b7f1
231 files changed
+21207

No files matched your search

@@ -0,0 +1,162 @@
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import test from 'node:test'
import { runInNewContext } from 'node:vm'
import ts from 'typescript'
import { parse } from '@vue/compiler-sfc'
import { createSSRApp, h } from 'vue'
import { renderToString } from 'vue/server-renderer'
import { parseTime } from '../src/utils/format'
// 执行组件中的真实处理函数,只替换网络与弹窗边界,避免写入业务库。
function source(path: string) {
const file = readFileSync(new URL('../src/views/crm/' + path, import.meta.url), 'utf8')
return ts.createSourceFile(
path,
parse(file).descriptor.scriptSetup!.content,
ts.ScriptTarget.Latest,
true
)
}
function evaluate(code: string, context: Record<string, unknown>) {
return runInNewContext(
ts.transpileModule(code, {
compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.None }
}).outputText,
context
)
}
function handler(path: string, name: string, context: Record<string, unknown>) {
const file = source(path)
const statement = file.statements.find(
(s) =>
(ts.isFunctionDeclaration(s) && s.name?.text === name) ||
(ts.isVariableStatement(s) &&
s.declarationList.declarations.some((d) => d.name.getText(file) === name))
)
assert.ok(statement, `组件应保留 ${name} 处理入口`)
return evaluate(statement.getText(file) + '\n' + name, context)
}
for (const [path, name, api] of [
['customer/FollowFormDialog.vue', 'loadContactList', 'fetchContactByCustomerId'],
['customer/components/ContactList.vue', 'getList', 'fetchContactsByCustomerId']
]) {
test(`${path}:解析实际已解包联系人数组并兼容旧包装`, async () => {
const rows = [{ id: '90071992547409931', contactName: '联系人甲' }]
for (const response of [rows, { data: rows }, [], null]) {
const contactList = { value: [{ id: 'old' }] }
const load = handler(path, name, {
[api]: async () => response,
contactList,
props: { customerId: 'customer-1' },
loading: { value: false },
console
})
await load('customer-1')
assert.equal(
JSON.stringify(contactList.value),
JSON.stringify(
response === rows || (!Array.isArray(response) && response?.data) ? rows : []
)
)
}
})
test(`${path}:请求失败清空旧联系人`, async () => {
const contactList = { value: [{ id: 'old' }] }
const loading = { value: false }
const load = handler(path, name, {
[api]: async () => {
throw new Error('offline')
},
contactList,
props: { customerId: 'customer-1' },
loading,
console: { error() {} }
})
await load('customer-1')
assert.equal(contactList.value.length, 0)
assert.equal(loading.value, false)
})
}
test('操作日志各字段只能作为文本渲染,不能注入标签或事件', async () => {
const payload = '<img src=x onerror="alert(1)"></pre><script>alert(2)</script>&"\n第二行'
let message: any
let options: any
const show = handler('customer/CustomerDetailDialog.vue', 'handleViewLogDetail', {
h,
ElMessageBox: {
alert(content: unknown, _title: string, config: unknown) {
message = content
options = config
}
}
})
show(
Object.fromEntries(
['title', 'operName', 'operTime', 'operUrl', 'operParam'].map((k) => [k, payload])
)
)
const html =
typeof message === 'string' && options.dangerouslyUseHTMLString
? message
: await renderToString(createSSRApp({ render: () => message }))
assert.doesNotMatch(html, /<img|<script/i)
assert.equal((html.match(/&lt;img/g) || []).length, 5)
assert.ok(html.includes('第二行'))
assert.notEqual(options.dangerouslyUseHTMLString, true)
})
test('新增商机跟进默认时间使用本地时间,跨日不偏移;编辑不覆盖已有值', async () => {
const previousTZ = process.env.TZ
process.env.TZ = 'Asia/Shanghai'
try {
const file = source('opportunity/components/FollowDialog.vue')
const watcher = file.statements.find(
(s) =>
ts.isExpressionStatement(s) &&
ts.isCallExpression(s.expression) &&
s.expression.expression.getText(file) === 'watch'
)!
for (const instant of ['2026-10-17T20:01:01+08:00', '2026-10-17T00:01:01+08:00']) {
let callback: (open: boolean) => Promise<void>
const form = { value: {} as Record<string, unknown> }
const props: any = { opportunityId: '90071992547409931' }
evaluate(watcher.getText(file), {
watch: (_source: unknown, fn: typeof callback) => {
callback = fn
},
props,
form,
visible: { value: false },
attachmentUrls: { value: '' },
resetForm: () => {
form.value = {}
},
Date: class extends Date {
constructor() {
super(instant)
}
},
parseTime,
getOpportunityFollow: async () => ({
data: {
id: 'follow-1',
followTime: '2026-10-16 09:30:12',
nextTime: '2026-10-17 20:01:01'
}
})
})
await callback!(true)
assert.equal(form.value.followTime, instant.slice(0, 19).replace('T', ' '))
props.followData = { id: 'follow-1' }
await callback!(true)
assert.equal(form.value.followTime, '2026-10-16 09:30:12')
assert.equal(form.value.nextTime, '2026-10-17 20:01:01')
}
} finally {
if (previousTZ == null) delete process.env.TZ
else process.env.TZ = previousTZ
}
})
@@ -0,0 +1,73 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { readFile } from 'node:fs/promises'
import ts from 'typescript'
const root = new URL('../../', import.meta.url)
const read = (path) => readFile(new URL(path, root), 'utf8')
test('危化品证上传位于运输管理并复用现有 WebView 壳', async () => {
const source = await read('miniprogram/config/workbench-menus.js')
const { WORKBENCH_MODULES } = await import(`data:text/javascript,${encodeURIComponent(source)}`)
const transport = WORKBENCH_MODULES.find((m) => m.key === 'pl')
const entry = transport.menus.find((m) => m.code === 'pl-plan-cert-webview')
assert.ok(entry, '运输管理缺少危化品证上传入口')
assert.equal(entry.name, '危化品证上传')
assert.equal(entry.perms, 'mini:pl:plan-cert:list')
assert.equal(entry.enabled, true)
const api = await read('miniprogram/config/api.js')
const ast = ts.createSourceFile('api.js', api, ts.ScriptTarget.Latest, true)
let expression
function visit(node) {
if (ts.isPropertyAssignment(node) && node.name.getText(ast) === "'pl-plan-cert-webview'")
expression = node.initializer.getText(ast)
ts.forEachChild(node, visit)
}
visit(ast)
assert.ok(expression, '缺少工作台路由映射')
const path = new Function('PAGE_PATHS', `return ${expression}`)({
mpWebview: '/pages/common/mp-webview'
})
assert.equal(path, '/pages/common/mp-webview?path=%2Fm%2Fpl%2Fplan-cert')
})
test('H5 列表与详情均使用独立移动路由并隐藏桌面工作标签', async () => {
const source = await read('web-admin/src/router/routes/staticRoutes.ts')
const ast = ts.createSourceFile('routes.ts', source, ts.ScriptTarget.Latest, true)
const routes = new Map()
function visit(node) {
if (ts.isObjectLiteralExpression(node)) {
const pathProp = node.properties.find(
(prop) => ts.isPropertyAssignment(prop) && prop.name.getText(ast) === 'path'
)
if (pathProp && ts.isPropertyAssignment(pathProp) && ts.isStringLiteral(pathProp.initializer))
routes.set(pathProp.initializer.text, node)
}
ts.forEachChild(node, visit)
}
visit(ast)
const listRoute = routes.get('/m/pl/plan-cert')
const detailRoute = routes.get('/m/pl/plan-cert/:id')
assert.ok(listRoute, '缺少 /m/pl/plan-cert 路由')
assert.match(listRoute.getText(ast), /views\/m\/pl\/plan-cert\/index\.vue/)
assert.ok(detailRoute, '缺少 /m/pl/plan-cert/:id 独立详情路由')
assert.match(detailRoute.getText(ast), /views\/m\/pl\/plan-cert\/detail\.vue/)
for (const route of [listRoute, detailRoute]) {
assert.match(route.getText(ast), /isMpWebview:\s*true/)
assert.match(route.getText(ast), /isHideTab:\s*true/)
}
})
test('菜单 SQL 仅补移动入口与已有授权角色的完整祖先链', async () => {
const sql = await read('docs/sql/migrations/2026-10-17-mini-pl-plan-cert-webview-menus.sql')
assert.match(sql, /START TRANSACTION/i)
assert.match(sql, /COMMIT/i)
assert.match(sql, /mini:pl:plan-cert:list/)
assert.match(sql, /MINI_PL_ROOT/)
assert.match(sql, /parent_id\s*=\s*'1'/)
assert.match(sql, /EXISTS\s*\([\s\S]*m\.perms\s*=\s*'pl:plan-cert:list'[\s\S]*\)/)
assert.match(sql, /r\.tenant_no\s*=\s*'shanxia2.0'/)
assert.match(sql, /ON DUPLICATE KEY UPDATE/i)
assert.doesNotMatch(sql, /\b(?:DELETE|DROP|ALTER|TRUNCATE)\s/i)
assert.doesNotMatch(sql, /pl:plan-cert:(?:upload|ready)/)
})
@@ -0,0 +1,471 @@
// 浏览器测试的 API 边界替身;绝不向真实业务接口发请求。
const pdfObjects = [
'<< /Type /Catalog /Pages 2 0 R >>',
'<< /Type /Pages /Kids [3 0 R] /Count 1 >>',
'<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Resources << >> /Contents 4 0 R >>',
'<< /Length 0 >>\nstream\n\nendstream'
]
let pdfFixture = '%PDF-1.4\n'
const offsets = [0]
pdfObjects.forEach((obj, i) => {
offsets.push(Buffer.byteLength(pdfFixture))
pdfFixture += `${i + 1} 0 obj\n${obj}\nendobj\n`
})
const xref = Buffer.byteLength(pdfFixture)
pdfFixture += `xref\n0 5\n0000000000 65535 f \n${offsets
.slice(1)
.map((n) => `${String(n).padStart(10, '0')} 00000 n `)
.join('\n')}\ntrailer\n<< /Size 5 /Root 1 0 R >>\nstartxref\n${xref}\n%%EOF`
export function makePlan(index, overrides = {}) {
const id = `plan-${index}`
const toxic = {
id: `${id}-toxic`,
planId: id,
productId: 'toxic',
productNo: 'CP001',
productName: '测试易制毒产品',
brandName: '测试品牌',
aliasName: '测试别名',
model: '99%',
unit: 'ton',
quantity: 12,
actualQty: 11,
isToxic: 1,
isExplosive: 0,
purchaseCertUrl: '',
transportCertUrl: '',
legalUseCertUrl: ''
}
const explosive = {
...toxic,
id: `${id}-explosive`,
productId: 'explosive',
productNo: 'CP002',
productName: '测试易制爆产品',
isToxic: 0,
isExplosive: 1
}
const stopProducts = [toxic, explosive].map((p) => ({
...p,
id: `stop-${p.id}`,
planProductId: p.id,
planQty: 12,
inboundQty: 10,
outboundQty: 9,
contractId: 'contract-1',
contractNo: 'HT-001',
packageSpec: 'bulk',
remark: '产品备注'
}))
return {
id,
planNo: `YS${String(index).padStart(3, '0')}`,
planDate: '2026-10-17',
createDate: '2026-10-17',
createTime: '2026-10-17 09:15:00',
belongsCompany: 'shanxia',
planType: ['inbound', 'outbound', 'direct'][(index - 1) % 3],
followStatus: 'pending_arrange',
transportStatus: 'pending',
archiveStatus: 'pending',
completeStatus: 'pending',
hasFreight: 1,
freightAmount: 1234,
freightRemark: '测试运费说明',
totalAmount: 12345,
hazardCertReady: 0,
followUserName: '测试跟进人',
licensePlate: '鄂E12345',
trailerNo: '鄂E1234挂',
driverName: '测试司机',
escortName: '测试押运员',
personnelSummary: '司机:测试司机;押运:测试押运员',
deliveryTimes: ['2026-10-18 10:30:00', '2026-10-19 14:20:00'],
remark: '证书迁移测试备注',
products: [toxic, explosive],
documentAttachments: [{ url: '/fixtures/plan.pdf', label: '计划附件.pdf' }],
load: {
id: `${id}-load`,
customerName: '测试供应商',
address: '湖北省宜昌市装货地址',
loadTime: '2026-10-17 09:20:00',
contact: '张师傅 13800000000',
notes: '装货注意事项',
contracts: [{ contractId: 'contract-1', contractNo: 'HT-001' }],
products: stopProducts
},
deliveries: [1, 2].map((seq) => ({
id: `${id}-delivery-${seq}`,
seq,
customerName: `测试需方${seq}`,
address: `送货地址${seq}`,
deliveryTime: `2026-10-${17 + seq} 10:30:00`,
contact: '李师傅 13900000000',
notes: `送货注意事项${seq}`,
generateDibang: 0,
contracts: [{ contractId: 'contract-1', contractNo: 'HT-001' }],
products: stopProducts.map((p) => ({ ...p, id: `${p.id}-${seq}`, planQty: 6 }))
})),
...overrides
}
}
export async function installCertFixture(context) {
const state = {
plans: Array.from({ length: 24 }, (_, i) => makePlan(i + 1)),
codes: [
'mini:pl:plan-cert:list',
'pl:plan-cert:list',
'pl:plan-cert:upload',
'pl:plan-cert:ready'
],
calls: [],
unknown: [],
failList: false,
failSave: false,
failReadyIds: [],
uploadGate: null,
listDelay: null,
linkedListGate: null,
failPermissions: false
}
state.plans[3].archiveStatus = 'archived'
state.plans[4].followStatus = 'cancelled'
state.plans[5].hazardCertReady = 1
state.plans[6].transportStatus = 'arranged'
state.plans[6].followStatus = 'arranged'
state.plans[6].transportId = 'transport-7'
await context.addInitScript(() => {
window.__copiedText = ''
Object.defineProperty(navigator, 'clipboard', {
configurable: true,
value: {
writeText: async (text) => {
window.__copiedText = text
}
}
})
window.wx = {
miniProgram: {
navigateBack() {},
reLaunch() {},
getEnv(cb) {
cb({ miniprogram: true })
}
}
}
})
await context.route('**/fixtures/**', (route) =>
route.fulfill(
route.request().url().endsWith('.png')
? {
contentType: 'image/png',
body: Buffer.from(
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+cL1sAAAAASUVORK5CYII=',
'base64'
)
}
: { contentType: 'application/pdf', body: pdfFixture }
)
)
await context.route('https://api.qrserver.com/**', (route) =>
route.fulfill({
contentType: 'image/svg+xml',
body: '<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200"><rect width="200" height="200" fill="white"/><text x="10" y="100">Mock QR preview</text></svg>'
})
)
await context.route('**/api/**', async (route) => {
const request = route.request()
const url = new URL(request.url())
if (!url.pathname.startsWith('/api/')) return route.continue()
const path = url.pathname.slice(4)
const method = request.method()
let body = {}
try {
body = request.postDataJSON() || {}
} catch {
body = {}
}
const params = Object.fromEntries(url.searchParams)
state.calls.push({ path, method, body, params })
let data
let error = ''
if (path === '/web/auth/mp-webview-exchange') {
data = {
token: 'fixture-token',
refreshToken: 'fixture-refresh',
userInfo: {
id: 'user-1',
userId: 'user-1',
userName: '测试用户',
role: 'admin',
roles: ['admin']
}
}
} else if (path === '/web/auth/menu-codes') {
data = { all: false, isSuperAdmin: false, menuCodes: state.codes }
if (state.failPermissions) error = '权限加载失败'
} else if (path === '/web/admin/dict-data/all') {
data = {
crm_product_unit: [{ value: 'ton', label: '吨' }],
pl_package_spec: [{ value: 'bulk', label: '散装' }]
}
} else if (path === '/transport/plan/') {
if (params.contractId === 'contract-1' && state.linkedListGate) await state.linkedListGate
if (state.listDelay) await state.listDelay(params)
if (state.failList) {
state.failList = false
error = '列表测试失败'
}
let rows = state.plans
if (params.followStatus)
rows = rows.filter((p) => params.followStatus.split(',').includes(p.followStatus))
if (params.planType) rows = rows.filter((p) => p.planType === params.planType)
if (params.hazardCertReady !== undefined)
rows = rows.filter((p) => p.hazardCertReady === Number(params.hazardCertReady))
if (params.q)
rows = rows.filter(
(p) =>
p.planNo.includes(params.q) || p.products.some((x) => x.productName.includes(params.q))
)
if (params.certUploadStatus === 'incomplete')
rows = rows.filter((p) =>
p.products.some((x) =>
x.isToxic
? !(x.purchaseCertUrl && x.transportCertUrl)
: x.isExplosive && !x.legalUseCertUrl
)
)
const page = Number(params.page || 1),
size = Number(params.pageSize || 20)
data = {
list: rows.slice((page - 1) * size, page * size),
total: rows.length,
page,
pageSize: size
}
} else if (path === '/transport/plan/column-facet-values') {
const values = {
planNo: ['YS001'],
licensePlate: ['鄂E12345'],
productName: ['测试易制毒产品'],
productSpec: ['99%'],
productUnit: ['ton'],
loadCustomer: ['测试供应商'],
deliveryCustomer: ['测试需方1'],
productContract: ['HT-001']
}
data = {
list: (values[body.field] || []).map((value) => ({ value, label: value, count: 1 }))
}
} else if (/^\/transport\/plan\/plan-\d+$/.test(path)) {
data = state.plans.find((p) => p.id === path.split('/').pop())
} else if (/\/plan-\d+\/product-certs$/.test(path)) {
const plan = state.plans.find((p) => p.id === path.split('/')[3])
if (state.failSave) {
state.failSave = false
error = '证书保存测试失败'
} else
for (const item of body.products)
Object.assign(
plan.products.find((p) => p.id === item.id),
item
)
data = plan
} else if (/\/plan-\d+\/hazard-cert-ready$/.test(path)) {
const plan = state.plans.find((p) => p.id === path.split('/')[3])
if (state.failReadyIds.includes(plan.id)) error = '齐备测试失败'
else plan.hazardCertReady = body.ready ? 1 : 0
data = plan
} else if (/\/plan-\d+\/arrange-info$/.test(path)) {
data = {
driverUrl: 'https://example.test/driver',
licensePlate: '鄂E12345',
siteRecords: [
{
siteLinkId: 'site-1',
siteUrl: 'https://example.test/site',
planProductId: 'plan-7-toxic',
productName: '测试易制毒产品',
customerName: '测试需方1'
}
],
inventoryRecords: [
{
dbInventoryId: 'inventory-7',
dbPurchasePlanId: 'purchase-7',
planProductId: 'plan-7-toxic',
productName: '测试易制毒产品',
businessType: '入库'
}
]
}
} else if (path === '/transport/inbound/by-plan/plan-7') {
data = {
id: 'io-7',
kind: 'inbound',
orderNo: 'RK-007',
status: 'in_progress',
siteFeedbackRemark: '入库现场备注',
siteFeedbackTime: '2026-10-17 16:20:00',
siteFeedbackImages: ['/fixtures/inbound.pdf'],
products: []
}
} else if (path === '/transport/order/transport-7') {
data = {
id: 'transport-7',
transportNo: 'TR007',
licensePlate: '鄂E12345',
driverName: '测试司机',
driverPhone: '13800000000',
escortName: '测试押运员',
freightAmount: 1234,
freightPrice: 50,
freightType: 'by_weight',
transportQty: 24,
hasInvoice: 1,
distanceKm: 100,
unit: 'ton',
transportStatus: 'arranged',
approvalStatus: 'approved',
createTime: '2026-10-17 11:00:00',
feedbackTime: '2026-10-17 16:00:00',
feedbackQty: 23,
feedbackRemark: '司机回传测试备注',
feedbackImages: '["/fixtures/driver.pdf"]',
driverStopFeedbacks: [
{
stopType: 'load',
stopId: 'plan-7-load',
label: '装货',
customerName: '测试供应商',
quantity: 23,
remark: '司机装货回传',
feedbackTime: '2026-10-17 16:00:00',
attachmentUrls: ['/fixtures/driver.png'],
products: []
}
],
siteStopFeedbacks: [
{
stopType: 'delivery',
stopId: 'plan-7-delivery-1',
label: '送货',
customerName: '测试需方1',
quantity: 12,
remark: '现场送货回传',
feedbackTime: '2026-10-18 10:00:00',
attachmentUrls: ['/fixtures/site.pdf'],
products: []
}
]
}
} else if (path === '/transport/freight/by-transport/transport-7') {
data = null
} else if (path === '/inventory/inventory-7/related') {
data = {
plan: null,
weighing: {
id: 'weighing-7',
vehicleNo: '鄂E12345',
netWeight: 11,
grossWeight: 30,
tareWeight: 19,
grossWeightTime: '2026-10-17 15:30:00',
tareWeightTime: '2026-10-17 16:30:00',
supplier: '测试供应商',
consignee: '测试需方1',
remarks: '测试过磅备注'
}
}
} else if (path === '/inventory/inventory-7') {
data = {
id: 'inventory-7',
date: '2026-10-17',
vehicleNo: '鄂E12345',
partnerCompany: '测试供应商',
product: '测试易制毒产品',
quantity: 12,
businessType: '入库'
}
} else if (/^\/web\/crm\/contract\/approval\/flow\/contract-[12]$/.test(path)) {
data = []
} else if (/^\/web\/crm\/contract\/contract-[12]$/.test(path)) {
data = {
id: path.split('/').pop(),
contractNo: path.endsWith('contract-1') ? 'HT-001' : 'HT-002',
contractName: '危化品证书测试合同',
opportunityId: 'opportunity-1',
quoteId: 'quote-1',
contractType: 'sales',
customerName: '测试需方1',
supplierName: '测试供应商',
status: 'approved',
startDate: '2026-01-01',
endDate: '2026-12-31',
remark: '合同说明',
amount: 2400,
partyA: '测试甲方',
partyB: '测试乙方',
partyAAccount: '测试账号001',
contractFile: '[{"ossId":"/fixtures/contract.pdf","name":"合同原件.pdf"}]',
attachmentFiles: '[{"ossId":"/fixtures/extra.pdf","name":"其他附件.pdf"}]',
products: [
{
id: 'contract-product-1',
productId: 'toxic',
productName: '测试别名',
unit: 'ton',
quantity: 24,
price: 100,
subtotal: 2400
}
],
attachments: '/fixtures/contract.pdf'
}
} else if (path === '/web/crm/opportunity/detail') {
data = { id: 'opportunity-1', opportunityName: '测试关联商机' }
} else if (path === '/web/crm/quote/detail') {
data = { id: 'quote-1', quoteNo: 'BJ-001' }
} else if (path === '/web/crm/products/detail') {
data = {
id: body.id,
productName: body.id === 'toxic' ? '测试易制毒产品' : '测试易制爆产品',
aliases: [{ aliasName: '测试别名' }],
isToxic: body.id === 'toxic' ? 1 : 0,
isExplosive: body.id === 'explosive' ? 1 : 0
}
} else if (path === '/web/admin/attachment/preview-url') {
data = { previewUrl: params.fileUrl || body.fileUrl }
} else if (path === '/web/admin/attachment/download-url') {
data = { downloadUrl: params.fileUrl || body.fileUrl }
} else if (path === '/web/admin/attachment/upload') {
if (state.uploadGate) await state.uploadGate
data = {
id: 'file-1',
fileName: '测试证书.pdf',
fileUrl: '/fixtures/cert.pdf',
fileType: 'application/pdf'
}
} else {
state.unknown.push({ path, method, body, params })
error = `未定义测试接口:${method} ${path}`
}
if (error)
return route.fulfill({
status: 400,
contentType: 'application/json',
body: JSON.stringify({ code: 400, msg: error, detail: error })
})
// 运输 API 是 FastAPI 直出;Web API 使用 code=200 的信封。
await route.fulfill({
contentType: 'application/json',
body: JSON.stringify(
path.startsWith('/transport/') || path.startsWith('/inventory/')
? data
: { code: 200, msg: 'ok', data }
)
})
})
return state
}
@@ -0,0 +1,73 @@
import assert from 'node:assert/strict'
import { readFile } from 'node:fs/promises'
const root = new URL('../src/views/m/crm/contract/', import.meta.url)
const list = await readFile(new URL('MpContractList.vue', root), 'utf8')
const detail = await readFile(new URL('detail.vue', root), 'utf8')
assert.match(list, /<MpBusinessHeader/, '合同列表须用 MpBusinessHeader')
assert.match(list, /mp-contract-list/, '合同列表根节点须挂进绿头样式')
assert.match(list, /mp-customer-view-tabs/, '状态 Tab 须用绿头均分样式')
assert.match(list, /class="mp-customer-dd"/, '筛选行须复用透明白字下拉')
assert.match(list, /mp-wv-flat-card/, '合同列表须用扁平卡')
assert.match(list, /更多字段/, '合同卡须提供更多字段展开')
assert.match(list, /useIntersectionObserver/, '合同列表须滚动加载')
assert.match(list, /mp-wv-card-actions--single/, '单按钮卡片不得撑满整行')
assert.match(list, /van-date-picker/, '更多筛选日期须用 Vant 日期')
assert.match(list, /left-text="关闭"/, '筛选与审批弹层顶栏只保留关闭')
assert.match(list, /更多·已筛/, '更多条件须有已筛提示')
assert.doesNotMatch(list, /MpExpenseCard/, '合同列表不得再使用金额卡')
assert.doesNotMatch(list, /加载更多/, '合同列表不得使用加载更多按钮')
assert.doesNotMatch(list, /<el-select|<el-input/, '列表弹层不得露出 Element 输入控件')
assert.match(list, /mode === 'manage'/, 'Speed Dial 必须只在管理入口出现')
assert.match(list, /selectMode/, '合同列表必须保留多选模式')
assert.match(list, /mp-wv-batch-bar/, '合同列表必须保留选择后的批量底栏')
assert.match(
list,
/pendingApprovalUserId|buildContractListQuery/,
'审批入口必须保留当前用户待审批过滤'
)
assert.match(list, /approvedByUserId|buildContractListQuery/, '审批入口必须保留当前用户已审批过滤')
assert.match(list, /Promise\.allSettled/, '批量审批和作废必须保留部分成功统计')
assert.match(list, /fetchUserOptions/, '提交审批必须保留审批人选择')
assert.match(list, /requestSeq/, '列表必须忽略过期并发响应')
assert.match(list, /requestedPage = reset \? 1 : pageNum\.value \+ 1/, '分页必须成功后再提交页码')
assert.match(list, /onKeywordUpdate/, '搜索词从非空清空时必须自动刷新')
assert.match(list, /mp-wv-card-actions/, '待处理合同卡必须保留虚线操作栏')
assert.match(
list,
/v-if="cardActions\(card\)\.length"/,
'无操作按钮的合同卡必须隐藏空操作栏'
)
assert.doesNotMatch(list, /:has\(/, '不得依赖旧 WebView 不稳定的 :has 选择器')
assert.doesNotMatch(
list,
/from ['"](?:vue|vue-router|element-plus)['"]/,
'合同列表不得手工导入已配置 auto-import 的 Vue、Router 或 Element Plus API'
)
assert.match(detail, /title="合同详情"/, '详情顶栏必须使用固定标题')
assert.doesNotMatch(detail, /\{\{\s*headerTitle\s*\}\}/, '详情顶栏不得使用记录标题')
assert.doesNotMatch(detail, /mp-wv-header__sub/, '详情顶栏不得展示副标题')
assert.match(detail, /mp-contract-detail-tabs/, '详情必须提供业务 Tab')
assert.match(detail, /onAnchorTab/, '详情 Tab 须为锚点')
assert.match(detail, /--mp-h5-anchor-offset/, '详情锚点须避开吸顶 Tab')
assert.match(detail, /mp-h5-approve-sheet/, '通过/驳回须使用贴底审批弹层')
assert.match(detail, /left-text="关闭"/, '审批弹层顶栏只保留关闭')
assert.match(detail, /showCrmConfirmDialog/, '详情确认须走横排确认弹窗')
assert.match(detail, /kind: 'danger'/, '删除/作废须危险确认语义')
assert.match(detail, /别名/, '详情产品须含别名')
assert.doesNotMatch(detail, /v-if="activeTab ===/, '详情分区不得按 Tab 互斥隐藏')
assert.match(detail, /<MpApprovalTimeline/, '审批信息必须使用共用时间轴')
assert.match(detail, /<MpAttachmentGrid/, '附件必须使用 72×72 共用宫格')
assert.match(detail, /parseCrmAttachmentField/, '详情必须继续复用 CRM 附件解析工具链')
assert.match(detail, /fetchUploadAttachment/, '详情必须继续复用现有附件上传接口')
assert.match(detail, /uploadAttachments/, '详情必须保持现有合同附件保存接口')
assert.match(detail, /minStep/, '审批动作只能针对当前最小未决步骤')
assert.doesNotMatch(
detail,
/from ['"](?:vue|vue-router|element-plus)['"]/,
'合同详情不得手工导入已配置 auto-import 的 Vue、Router 或 Element Plus API'
)
console.log('contract DOM contract: PASS')
+548
View File
@@ -0,0 +1,548 @@
import assert from 'node:assert/strict'
import { mkdir } from 'node:fs/promises'
import { chromium } from 'playwright'
// 本地 H5 交互回归:所有接口均由 fixture 拦截,不写真实业务库。
const origin = process.env.CONTRACT_TEST_ORIGIN || 'http://localhost:3006'
const artifacts = '/tmp/shanxia-contract-e2e'
await mkdir(artifacts, { recursive: true })
const browser = await chromium.launch({ headless: true, channel: 'chrome' })
const context = await browser.newContext({
viewport: { width: 375, height: 812 },
isMobile: true,
deviceScaleFactor: 1
})
await context.addInitScript(() => {
const start = () => {
const root = document.documentElement
if (!root) return
const hide = () => {
const el = document.getElementById('__vue-devtools-container__')
if (el) el.style.setProperty('display', 'none', 'important')
}
hide()
new MutationObserver(hide).observe(root, { childList: true, subtree: true })
}
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', start)
else start()
})
const page = await context.newPage()
page.setDefaultTimeout(7000)
const pageErrors = []
const calls = []
page.on('pageerror', (error) => pageErrors.push(error.message))
const baseContract = {
id: 'contract-1',
contractNo: 'HT-20261017-001',
contractName: '年度化工原料销售合同',
customerId: 'customer-1',
customerName: '宜昌测试客户',
contactName: '张经理',
contactMobile: '13800138000',
contractType: 'sale',
amount: 128600,
freight: 500,
barrelDeposit: 1000,
amountWithTax: 130100,
signDate: '2026-10-17',
startDate: '2026-10-18',
endDate: '2027-10-17',
ownerUserId: 'user-1',
ownerUserName: '测试销售',
status: 'draft',
canApprove: true,
partyA: '宜昌测试客户',
partyAContact: '张经理',
partyAMobile: '13800138000',
partyB: '山峡化工',
partyBContact: '李经理',
partyBMobile: '13900139000',
paymentTerms: '月结 30 天',
deliveryTerms: '送货上门',
contractTerms: '按约定履行',
attachmentFiles: JSON.stringify([{ ossId: '/fixtures/合同扫描件.pdf', category: 'scan' }]),
remark: 'fixture 合同',
createBy: 'user-1',
createTime: '2026-10-17 09:00:00',
products: [
{
id: 'line-1',
standardProductName: '工业甲醇',
quantity: 10,
unit: '吨',
unitPrice: 12000,
amount: 120000
}
]
}
const contracts = [
baseContract,
{
...baseContract,
id: 'contract-2',
contractNo: 'HT-20261017-002',
contractName: '已审批合同',
status: 'approved',
canApprove: false
},
{
...baseContract,
id: 'contract-fail',
contractNo: 'HT-20261017-003',
contractName: '审批失败样本',
status: 'approving',
canApprove: true
}
]
let approvals = [
{
id: 'approval-1',
contractId: baseContract.id,
step: 1,
approverId: 'user-before',
approverName: '前置审批人',
approvalResult: 'pending',
approvalOpinion: '',
createTime: '2026-10-17 10:00:00'
},
{
id: 'approval-2',
contractId: baseContract.id,
step: 2,
approverId: 'user-1',
approverName: '测试审批人',
approvalResult: 'pending',
approvalOpinion: '',
createTime: '2026-10-17 10:30:00'
}
]
let approvalEntry = false
let forbiddenMode = ''
const dict = {
crm_contract_status: [
{ value: 'draft', label: '草稿', tagType: 'info' },
{ value: 'approving', label: '待审批', tagType: 'warning' },
{ value: 'approved', label: '已审批', tagType: 'success' },
{ value: 'invalid', label: '已作废', tagType: 'danger' }
],
crm_contract_type: [
{ value: 'sale', label: '销售合同', tagType: 'primary' },
{ value: 'purchase', label: '采购合同', tagType: 'info' }
]
}
await context.addInitScript(() => {
window.wx = {
miniProgram: {
navigateBack() {},
reLaunch() {},
getEnv(callback) {
callback({ miniprogram: true })
}
}
}
})
await context.route('**/api/**', async (route) => {
const request = route.request()
const url = new URL(request.url())
if (!url.pathname.startsWith('/api/')) return route.continue()
const path = url.pathname.replace(/^\/api/, '')
let body = Object.fromEntries(url.searchParams)
try {
body = { ...body, ...(request.postDataJSON() || {}) }
} catch {
// multipart 上传不参与 body 精确断言。
}
calls.push({ path, body })
let data = {}
let code = 200
let msg = 'ok'
if (path === '/web/auth/mp-webview-exchange') {
const ticket = String(body.ticket || '')
approvalEntry = ticket.includes('approve')
forbiddenMode = ticket.includes('forbidden-list')
? 'list'
: ticket.includes('forbidden-detail')
? 'detail'
: ''
data = {
token: 'fixture-token',
refreshToken: 'fixture-refresh',
userInfo: {
id: 'user-1',
userId: 'user-1',
userName: '测试用户',
role: 'admin',
roles: ['admin']
}
}
} else if (path === '/web/admin/dict-data/all') {
data = dict
} else if (path === '/web/admin/users/options') {
data = [{ value: 'user-1', label: '测试审批人', userNo: 'approver' }]
} else if (path === '/web/crm/contract/list') {
if (forbiddenMode === 'list') {
code = 403
msg = '无权限访问合同列表'
} else {
const list = body.approvedByUserId
? contracts.filter((item) => item.status === 'approved')
: approvalEntry
? contracts.map((item) => ({
...item,
status: item.id === 'contract-2' ? 'approved' : 'approving'
}))
: contracts
data = { list, total: list.length }
}
} else if (/^\/web\/crm\/contract\/contract-(?:1|2|fail)$/.test(path)) {
if (forbiddenMode === 'detail') {
code = 403
msg = '无权限访问合同详情'
} else {
const id = decodeURIComponent(path.split('/').pop())
const row = contracts.find((item) => item.id === id) || baseContract
data = {
...row,
status: approvalEntry
? approvals.some((item) => item.approvalResult === 'pending')
? 'approving'
: 'approved'
: row.status
}
}
} else if (/^\/web\/crm\/contract\/approval\/flow\//.test(path)) {
data = { list: approvals }
} else if (path === '/web/crm/contract-approver-setting/get') {
data = { approverIds: ['user-1'], status: '0' }
} else if (path === '/web/crm/contract/batchSubmitApproval') {
data = body.ids?.length || 0
} else if (path === '/web/crm/contract/approval') {
if (body.id === 'contract-fail') {
await route.abort('failed')
return
} else {
approvals = approvals.map((item) => ({
...item,
approvalResult: body.approvalResult,
approvalOpinion: body.approvalOpinion,
approvalTime: '2026-10-17 11:00:00'
}))
data = true
}
} else if (path === '/web/admin/attachment/upload') {
data = { id: 'upload-1', fileName: '补充扫描件.png', fileUrl: '/fixtures/补充扫描件.png' }
} else if (path === '/web/crm/contract/uploadAttachments') {
data = true
} else if (path === '/web/crm/contract/invalid') {
data = true
}
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ code, msg, data })
})
})
const click = (name) =>
page
.getByRole('button', { name, exact: true })
.or(page.getByRole('tab', { name, exact: true }))
.filter({ visible: true })
.first()
.click()
const lastCall = (path) => calls.findLast((item) => item.path === path)
async function assertNoOverflow(width) {
await page.setViewportSize({ width, height: 812 })
assert.equal(
await page.evaluate(() => document.documentElement.scrollWidth > innerWidth),
false,
`页面在 ${width}px 不应横向溢出`
)
}
function boxesOverlap(a, b) {
return !(
a.x + a.width <= b.x ||
b.x + b.width <= a.x ||
a.y + a.height <= b.y ||
b.y + b.height <= a.y
)
}
try {
await page.goto(`${origin}/#/m/crm/contract?mpTicket=contract-forbidden-list`)
await page.getByText('无权限', { exact: true }).waitFor()
await page.goto(
`${origin}/#/m/crm/contract/contract-1?from=manage&mpTicket=contract-forbidden-detail`
)
await page.locator('.mp-wv-empty').getByText('无权限访问合同详情', { exact: true }).waitFor()
await page.goto(`${origin}/#/m/crm/contract?mpTicket=contract-manage-fixture`)
await page.getByRole('heading', { name: '合同管理', exact: true }).waitFor()
await page.getByRole('button', { name: `查看合同:${baseContract.contractName}` }).waitFor()
const listOrder = await Promise.all(
['.mp-wv-header', '.mp-customer-view-tabs', '.mp-customer-dd', '.mp-wv-flat-card'].map(
async (selector) => (await page.locator(selector).first().boundingBox())?.y ?? -1
)
)
assert.deepEqual(
[...listOrder].sort((a, b) => a - b),
listOrder
)
assert.equal(await page.locator('.mp-customer-dd .van-dropdown-menu__item').count(), 3)
assert.equal(await page.locator('.mp-wv-speed-dial').count(), 1)
const manageCards = page.locator('.mp-wv-flat-card')
assert.equal(await manageCards.nth(0).locator('.mp-wv-card-actions').isVisible(), true)
assert.equal(await manageCards.nth(1).locator('.mp-wv-card-actions').count(), 0)
assert.equal(await manageCards.nth(2).locator('.mp-wv-card-actions').count(), 0)
await page.locator('.van-dropdown-menu__title', { hasText: '全部类型' }).click()
await Promise.all([
page.waitForResponse((response) =>
new URL(response.url()).pathname.endsWith('/web/crm/contract/list')
),
page.locator('.van-dropdown-item__option', { hasText: '销售合同' }).first().click()
])
assert.equal(lastCall('/web/crm/contract/list').body.contractType, 'sale')
await page.locator('.van-dropdown-menu__title', { hasText: '更多' }).click()
const filterSheet = page.getByRole('dialog').filter({ hasText: '更多筛选' })
await filterSheet.waitFor()
await filterSheet.locator('input[type="search"]').fill('年度')
await filterSheet.getByText('签订日起', { exact: true }).click()
await page.locator('.van-picker__confirm').click()
await filterSheet.getByText('签订日止', { exact: true }).click()
await page.locator('.van-picker__confirm').click()
await filterSheet.locator('.van-field').filter({ hasText: '金额最低' }).locator('input').fill('100')
await filterSheet.locator('.van-field').filter({ hasText: '金额最高' }).locator('input').fill('200000')
await Promise.all([
page.waitForResponse((response) =>
new URL(response.url()).pathname.endsWith('/web/crm/contract/list')
),
filterSheet.getByRole('button', { name: '确定', exact: true }).click()
])
const moreBody = lastCall('/web/crm/contract/list').body
assert.equal(moreBody.keyword, '年度')
assert.match(moreBody.signDateBegin, /^\d{4}-\d{2}-\d{2}$/)
assert.match(moreBody.signDateEnd, /^\d{4}-\d{2}-\d{2}$/)
assert.equal(Number(moreBody.minAmount), 100)
assert.equal(Number(moreBody.maxAmount), 200000)
const searchInput = page.getByRole('searchbox', { name: '搜索合同' })
await Promise.all([
page.waitForResponse((response) =>
new URL(response.url()).pathname.endsWith('/web/crm/contract/list')
),
searchInput.fill('')
])
assert.equal('keyword' in lastCall('/web/crm/contract/list').body, false)
await click('多选')
assert.ok(await page.locator('.mp-wv-batch-bar').isVisible())
const selectors = page.locator('.expense-card__select')
await selectors.nth(0).click()
await selectors.nth(1).click()
await click('提交审批')
const submitSheet = page.getByRole('dialog').filter({ hasText: '提交审批' })
await submitSheet.waitFor()
assert.ok(await submitSheet.getByText('已跳过 1 条非草稿', { exact: false }).isVisible())
await Promise.all([
page.waitForResponse((response) =>
response.url().endsWith('/web/crm/contract/batchSubmitApproval')
),
submitSheet.getByRole('button', { name: '确认提交', exact: true }).click()
])
assert.deepEqual(lastCall('/web/crm/contract/batchSubmitApproval').body.ids, ['contract-1'])
const submitSuccess = page.getByText('成功提交 1 条,跳过 1 条', { exact: true })
await submitSuccess.waitFor()
await submitSuccess.waitFor({ state: 'hidden' })
await click('快捷操作')
assert.ok(await page.getByRole('button', { name: '新增合同', exact: true }).isVisible())
await click('快捷操作')
await page.screenshot({ path: `${artifacts}/manage-list-375.png`, fullPage: true })
await assertNoOverflow(375)
const manageDetailUrl = `${origin}/#/m/crm/contract/contract-1?from=manage&mpTicket=contract-manage-direct`
const detailCallsBefore = calls.filter(
(item) => item.path === '/web/crm/contract/contract-1'
).length
await page.goto(manageDetailUrl)
await page.getByRole('heading', { name: '合同详情', exact: true }).waitFor()
await page.reload()
await page.getByRole('heading', { name: '合同详情', exact: true }).waitFor()
assert.ok(
calls.filter((item) => item.path === '/web/crm/contract/contract-1').length >=
detailCallsBefore + 2
)
assert.equal(await page.locator('.mp-wv-header').getByText(baseContract.contractName).count(), 0)
assert.equal(await page.locator('.mp-wv-header__sub').count(), 0)
assert.ok(await page.getByRole('button', { name: '提交审批', exact: true }).isVisible())
assert.ok(await page.getByRole('button', { name: '编辑', exact: true }).isVisible())
assert.equal(await page.getByRole('button', { name: '通过', exact: true }).count(), 0)
await click('产品明细')
await page.getByText('工业甲醇', { exact: true }).waitFor()
await click('审批信息')
await page.locator('.mp-crm-approval-timeline').waitFor()
await click('附件')
const attachment = page.locator('.mp-crm-att-grid .att-item').first()
const attachmentBox = await attachment.boundingBox()
assert.equal(Math.round(attachmentBox?.width || 0), 72)
assert.equal(Math.round(attachmentBox?.height || 0), 72)
const previewBox = await attachment.locator('.att-preview').boundingBox()
const removeBox = await attachment.locator('.att-remove').boundingBox()
const addBox = await page.locator('.mp-crm-att-grid .att-add').boundingBox()
const attachmentGeometry = { attachmentBox, previewBox, removeBox, addBox }
console.log(`contract attachment geometry: ${JSON.stringify(attachmentGeometry)}`)
assert.equal(
Math.round(previewBox?.width || 0),
72,
`附件预览宽度必须为 72px:${JSON.stringify(previewBox)}`
)
assert.equal(
Math.round(previewBox?.height || 0),
72,
`附件预览高度必须为 72px:${JSON.stringify(previewBox)}`
)
assert.ok(
(removeBox?.width || 0) >= 44 && (removeBox?.height || 0) >= 44,
`删除附件命中区必须不小于 44px:${JSON.stringify(removeBox)}`
)
assert.ok(
(addBox?.width || 0) >= 44 && (addBox?.height || 0) >= 44,
`添加附件命中区必须不小于 44px:${JSON.stringify(addBox)}`
)
assert.equal(
boxesOverlap(removeBox, addBox),
false,
`删除与添加命中区不得重叠:${JSON.stringify({ removeBox, addBox })}`
)
await page.screenshot({ path: `${artifacts}/manage-detail-375.png`, fullPage: true })
await click('更多')
const uploadScan = page.getByRole('button', { name: '上传扫描件', exact: true })
await uploadScan.waitFor()
const uploadScanBox = await uploadScan.boundingBox()
assert.ok(uploadScanBox.y >= 0 && uploadScanBox.y + uploadScanBox.height <= 812)
await uploadScan.click()
await page.locator('input[type="file"]').setInputFiles({
name: '补充扫描件.png',
mimeType: 'image/png',
buffer: Buffer.from('fixture')
})
await page.waitForResponse((response) =>
response.url().endsWith('/web/crm/contract/uploadAttachments')
)
assert.equal(lastCall('/web/crm/contract/uploadAttachments').body.id, 'contract-1')
assert.equal(lastCall('/web/crm/contract/uploadAttachments').body.attachments.length, 2)
await page.goto(`${origin}/#/m/crm/contract/approval?mpTicket=contract-approve-fixture`)
await page.getByRole('heading', { name: '合同审批', exact: true }).waitFor()
await page.getByRole('button', { name: `查看合同:${baseContract.contractName}` }).waitFor()
assert.equal(await page.locator('.mp-wv-speed-dial').count(), 0)
assert.equal(lastCall('/web/crm/contract/list').body.pendingApprovalUserId, 'user-1')
const approveCards = page.locator('.mp-wv-flat-card')
assert.equal(await approveCards.nth(0).locator('.mp-wv-card-actions').isVisible(), true)
assert.equal(await approveCards.nth(1).locator('.mp-wv-card-actions').count(), 0)
assert.equal(await approveCards.nth(2).locator('.mp-wv-card-actions').isVisible(), true)
await click('多选')
const approveSelectors = page.locator('.expense-card__select')
await approveSelectors.nth(0).click()
await approveSelectors.nth(1).click()
await approveSelectors.nth(2).click()
await click('通过')
const batchApproveSheet = page.getByRole('dialog').filter({ hasText: '批量通过' })
await batchApproveSheet.waitFor()
assert.ok(await batchApproveSheet.getByText('已跳过 1 条不可审批', { exact: false }).isVisible())
await batchApproveSheet.getByRole('button', { name: '确认通过', exact: true }).click()
await page.waitForTimeout(100)
const partialMessages = await page.locator('.el-message').allTextContents()
assert.ok(
partialMessages.some((text) => text.includes('成功通过 1 条,失败 1 条,跳过 1 条')),
`批量部分成功提示缺失:${partialMessages.join(' | ')}`
)
assert.equal(calls.filter((item) => item.path === '/web/crm/contract/approval').length, 2)
assert.equal(await page.locator('.mp-wv-batch-bar').count(), 0)
await page.waitForFunction(() => document.querySelectorAll('.el-message').length === 0)
approvals = approvals.map((item) => ({
...item,
approvalResult: 'pending',
approvalOpinion: '',
approvalTime: ''
}))
await page.goto(
`${origin}/#/m/crm/contract/contract-1?from=approve&mpTicket=contract-approve-direct`
)
await page.getByRole('heading', { name: '合同详情', exact: true }).waitFor()
assert.match(page.url(), /from=approve/)
assert.equal(await page.getByRole('button', { name: '通过', exact: true }).count(), 0)
assert.equal(await page.getByRole('button', { name: '驳回', exact: true }).count(), 0)
assert.equal(await page.getByRole('button', { name: '提交审批', exact: true }).count(), 0)
assert.equal(await page.getByRole('button', { name: '编辑', exact: true }).count(), 0)
approvals[0] = {
...approvals[0],
approvalResult: 'approved',
approvalOpinion: '前置审批已通过',
approvalTime: '2026-10-17 10:20:00'
}
await page.reload()
await page.getByRole('button', { name: '通过', exact: true }).waitFor()
assert.ok(await page.getByRole('button', { name: '驳回', exact: true }).isVisible())
assert.equal(await page.getByRole('button', { name: '提交审批', exact: true }).count(), 0)
assert.equal(await page.getByRole('button', { name: '编辑', exact: true }).count(), 0)
await click('通过')
const approveSheet = page.getByRole('dialog').filter({ hasText: '通过合同' })
await approveSheet.waitFor()
await approveSheet.getByRole('button', { name: '确认通过', exact: true }).click()
const confirmDialog = page.locator('.van-dialog').filter({ hasText: '确认要通过该合同吗?' })
await confirmDialog.getByRole('button', { name: '确认', exact: true }).click()
await confirmDialog.waitFor({ state: 'hidden' })
assert.equal(lastCall('/web/crm/contract/approval').body.id, 'contract-1')
assert.equal(lastCall('/web/crm/contract/approval').body.approvalResult, 'approved')
await page.waitForFunction(() => document.querySelectorAll('.el-message').length === 0)
await assertNoOverflow(414)
await page.screenshot({ path: `${artifacts}/approve-detail-414.png`, fullPage: true })
await page.getByRole('button', { name: '返回合同审批', exact: true }).click()
await page.getByRole('heading', { name: '合同审批', exact: true }).waitFor()
await Promise.all([
page.waitForResponse((response) =>
new URL(response.url()).pathname.endsWith('/web/crm/contract/list')
),
click('已审批')
])
assert.equal(lastCall('/web/crm/contract/list').body.approvedByUserId, 'user-1')
await page.screenshot({ path: `${artifacts}/approve-list-414.png`, fullPage: true })
assert.deepEqual(pageErrors, [])
console.log(
JSON.stringify({
result: 'PASS',
assertions:
'管理/审批列表骨架、真实筛选、金额卡、动作栏显隐、Speed Dial差异、多选批量底栏、批量提交、批量审批部分成功、详情直达/刷新、列表与详情403、两步审批门禁、入口权限差异、固定详情头、Tab、时间轴、72px附件与不重叠命中区、附件上传、单条审批、375/414布局',
apiCalls: calls.length,
screenshots: artifacts
})
)
} catch (error) {
await page.screenshot({ path: `${artifacts}/failure.png`, fullPage: true })
console.error(await page.locator('body').innerText())
console.error('Page errors:', pageErrors)
console.error('API calls:', calls)
throw error
} finally {
await browser.close()
}
@@ -0,0 +1,78 @@
import assert from 'node:assert/strict'
import { readFile } from 'node:fs/promises'
const root = new URL('../src/views/m/crm/customer/', import.meta.url)
const [list, detail, filters, attachments, fields, styles] = await Promise.all([
readFile(new URL('index.vue', root), 'utf8'),
readFile(new URL('detail.vue', root), 'utf8'),
readFile(new URL('CustomerFilters.vue', root), 'utf8'),
readFile(new URL('CustomerAttachments.vue', root), 'utf8'),
readFile(new URL('CustomerFields.vue', root), 'utf8'),
readFile(new URL('customer.scss', root), 'utf8')
])
for (const component of [
'MpBusinessHeader',
'MpStatusTabs',
'MpThreeColumnFilters',
'MpExpenseCard'
]) {
assert.match(list, new RegExp(`<${component}\\b`), `客户列表应使用 ${component}`)
}
const headerAt = list.indexOf('<MpBusinessHeader')
const tabsAt = list.indexOf('<MpStatusTabs')
const filtersAt = list.indexOf('<MpThreeColumnFilters')
const cardAt = list.indexOf('<MpExpenseCard')
assert.ok(headerAt >= 0 && headerAt < tabsAt && tabsAt < filtersAt && filtersAt < cardAt)
assert.doesNotMatch(
list,
/class="mp-customer-actions"[\s\S]*+ 新增[\s\S]*筛选[\s\S]*显示[\s\S]*刷新/
)
assert.match(list, /class="mp-wv-speed-dial"/)
assert.match(list, /class="mp-customer-batch-bar"/)
assert.match(list, /requestSnapshot/)
assert.match(list, /onKeywordUpdate/)
assert.match(list, /customerTypeIn/)
assert.match(list, /levelIn/)
assert.match(list, /:show-actions="!selectMode"/, '选择模式必须隐藏卡片动作栏')
assert.match(list, /rows\.value = \[\]/, 'reset 请求必须先清空旧列表')
assert.match(list, /total\.value = 0/, 'reset 请求必须先清空旧总数')
assert.match(list, /selected\.value = \[\]/, 'reset 请求必须先清空旧选择')
assert.match(list, /customerCardTime\(row\)/, '客户卡时间必须支持 lastTime/createTime 回退')
assert.match(detail, /<MpBusinessHeader\s+title="客户详情"/)
assert.doesNotMatch(detail, /mp-wv-header__sub/)
for (const label of ['资料', '跟进记录', '联系人', '商机', '合同', '开票信息', '操作日志']) {
assert.ok(detail.includes(label), `详情应保留 ${label} Tab`)
}
assert.match(detail, /mp-customer-detail-tabs/)
assert.match(detail, /watch\(/, '详情必须监听复用路由变化')
assert.match(detail, /route\.params\.id/, '详情必须监听客户 ID')
assert.match(detail, /route\.query\.tab/, '详情必须监听 query tab')
assert.match(detail, /requestSeq/, '详情必须隔离过期请求')
assert.match(detail, /requestedId/, '详情应用响应前必须核对请求客户 ID')
assert.match(filters, />关键词</, 'More 面板必须展示并回写顶部关键词')
assert.match(filters, />业务视图</, 'More 面板必须展示四个业务视图')
assert.match(filters, /keyword:\s*keyword\.trim\(\)/, 'facet 请求必须传递服务端关键词')
assert.match(filters, /facets\.value = \{\}/, '筛选上下文变化必须清空 facet')
assert.match(filters, /facetContextVersion/, '筛选上下文变化必须隔离旧 facet 响应')
assert.match(attachments, /<MpAttachmentGrid\b/)
assert.match(attachments, /type="file"/)
assert.match(attachments, /:disabled="uploading > 0"/, '上传期间必须禁止再次选择文件')
assert.match(attachments, /if \(uploading\.value > 0\)/, '上传处理器必须拒绝并发选择')
assert.match(
attachments,
/existing\.push\(url\)[\s\S]*emit\('update:modelValue', existing\.join\(','\)\)/,
'每个文件成功后必须立即保留并提交引用'
)
assert.match(attachments, /ElMessage\.error\(/, '后续文件上传失败必须给出反馈')
assert.doesNotMatch(fields, /<el-tag\b/, 'WebView 详情字典与状态不得使用桌面深色标签')
assert.match(fields, /mp-customer-webview-tag/, 'WebView 详情字典与状态必须使用浅底标签')
assert.match(styles, /\.mp-customer-batch-bar/)
assert.match(styles, /min-height:\s*44px/)
assert.match(styles, /\.mp-customer-webview-tag/)
console.log('customer DOM contract: PASS')
+946
View File
@@ -0,0 +1,946 @@
import { chromium } from 'playwright'
import assert from 'node:assert/strict'
import { mkdir } from 'node:fs/promises'
// 本地 H5 交互回归:所有 API 均由 fixture 拦截,不写真实业务库。
const origin = process.env.CUSTOMER_TEST_ORIGIN || 'http://localhost:3006'
const artifacts = '/tmp/shanxia-customer-e2e'
await mkdir(artifacts, { recursive: true })
const browser = await chromium.launch({ headless: true, channel: 'chrome' })
const context = await browser.newContext({
viewport: { width: 375, height: 812 },
isMobile: true,
deviceScaleFactor: 1
})
const page = await context.newPage()
const pageErrors = []
page.on('pageerror', (error) => pageErrors.push(error.message))
const calls = []
const customers = [
{
id: '90071992547409931',
customerNo: 'KH001',
customerName: '山峡化工测试客户',
shortName: '山峡',
customerType: 'company',
level: 'normal',
status: 'normal',
dealStatus: 'undeal',
mobile: '13800138000',
source: 'phone',
parkArea: '园区A',
province: '湖北',
city: '宜昌',
district: '西陵',
ownerUserId: 'user-1',
ownerUserName: '测试用户',
createBy: 'user-1',
createTime: '2026-10-17 09:00:00',
businessLicenseImages: '',
businessPermitImages: '',
otherCertImages: ''
}
]
const page2Customer = {
...customers[0],
id: 'customer-page-2',
customerNo: 'KH-P2',
customerName: '分页客户'
}
const secondCustomer = {
...customers[0],
id: 'customer-fast-b',
customerNo: 'KH-B',
customerName: '快速客户B',
shortName: '客户B'
}
let contacts = [
{
id: 'contact-1',
customerId: customers[0].id,
contactName: '张经理',
mobile: '13800138001',
role: 'decision',
status: 'active',
isPrimary: 0,
isKey: 1,
createBy: 'user-1'
}
]
let follows = []
let invoices = []
const opportunity = {
id: 'opp-1',
opportunityName: '测试商机',
customerId: customers[0].id,
customerName: customers[0].customerName,
amount: 123,
status: 'following',
stage: 'initial',
stagePercent: 10,
winRate: 30,
ownerUserId: 'user-1',
createBy: 'user-1'
}
let opportunityFollows = []
let failInvoice = false
let failList = false
let failNextPage2 = false
let delayNextPage2 = false
let delayedDetailId = ''
let forbiddenMode = ''
let uploadGate = null
let signalUploadStarted = null
let uploadQueue = []
const dict = Object.fromEntries(
Object.entries({
crm_customer_type: ['company', '企业'],
crm_customer_level: ['normal', '普通'],
crm_clue_source: ['phone', '电话'],
crm_customer_park: ['园区A', '园区A'],
crm_follow_type: ['phone', '电话'],
crm_customer_status: ['normal', '正常'],
crm_deal_status: ['undeal', '未成交'],
crm_contact_role: ['decision', '决策人']
}).map(([key, [value, label]]) => [key, [{ value, label, tagType: 'success' }]])
)
dict.crm_customer_type.push({ value: 'person', label: '个人', tagType: 'info' })
dict.crm_customer_level.push({ value: 'key', label: '重点', tagType: 'warning' })
dict.crm_opportunity_stage = [
{ value: 'initial', label: '初步' },
{ value: 'quote', label: '报价' }
]
await context.addInitScript(() => {
window.wx = {
miniProgram: {
navigateBack() {},
reLaunch() {},
getEnv(cb) {
cb({ miniprogram: true })
}
}
}
})
await context.route('**/api/**', async (route) => {
const request = route.request()
if (!new URL(request.url()).pathname.startsWith('/api/')) return route.continue()
const path = new URL(request.url()).pathname.replace(/^\/api/, '')
let body = {}
try {
body = request.postDataJSON() || {}
} catch {
body = {}
}
calls.push({ path, body })
let data = {}
let code = 200
let msg = 'ok'
if (path === '/web/auth/mp-webview-exchange') {
const ticket = String(body.ticket || '')
forbiddenMode = ticket.includes('forbidden-list')
? 'list'
: ticket.includes('forbidden-detail')
? 'detail'
: ''
data = {
token: 'fixture-token',
refreshToken: 'fixture-refresh',
userInfo: {
id: 'user-1',
userId: 'user-1',
userName: '测试用户',
role: 'admin',
roles: ['admin']
}
}
} else if (path === '/web/admin/dict-data/all') data = dict
else if (path === '/web/auth/current-user')
data = { id: 'user-1', userId: 'user-1', userName: '测试用户' }
else if (path === '/web/auth/menu-codes') data = []
else if (path === '/web/admin/menu-favorites') data = []
else if (path === '/web/admin/users/options') data = [{ value: 'user-1', label: '测试用户' }]
else if (/\/customer\/(list|mine|toFollow|key)$/.test(path)) {
if (forbiddenMode === 'list') {
code = 403
msg = '无权限访问客户列表'
} else if (failList) {
code = 500
msg = '列表测试失败'
failList = false
} else if (Number(body.page) === 2) {
if (failNextPage2) {
code = 500
msg = '分页测试失败'
failNextPage2 = false
} else {
if (delayNextPage2) {
delayNextPage2 = false
await new Promise((resolve) => setTimeout(resolve, 500))
}
data = { list: [page2Customer], total: customers.length + 1 }
}
} else data = { list: customers, total: customers.length + 1 }
} else if (path === '/web/crm/customer/detail') {
if (forbiddenMode === 'detail') {
code = 403
msg = '无权限访问客户详情'
} else {
if (body.id === delayedDetailId) await new Promise((resolve) => setTimeout(resolve, 500))
data = [...customers, secondCustomer].find((c) => c.id === body.id)
}
} else if (path === '/web/crm/customer/checkDuplicate')
data = { isDuplicate: false, duplicates: [] }
else if (path === '/web/crm/customer/options') data = customers
else if (path === '/web/crm/customer/column-facet-values')
data = {
list: body.keyword
? [{ value: 'KH-REMOTE-201', label: '第201号外值', count: 1 }]
: [{ value: 'KH001', label: 'KH001', count: 1 }]
}
else if (path === '/web/crm/customer/add') {
data = { ...body, id: 'created-customer', customerNo: 'KH002', createBy: 'user-1' }
customers.push(data)
} else if (path === '/web/crm/customer/update') {
Object.assign(
customers.find((c) => c.id === body.id),
body
)
data = body
} else if (path === '/web/crm/customer/delete' || path === '/web/crm/customer/intoPool') {
for (let i = customers.length - 1; i >= 0; i--)
if (body.ids.includes(customers[i].id)) customers.splice(i, 1)
} else if (path === '/web/crm/contact/byCustomer') data = contacts
else if (path === '/web/crm/contact/detail') data = contacts.find((c) => c.id === body.id)
else if (path === '/web/crm/contact/add') {
data = { ...body, id: 'contact-2', createBy: 'user-1' }
contacts.push(data)
} else if (path === '/web/crm/contact/update') {
Object.assign(
contacts.find((c) => c.id === body.id),
body
)
data = body
} else if (path === '/web/crm/contact/setPrimary')
contacts.forEach((c) => (c.isPrimary = c.id === body.id ? 1 : 0))
else if (path === '/web/crm/contact/delete')
contacts = contacts.filter((c) => !body.ids.includes(c.id))
else if (path === '/web/crm/customer/follow/byCustomer') data = follows
else if (path === '/web/crm/customer/follow/add') {
data = {
...body,
id: 'follow-1',
createBy: 'user-1',
createByName: '测试用户',
contactName: '张经理'
}
follows.push(data)
} else if (path === '/web/crm/customer/follow/delete')
follows = follows.filter((f) => !body.ids.includes(f.id))
else if (path === '/web/crm/invoice-info/by-customer') data = invoices
else if (path === '/web/crm/invoice-info/add') {
if (failInvoice) {
code = 500
msg = '开票测试失败'
failInvoice = false
} else {
data = { ...body, id: 'invoice-1', createBy: 'user-1' }
invoices.push(data)
}
} else if (path === '/web/crm/invoice-info/update') {
Object.assign(
invoices.find((i) => i.id === body.id),
body
)
data = body
} else if (path === '/web/crm/invoice-info/set-default')
invoices.forEach((i) => (i.isDefault = i.id === body.id ? '1' : '0'))
else if (path === '/web/crm/invoice-info/delete')
invoices = invoices.filter((i) => i.id !== body.id)
else if (path === '/web/admin/attachment/upload') {
signalUploadStarted?.()
signalUploadStarted = null
if (uploadGate) await uploadGate
const queued = uploadQueue.shift()
if (queued?.fail) {
code = 500
msg = queued.fail
} else {
data = queued?.data || {
id: 'file-1',
fileName: '证件.pdf',
fileUrl: '/fixtures/customer.pdf',
fileType: 'application/pdf'
}
}
} else if (path === '/web/admin/attachment/preview-url') data = { previewUrl: body.fileUrl }
else if (path === '/web/crm/opportunity/list')
data = {
list: [opportunity],
total: 1
}
else if (path === '/web/crm/opportunity/detail') data = opportunity
else if (path === '/web/crm/opportunity/update' || path === '/web/crm/opportunity/stage')
Object.assign(opportunity, body)
else if (path === '/web/crm/opportunity/follow/list')
data = { list: opportunityFollows, total: opportunityFollows.length }
else if (path === '/web/crm/opportunity/follow/add')
opportunityFollows.push({ ...body, id: 'opp-follow-1', createBy: 'user-1' })
else if (path === '/web/crm/opportunity/follow/update') Object.assign(opportunityFollows[0], body)
else if (path === '/web/crm/opportunity/follow/delete') opportunityFollows = []
else if (path.includes('/opportunity/')) data = { list: [] }
else if (path === '/web/crm/contract/list')
data = { rows: [{ id: 'contract-1', contractName: '测试合同' }], total: 1 }
else if (path === '/web/monitor/operlog/list')
data = {
rows: [
{
id: 'log-1',
title: 'CRM客户管理',
operName: '测试用户',
status: '0',
operParam: '<img src=x onerror=alert(1)>',
operTime: '2026-10-17 10:00:00'
}
],
total: 1
}
else throw new Error(`未处理的客户 E2E API:${path}`)
await route.fulfill({
contentType: 'application/json',
body: JSON.stringify({ code, msg, data })
})
})
const label = (name) => page.getByLabel(name, { exact: true }).filter({ visible: true })
const click = (name) =>
page
.getByRole('button', { name, exact: true })
.or(page.getByRole('tab', { name, exact: true }))
.filter({ visible: true })
.click()
const waitHeading = (name) => page.getByRole('heading', { name, exact: true }).waitFor()
const closeSheet = () =>
page.getByRole('button', { name: '关闭', exact: true }).filter({ visible: true }).click()
const hideDevTools = async () => {
await page.addStyleTag({
content:
'#vue-devtools-anchor,.vue-devtools__anchor,.vue-devtools-frame{display:none!important}'
})
assert.equal(await page.locator('#vue-devtools-anchor').filter({ visible: true }).count(), 0)
}
const assertNoOverflow = async (label) => {
const overflow = await page.evaluate(() => document.documentElement.scrollWidth > innerWidth)
assert.equal(overflow, false, `${label}不应横向溢出`)
}
const assertMinTouchTargets = async (locator, label) => {
const sizes = await locator.evaluateAll((elements) =>
elements
.filter((element) => element.getClientRects().length > 0)
.map((element) => ({
width: element.getBoundingClientRect().width,
height: element.getBoundingClientRect().height
}))
)
assert.ok(sizes.length > 0, `${label}应存在可见触控目标`)
assert.ok(
sizes.every(({ width, height }) => width >= 44 && height >= 44),
`${label}触控目标应至少为44×44px:${JSON.stringify(sizes)}`
)
}
const waitForMessagesToClear = () =>
page.waitForFunction(() => !document.querySelector('.el-message'), undefined, { timeout: 6000 })
try {
await page.goto(`${origin}/#/m/crm/customer?mpTicket=customer-forbidden-list`)
await page.locator('.mp-customer-error').filter({ hasText: '无权限访问客户列表' }).waitFor()
assert.equal(await page.locator('.mp-crm-expense-card').count(), 0)
assert.equal(await page.locator('.mp-wv-status-tabs').count(), 0)
assert.equal(await page.locator('.mp-wv-filter-bar--three').count(), 0)
assert.equal(await page.locator('.mp-customer-summary').count(), 0)
assert.equal(await page.locator('.mp-wv-speed-dial').count(), 0)
assert.equal(await page.locator('.mp-customer-batch-bar').count(), 0)
assert.equal(await page.locator('.mp-customer-sheet').count(), 0)
await page.goto(
`${origin}/#/m/crm/customer/${customers[0].id}?mpTicket=customer-forbidden-detail`
)
await page.locator('.mp-customer-error').filter({ hasText: '无权限访问客户详情' }).waitFor()
await page.goto(`${origin}/#/m/crm/customer?mpTicket=customer-fixture`)
await hideDevTools()
await page.getByRole('button', { name: `查看客户:${customers[0].customerName}` }).waitFor()
const skeletonOrder = await page
.locator('.mp-wv-header, .mp-wv-status-tabs, .mp-wv-filter-bar--three, .mp-crm-expense-card')
.evaluateAll((nodes) => nodes.map((node) => node.className))
assert.match(String(skeletonOrder[0]), /mp-wv-header/)
assert.match(String(skeletonOrder[1]), /mp-wv-status-tabs/)
assert.match(String(skeletonOrder[2]), /mp-wv-filter-bar--three/)
assert.match(String(skeletonOrder[3]), /mp-crm-expense-card/)
assert.equal(await page.locator('.mp-customer-actions').filter({ visible: true }).count(), 0)
assert.equal(await page.locator('.mp-wv-speed-dial').count(), 1)
assert.equal(await page.getByText('导出', { exact: true }).count(), 0)
const cardActionSizes = await page
.locator('.mp-crm-expense-card .op-actions button')
.evaluateAll((buttons) =>
buttons.map((button) => ({
width: button.getBoundingClientRect().width,
height: button.getBoundingClientRect().height
}))
)
assert.ok(cardActionSizes.every(({ width, height }) => width >= 44 && height >= 44))
await assertMinTouchTargets(page.locator('.mp-wv-speed-main'), 'Speed Dial主按钮')
await click('快捷操作')
await assertMinTouchTargets(page.locator('.mp-wv-speed-item'), 'Speed Dial菜单')
await click('批量选择')
await assertMinTouchTargets(page.locator('.mp-customer-batch-bar button'), '批量操作栏')
await page.locator('.expense-card__select').first().click()
assert.equal(await page.locator('.mp-crm-expense-card .ec-bottom').count(), 0)
failList = true
await click('重点')
await page.getByText('列表测试失败', { exact: true }).first().waitFor()
assert.equal(await page.locator('.mp-crm-expense-card').count(), 0)
assert.match(await page.locator('.mp-customer-summary').innerText(), /共 0 位客户 · 已加载 0 位/)
assert.match(await page.locator('.mp-customer-batch-bar').innerText(), /已选 0 项/)
await click('重试')
await page.getByRole('button', { name: `查看客户:${customers[0].customerName}` }).waitFor()
await click('完成')
await click('全部')
failNextPage2 = true
await click('加载更多(1/2)')
await page.getByText('分页测试失败', { exact: true }).waitFor()
await click('重试')
await page.getByRole('button', { name: '查看客户:分页客户', exact: true }).waitFor()
const page2Calls = calls.filter(
(call) => call.path.endsWith('/customer/list') && Number(call.body.page) === 2
)
assert.deepEqual(
page2Calls.slice(-2).map((call) => Number(call.body.page)),
[2, 2],
'分页失败后重试不得跳到第 3 页'
)
await page.getByLabel('搜索客户').fill('测试')
await Promise.all([
page.waitForResponse((response) => response.url().endsWith('/customer/list')),
page.getByLabel('搜索客户').press('Enter')
])
await Promise.all([
page.waitForResponse((response) => response.url().endsWith('/customer/list')),
page.getByLabel('搜索客户').fill('')
])
assert.equal(
calls.findLast((call) => call.path.endsWith('/customer/list')).body.keyword,
undefined
)
delayNextPage2 = true
await click('加载更多(1/2)')
await click('客户类型')
await click('企业')
await page.waitForTimeout(650)
assert.equal(
await page.getByRole('button', { name: '查看客户:分页客户', exact: true }).count(),
0,
'旧筛选的第 2 页结果不得混入新筛选'
)
await click('企业')
await click('全部类型')
for (const [name, endpoint] of [
['待跟进', 'toFollow'],
['重点', 'key'],
['全部', 'list']
]) {
await Promise.all([
page.waitForResponse((r) => r.url().endsWith('/customer/' + endpoint)),
click(name)
])
}
await Promise.all([
page.waitForResponse((r) => r.url().includes('/customer/mine')),
click('我的')
])
assert.equal(calls.findLast((c) => c.path.endsWith('/customer/mine')).body.viewMode, 'mine')
await page.getByLabel('搜索客户').fill('顶部词')
await Promise.all([
page.waitForResponse((r) => r.url().includes('/customer/mine')),
page.getByLabel('搜索客户').press('Enter')
])
await page.getByRole('button', { name: /^更多/ }).click()
const filterSheet = page.locator('.mp-sheet').filter({ hasText: '更多筛选' })
await assertMinTouchTargets(
filterSheet.locator('.mp-sheet-close, .mp-sheet-foot button'),
'更多筛选底部与关闭按钮'
)
assert.equal(await filterSheet.getByLabel('关键词').inputValue(), '顶部词')
assert.equal(await filterSheet.getByLabel('业务视图').inputValue(), 'mine')
await filterSheet.getByLabel('关键词').fill('面板词')
await filterSheet.getByLabel('业务视图').selectOption('key')
await filterSheet.getByLabel('排序字段').selectOption('createTime')
const mobileFilter = filterSheet
.locator('details')
.filter({ has: page.locator('summary:text-is("手机号")') })
await mobileFilter.locator('summary').click()
await mobileFilter.locator('input').fill('138')
const followCountFilter = filterSheet
.locator('details')
.filter({ has: page.locator('summary:text-is("跟进次数")') })
await followCountFilter.locator('summary').click()
await followCountFilter.getByLabel('最小值').fill('1')
const createTimeFilter = filterSheet
.locator('details')
.filter({ has: page.locator('summary:text-is("创建时间")') })
await createTimeFilter.locator('summary').click()
await createTimeFilter.getByLabel('起始时间').fill('2026-10-01T08:00')
const customerNoFilter = filterSheet
.locator('details')
.filter({ has: page.locator('summary:text-is("客户编号")') })
await customerNoFilter.locator('summary').click()
await Promise.all([
page.waitForResponse((r) => r.url().endsWith('/customer/column-facet-values')),
customerNoFilter.locator('input[type="search"]').fill('远端')
])
assert.equal(
calls.findLast((c) => c.path.endsWith('/customer/column-facet-values')).body.keyword,
'远端'
)
await customerNoFilter.getByText('第201号外值', { exact: true }).waitFor()
await page.locator('summary').filter({ hasText: '客户类型' }).click()
await page.getByLabel('企业', { exact: true }).check()
await page.getByLabel('个人', { exact: true }).check()
await page.locator('summary').filter({ hasText: '客户级别' }).click()
await page.getByLabel('普通', { exact: true }).check()
await page.getByLabel('重点', { exact: true }).check()
await page.getByLabel('客户简称', { exact: true }).uncheck()
await Promise.all([
page.waitForResponse((r) => r.url().includes('/customer/key')),
click('应用筛选')
])
const appliedFilterCall = calls.findLast((c) => c.path.endsWith('/customer/key'))
assert.equal(appliedFilterCall.body.keyword, '面板词')
assert.equal(appliedFilterCall.body.customerTypeIn, 'company,person')
assert.equal(appliedFilterCall.body.levelIn, 'normal,key')
assert.equal(appliedFilterCall.body.mobile, '138')
assert.equal(appliedFilterCall.body.followCountMin, '1')
assert.equal(appliedFilterCall.body.beginTime, '2026-10-01 08:00:00')
assert.equal(appliedFilterCall.body.sortField, 'createTime')
assert.equal(await page.getByLabel('搜索客户').inputValue(), '面板词')
assert.equal(
await page.getByRole('button', { name: '重点', exact: true }).getAttribute('aria-pressed'),
'true'
)
assert.deepEqual(
await page.locator('.mp-wv-filter-bar--three .mp-wv-filter-trig__val').allTextContents(),
['已选2项', '已选2项']
)
await page.locator('.mp-wv-filter-bar--three .mp-wv-filter-trig').first().click()
await click('企业')
assert.equal(
calls.findLast((c) => c.path.endsWith('/customer/key')).body.customerTypeIn,
'company'
)
assert.equal(
await page.locator('.mp-wv-filter-bar--three .mp-wv-filter-trig__val').first().innerText(),
'企业'
)
assert.equal(
await page
.locator('.mp-crm-expense-card')
.first()
.getByText('客户简称', { exact: true })
.count(),
0
)
await page.getByRole('button', { name: /^更多/ }).click()
await Promise.all([
page.waitForResponse((r) => r.url().endsWith('/customer/list')),
filterSheet.getByRole('button', { name: '重置', exact: true }).click()
])
assert.equal(await page.getByLabel('搜索客户').inputValue(), '')
assert.equal(
await page.getByRole('button', { name: '全部', exact: true }).getAttribute('aria-pressed'),
'true'
)
assert.deepEqual(
await page.locator('.mp-wv-filter-bar--three .mp-wv-filter-trig__val').allTextContents(),
['客户类型', '客户级别']
)
assert.equal(
await page
.locator('.mp-crm-expense-card')
.first()
.getByText('客户简称', { exact: true })
.count(),
1
)
await page.waitForTimeout(3200)
await page.setViewportSize({ width: 414, height: 812 })
await hideDevTools()
await assertNoOverflow('414px 有数据列表')
await page.screenshot({ path: `${artifacts}/list-414.png`, fullPage: true })
await page.setViewportSize({ width: 375, height: 812 })
await assertNoOverflow('375px 有数据列表')
await page.screenshot({ path: `${artifacts}/list-375.png`, fullPage: true })
await page.getByRole('button', { name: `查看客户:${customers[0].customerName}` }).click()
await waitHeading('客户详情')
await page.goto(`${origin}/#/m/crm/customer/${customers[0].id}`)
await waitHeading('客户详情')
await page.reload()
await waitHeading('客户详情')
customers[0].createBy = 'another-user'
await page.reload()
await waitHeading('客户详情')
assert.equal(await page.getByRole('button', { name: '删除', exact: true }).isDisabled(), true)
customers[0].createBy = 'user-1'
await page.reload()
await waitHeading('客户详情')
assert.equal(await page.getByRole('button', { name: '删除', exact: true }).isEnabled(), true)
const detailActionSizes = await page.locator('.mp-wv-fab-bar button').evaluateAll((buttons) =>
buttons.map((button) => ({
width: button.getBoundingClientRect().width,
height: button.getBoundingClientRect().height
}))
)
assert.ok(detailActionSizes.every(({ width, height }) => width >= 44 && height >= 44))
assert.deepEqual(await page.locator('.mp-customer-detail-tabs button').allTextContents(), [
'资料',
'跟进记录',
'联系人',
'商机',
'合同',
'开票信息',
'操作日志'
])
const detailTag = page.locator('.mp-customer-webview-tag').first()
await detailTag.waitFor()
assert.notEqual(
await detailTag.evaluate((tag) => getComputedStyle(tag).color),
'rgb(255, 255, 255)'
)
await page.setViewportSize({ width: 414, height: 812 })
await hideDevTools()
await assertNoOverflow('414px 客户详情')
await page.screenshot({ path: `${artifacts}/detail-414.png`, fullPage: true })
await page.setViewportSize({ width: 375, height: 812 })
await page.goto(`${origin}/#/m/crm/customer/${secondCustomer.id}?tab=invoice`)
await page.getByText('暂无开票信息', { exact: true }).waitFor()
assert.equal(
calls.findLast((call) => call.path.endsWith('/customer/detail')).body.id,
secondCustomer.id
)
assert.ok(
await page
.locator('.mp-customer-detail-tabs button')
.filter({ hasText: '开票信息' })
.evaluate((button) => button.classList.contains('active'))
)
delayedDetailId = customers[0].id
const slowARequest = page.waitForRequest((request) => {
if (!request.url().endsWith('/web/crm/customer/detail')) return false
try {
return request.postDataJSON()?.id === customers[0].id
} catch {
return false
}
})
await page.evaluate((id) => {
location.hash = `#/m/crm/customer/${id}?tab=follow`
}, customers[0].id)
await slowARequest
await page.evaluate((id) => {
location.hash = `#/m/crm/customer/${id}?tab=contact`
}, secondCustomer.id)
await page.getByRole('heading', { name: '张经理', exact: true }).waitFor()
await page.waitForTimeout(650)
assert.ok(
await page
.locator('.mp-customer-detail-tabs button')
.filter({ hasText: '联系人' })
.evaluate((button) => button.classList.contains('active'))
)
await click('资料')
await page.getByRole('heading', { name: secondCustomer.customerName, exact: true }).waitFor()
assert.equal(await page.getByRole('heading', { name: customers[0].customerName }).count(), 0)
delayedDetailId = ''
await page.evaluate((id) => {
location.hash = `#/m/crm/customer/${id}?tab=follow`
}, customers[0].id)
await page.getByRole('button', { name: '+ 添加跟进', exact: true }).waitFor()
assert.ok(
await page
.locator('.mp-customer-detail-tabs button')
.filter({ hasText: '跟进记录' })
.evaluate((button) => button.classList.contains('active'))
)
await click('跟进记录')
await click('+ 添加跟进')
await label('关联联系人').selectOption('contact-1')
await label('跟进内容 *').fill('移动端跟进测试')
await label('下次联系时间').fill('2026-10-18T10:00')
await page
.locator('.mp-sheet')
.filter({ hasText: '添加跟进记录' })
.locator('input[type=file]')
.setInputFiles({
name: '跟进附件.pdf',
mimeType: 'application/pdf',
buffer: Buffer.from('%PDF-1.4\nfollow-fixture')
})
await page.getByText('customer.pdf', { exact: true }).filter({ visible: true }).waitFor()
await click('保存跟进')
await page.getByText('移动端跟进测试', { exact: true }).waitFor()
assert.equal(follows[0].customerId, '90071992547409931')
assert.equal(follows[0].nextTime, '2026-10-18 10:00:00')
assert.equal(follows[0].attachment, '/fixtures/customer.pdf')
const followAttachment = page
.locator('.mp-wv-card')
.filter({ hasText: '移动端跟进测试' })
.locator('.att-item')
.first()
const followAttachmentBox = await followAttachment.boundingBox()
assert.equal(followAttachmentBox?.width, 72)
assert.equal(followAttachmentBox?.height, 72)
await followAttachment.locator('.att-preview').click()
await page.getByRole('dialog').getByText('customer.pdf', { exact: true }).waitFor()
await page.keyboard.press('Escape')
await click('联系人')
await page.getByRole('heading', { name: '张经理', exact: true }).waitFor()
await click('+ 新增联系人')
await label('联系人姓名 *').fill('李经理')
await label('手机号 *').fill('13900139000')
await click('保存联系人')
await page.getByRole('heading', { name: '李经理', exact: true }).waitFor()
assert.equal(contacts[1].customerId, '90071992547409931')
await click('开票信息')
await click('+ 新增开票信息')
await label('单位名称(章) *').fill('测试开票单位')
await label('税号').fill('123456789')
await click('保存开票信息')
await page.getByText('测试开票单位', { exact: true }).waitFor()
await click('设为默认')
await page.getByText('默认', { exact: true }).filter({ visible: true }).waitFor()
assert.equal(invoices[0].isDefault, '1')
await click('操作日志')
await click('CRM客户管理')
await page.getByText('<img src=x onerror=alert(1)>', { exact: true }).waitFor()
assert.equal(await page.locator('img[src="x"]').count(), 0)
await closeSheet()
assert.equal(await page.locator('.mp-sheet-mask').filter({ visible: true }).count(), 0)
await click('商机')
await click('测试商机')
await page.getByText('123', { exact: true }).waitFor()
await click('修改商机')
await label('商机名称 *').fill('移动修改商机')
await click('保存商机操作')
await page.getByText('移动修改商机', { exact: true }).filter({ visible: true }).first().waitFor()
assert.equal(opportunity.customerId, '90071992547409931')
await click('推进阶段')
await label('商机阶段 *').selectOption('quote')
await label('变更原因 *').fill('已报价')
await click('保存商机操作')
await page.getByRole('button', { name: '推进阶段', exact: true }).waitFor()
assert.equal(opportunity.stagePercent, 60)
await click('添加商机跟进')
await label('商机跟进内容 *').fill('商机跟进测试')
await click('保存商机操作')
await page.getByText('商机跟进测试', { exact: true }).waitFor()
await click('编辑商机跟进')
await label('商机跟进内容 *').fill('商机跟进已编辑')
await click('保存商机操作')
await page.getByText('商机跟进已编辑', { exact: true }).waitFor()
await click('删除商机跟进')
await page.getByRole('button', { name: /^(确定|确认)$/ }).click()
await page.getByText('暂无跟进记录', { exact: true }).waitFor()
await closeSheet()
await click('合同')
await page.getByText('测试合同', { exact: true }).waitFor()
await click('资料')
await page.screenshot({ path: `${artifacts}/detail-375.png`, fullPage: true })
await click('编辑')
await waitHeading('编辑客户')
await label('客户简称 *').fill('移动编辑')
const certificateInput = page.locator('input[type=file]').first()
let releaseUploadGate
uploadGate = new Promise((resolve) => {
releaseUploadGate = resolve
})
const uploadStarted = new Promise((resolve) => {
signalUploadStarted = resolve
})
const uploadCallsBeforeConcurrent = calls.filter(
(call) => call.path === '/web/admin/attachment/upload'
).length
await certificateInput.setInputFiles({
name: '并发首个.pdf',
mimeType: 'application/pdf',
buffer: Buffer.from('%PDF-1.4\nconcurrent-first')
})
await uploadStarted
await certificateInput.evaluate((input) => {
const transfer = new DataTransfer()
transfer.items.add(new File(['second'], '并发第二个.pdf', { type: 'application/pdf' }))
Object.defineProperty(input, 'files', { value: transfer.files, configurable: true })
input.dispatchEvent(new Event('change', { bubbles: true }))
})
await page.waitForTimeout(100)
assert.equal(
calls.filter((call) => call.path === '/web/admin/attachment/upload').length,
uploadCallsBeforeConcurrent + 1,
'上传期间再次选择不得启动第二个上传请求'
)
releaseUploadGate()
uploadGate = null
await page.getByText('customer.pdf', { exact: true }).waitFor()
await page.waitForFunction(() => {
const input = document.querySelector('input[type=file]')
return !!input && !input.disabled
})
uploadQueue = [
{
data: {
id: 'partial-ok',
fileName: '部分成功.pdf',
fileUrl: '/fixtures/partial-ok.pdf',
fileType: 'application/pdf'
}
}
]
const uploadCallsBeforePartialFailure = calls.filter(
(call) => call.path === '/web/admin/attachment/upload'
).length
await certificateInput.setInputFiles({
name: '部分成功.pdf',
mimeType: 'application/pdf',
buffer: Buffer.from('%PDF-1.4\npartial-ok')
})
await page.getByText('partial-ok.pdf', { exact: true }).waitFor()
await page.waitForFunction(() => {
const input = document.querySelector('input[type=file]')
return !!input && !input.disabled
})
uploadQueue = [{ fail: '后续上传失败' }]
await certificateInput.setInputFiles({
name: '后续失败.pdf',
mimeType: 'application/pdf',
buffer: Buffer.from('%PDF-1.4\npartial-fail')
})
for (
let attempt = 0;
attempt < 100 &&
calls.filter((call) => call.path === '/web/admin/attachment/upload').length <
uploadCallsBeforePartialFailure + 2;
attempt += 1
)
await page.waitForTimeout(20)
await page.getByText('后续上传失败', { exact: true }).last().waitFor()
assert.equal(uploadQueue.length, 0, '后续失败请求应被处理')
assert.equal(
calls.filter((call) => call.path === '/web/admin/attachment/upload').length,
uploadCallsBeforePartialFailure + 2
)
assert.ok(await page.getByText('customer.pdf', { exact: true }).isVisible())
await assertMinTouchTargets(
page.locator(
'.mp-customer-attachments .att-preview, .mp-customer-attachments .att-remove, .mp-customer-attachments .att-add'
),
'附件预览、删除与添加'
)
await waitForMessagesToClear()
await page.setViewportSize({ width: 414, height: 812 })
await hideDevTools()
await assertNoOverflow('414px 附件表单')
await page.screenshot({ path: `${artifacts}/form-attachments-414.png`, fullPage: true })
await page.setViewportSize({ width: 375, height: 812 })
await click('保存客户')
await waitHeading('客户详情')
assert.equal(customers[0].shortName, '移动编辑')
assert.match(customers[0].businessLicenseImages, /\/fixtures\/customer\.pdf/)
assert.match(customers[0].businessLicenseImages, /\/fixtures\/partial-ok\.pdf/)
await page.getByRole('button', { name: '返回客户列表' }).click()
await click('快捷操作')
await click('新增客户')
await waitHeading('新增客户')
for (const [name, value] of [
['客户名称 *', '新客户'],
['客户简称 *', '新'],
['省份 *', '湖北'],
['城市 *', '宜昌'],
['区县 *', '西陵'],
['所在园区 *', '园区A']
])
await label(name).fill(value)
await label('客户类型 *').selectOption('company')
await label('客户来源 *').selectOption('phone')
await label('单位名称(章)').fill('新增开票单位')
failInvoice = true
await click('保存客户')
await page.getByText('客户已创建。请补存开票资料,无需再次新增客户。').waitFor()
await click('补存开票资料')
await waitHeading('客户详情')
assert.equal(calls.filter((c) => c.path === '/web/crm/customer/add').length, 1)
await page.getByRole('button', { name: '返回客户列表' }).click()
await page.getByRole('button', { name: '查看客户:新客户', exact: true }).waitFor()
await click('快捷操作')
await click('批量选择')
await page
.locator('.mp-crm-expense-card')
.filter({ hasText: '新客户' })
.locator('.expense-card__select')
.click()
await click('放入公海')
await label('放入原因 *').fill('测试批量放入')
await click('确认放入')
await page.getByRole('button', { name: /^(确定|确认)$/ }).click()
await page.getByRole('button', { name: '查看客户:新客户', exact: true }).waitFor({
state: 'hidden'
})
assert.deepEqual(calls.findLast((c) => c.path.endsWith('/customer/intoPool')).body.ids, [
'created-customer'
])
await click('快捷操作')
await click('批量选择')
await page.locator('.expense-card__select').first().click()
await click('删除')
await page.getByRole('button', { name: /^(确定|确认)$/ }).click()
await page.getByText('暂无客户,可调整筛选后重试').waitFor()
assert.deepEqual(calls.findLast((c) => c.path.endsWith('/customer/delete')).body.ids, [
'90071992547409931'
])
failList = true
await page.getByLabel('搜索客户').fill('失败')
await page.getByLabel('搜索客户').press('Enter')
await page.getByText('列表测试失败', { exact: true }).first().waitFor()
await click('重试')
await page.getByText('暂无客户,可调整筛选后重试').waitFor()
await waitForMessagesToClear()
for (const width of [375, 414]) {
await page.setViewportSize({ width, height: 812 })
await assertNoOverflow(`${width}px 空列表`)
assert.equal(await page.locator('.mp-sheet-mask').filter({ visible: true }).count(), 0)
assert.equal(await page.locator('.mp-wv-speed-mask.open').count(), 0)
if (width === 414)
await page.screenshot({ path: `${artifacts}/list-empty-414.png`, fullPage: true })
}
assert.deepEqual(pageErrors, [])
console.log(
JSON.stringify({
result: 'PASS',
assertions:
'四视图、快捷/高级筛选与显示字段、搜索清空、分页失败回滚与乱序隔离、卡片动作、直达详情刷新、创建人权限、客户跟进/联系人/商机/合同/开票/日志、72px附件上传预览、客户编辑与新增失败重试、批量公海/删除、44px触达、375/414无溢出遮罩',
apiCalls: calls.length,
screenshots: artifacts
})
)
} catch (error) {
await page.screenshot({ path: `${artifacts}/failure.png`, fullPage: true })
console.error(await page.locator('body').innerText())
console.error('Page errors:', pageErrors)
console.error(
'API calls:',
calls.map((c) => c.path)
)
throw error
} finally {
await context.close()
await browser.close()
}
@@ -0,0 +1,221 @@
import assert from 'node:assert/strict'
import { mkdir } from 'node:fs/promises'
import { chromium } from 'playwright'
const origin = process.env.MP_CRM_PRIMITIVES_ORIGIN || 'http://localhost:3006'
const artifacts = '/tmp/shanxia-mp-crm-primitives'
await mkdir(artifacts, { recursive: true })
const browser = await chromium.launch({ headless: true, channel: 'chrome' })
const context = await browser.newContext({
viewport: { width: 375, height: 812 },
isMobile: true,
deviceScaleFactor: 1
})
const page = await context.newPage()
const pageErrors = []
page.on('pageerror', (error) => pageErrors.push(error.message))
try {
await page.goto(origin, { waitUntil: 'domcontentloaded' })
await page.evaluate(async () => {
const [
{ createApp, h, ref },
{ default: Header },
{ default: Tabs },
{ default: Filters },
{ default: Card },
{ default: Attachments },
{ default: Timeline }
] = await Promise.all([
import('/node_modules/.vite/deps/vue.js'),
import('/src/components/mp/MpBusinessHeader.vue'),
import('/src/components/mp/MpStatusTabs.vue'),
import('/src/components/mp/MpThreeColumnFilters.vue'),
import('/src/components/mp/MpExpenseCard.vue'),
import('/src/components/mp/MpAttachmentGrid.vue'),
import('/src/components/mp/MpApprovalTimeline.vue'),
import('/src/styles/mp-webview.scss')
])
document.body.innerHTML = '<div id="primitive-fixture"></div>'
document.body.style.margin = '0'
window.__primitiveEvents = []
createApp({
setup() {
const keyword = ref('')
const status = ref('all')
const quickFilters = ref([
{
key: 'owner',
label: '负责人',
value: 'all',
options: [
{ label: '全部负责人', value: 'all' },
{ label: '测试用户', value: 'user-1' }
]
},
{
key: 'date',
label: '创建时间',
value: 'all',
options: [
{ label: '全部时间', value: 'all' },
{ label: '本月', value: 'month' }
]
}
])
const event = (name, payload) => window.__primitiveEvents.push({ name, payload })
return () =>
h(
'main',
{
class: 'primitive-page',
style: {
boxSizing: 'border-box',
width: '100%',
padding: '0 10px 24px',
overflowX: 'clip'
}
},
[
h(Header, {
title: '报价管理',
searchable: true,
keyword: keyword.value,
searchPlaceholder: '搜索报价单号或客户',
'onUpdate:keyword': (value) => (keyword.value = value),
onSearch: () => event('search', keyword.value),
onBack: () => event('back')
}),
h(Tabs, {
modelValue: status.value,
tabs: [
{ label: '全部', value: 'all', count: 2 },
{ label: '草稿', value: 'draft', count: 1 }
],
'onUpdate:modelValue': (value) => (status.value = value),
onChange: (value) => event('status', value)
}),
h(Filters, {
quickFilters: quickFilters.value,
moreActive: true,
onSelect: (payload) => event('filter', payload),
onMore: () => event('more')
}),
h(
Card,
{
title: 'BJ20261017001',
status: '审批中',
statusTone: 'warning',
amount: '¥ 12,680.00',
amountLabel: '报价金额',
time: '2026-10-17 10:30',
onOpen: () => event('open')
},
{
emphasis: () => h('span', '山峡化工测试客户'),
kv: () => [h('div', '有效期:30 天'), h('div', '负责人:测试用户')],
actions: () => h('button', { type: 'button' }, '编辑')
}
),
h(Attachments, {
items: [{ id: '1', url: '/fixture.pdf', name: '报价附件.pdf' }],
editable: true,
onAdd: () => event('attachment-add')
}),
h(Timeline, {
items: [
{
id: '1',
name: '张审批',
status: '已通过',
tone: 'success',
opinion: '同意',
time: '2026-10-17 11:00'
}
]
}),
h('section', { class: 'legacy-filter-smoke', 'aria-label': '历史两栏筛选冒烟' }, [
h('div', { class: 'mp-wv-filter-bar' }, [
h('button', { class: 'mp-wv-filter-trig', type: 'button' }, '历史筛选一'),
h('button', { class: 'mp-wv-filter-trig', type: 'button' }, '历史筛选二')
])
])
]
)
}
}).mount('#primitive-fixture')
})
await page.locator('.primitive-page').waitFor()
const searchBox = page.locator('.mp-wv-search')
assert.equal(await searchBox.getAttribute('aria-label'), '搜索')
assert.ok((await searchBox.boundingBox()).height >= 44, '搜索框触达高度不足 44px')
await searchBox.fill('测试报价')
await searchBox.press('Enter')
await page.locator('.mp-wv-status-tabs .filter-tag').nth(1).click()
assert.equal(
await page.locator('.mp-wv-status-tabs .filter-tag').nth(1).getAttribute('aria-pressed'),
'true'
)
const firstFilter = page.locator('.mp-wv-filter-trig').first()
await firstFilter.click()
const option = page.locator('.mp-wv-filter-panel .mp-wv-filter-opt').nth(1)
await option.waitFor()
const optionIsTopmost = await option.evaluate((element) => {
const box = element.getBoundingClientRect()
const topmost = document.elementFromPoint(box.left + box.width / 2, box.top + box.height / 2)
return topmost === element || element.contains(topmost)
})
assert.equal(optionIsTopmost, true, '筛选遮罩覆盖了下拉选项')
assert.ok((await option.boundingBox()).height >= 44, '筛选选项触达高度不足 44px')
await option.click()
assert.equal(
await page.locator('.mp-wv-filter-panel').getAttribute('class'),
'mp-wv-filter-panel'
)
await firstFilter.click()
await page.locator('.mp-wv-filter-mask.open').waitFor()
await page.mouse.click(5, 760)
assert.equal(await firstFilter.getAttribute('aria-expanded'), 'false')
const cardOpen = page.locator('.mp-crm-expense-card .expense-card__open')
await cardOpen.focus()
await cardOpen.press('Enter')
await cardOpen.press('Space')
const eventNames = await page.evaluate(() => window.__primitiveEvents.map((item) => item.name))
assert.deepEqual(eventNames.slice(0, 5), ['search', 'status', 'filter', 'open', 'open'])
const legacyColumns = await page
.locator('.legacy-filter-smoke .mp-wv-filter-bar')
.evaluate((element) => getComputedStyle(element).gridTemplateColumns.split(' ').length)
assert.equal(legacyColumns, 2, '历史筛选栏不应被改成三列')
const attachmentBox = await page.locator('.mp-crm-att-grid .att-item').first().boundingBox()
assert.equal(attachmentBox.width, 72)
assert.equal(attachmentBox.height, 72)
await page.evaluate(() => document.activeElement?.blur())
const viewportGeometry = await page.evaluate(() => ({
clientWidth: document.documentElement.clientWidth,
scrollWidth: document.documentElement.scrollWidth
}))
assert.equal(viewportGeometry.clientWidth, 375)
assert.ok(
viewportGeometry.scrollWidth <= viewportGeometry.clientWidth,
`公共原语出现横向溢出:${JSON.stringify(viewportGeometry)}`
)
await page.screenshot({ path: `${artifacts}/primitives-375.png`, fullPage: true })
assert.deepEqual(pageErrors, [], `页面异常:${pageErrors.join(';')}`)
console.log('CRM 公共原语浏览器交互回归通过:搜索、Tab、筛选、键盘开卡、附件与历史两栏冒烟')
} finally {
await browser.close()
}
@@ -0,0 +1,76 @@
import assert from 'node:assert/strict'
import { readFile } from 'node:fs/promises'
const root = new URL('../src/views/m/crm/product/', import.meta.url)
const list = await readFile(new URL('index.vue', root), 'utf8')
const detail = await readFile(new URL('detail.vue', root), 'utf8')
const form = await readFile(new URL('form.vue', root), 'utf8')
const formDialog = await readFile(
new URL('../src/components/business/product-form-dialog/index.vue', import.meta.url),
'utf8'
)
const order = ['<MpBusinessHeader', '<MpStatusTabs', '<MpThreeColumnFilters', '<MpExpenseCard'].map(
(token) => list.indexOf(token)
)
assert.ok(
order.every((index) => index >= 0),
'产品列表必须使用四个共享展示原语'
)
assert.deepEqual(
[...order].sort((a, b) => a - b),
order,
'列表必须依次为搜索、Tab、三栏筛选、卡片'
)
assert.match(list, /<template #actions>/, '产品卡必须提供虚线操作底栏')
assert.match(list, /编辑/, '产品卡必须提供编辑动作')
assert.match(list, /上架|下架/, '产品卡必须提供上下架动作')
assert.match(list, /删除/, '产品卡必须保留删除动作')
assert.equal(
(list.match(/class="mp-wv-speed-item/g) || []).length,
2,
'Speed Dial 必须保留分类和新增双入口'
)
assert.match(list, /requestSeq/, '列表必须用请求序号隔离过期响应')
assert.match(list, /requestSnapshot/, '列表必须用查询快照隔离过期响应')
assert.match(list, /fetchProductColumnFacetValues/, '型号快捷筛选必须来自完整列值接口')
assert.match(list, /role="alert"/, '分页失败必须显示可见错误')
assert.match(list, /categoryRequestSeq/, '分类树加载必须隔离过期响应')
assert.match(
list,
/categoryMapLoaded\.value\s*=\s*false|categoryMapLoaded\s*=\s*false/,
'分类失败必须允许重试'
)
assert.match(
list,
/\.mp-wv-speed-item[\s\S]*min-height:\s*44px/,
'Speed Dial 项命中高度不得小于 44px'
)
assert.doesNotMatch(
list,
/from 'vue'|from 'vue-router'|from 'element-plus'/,
'不得手工导入自动导入项'
)
assert.match(detail, /title="产品详情"/, '详情顶栏必须使用固定标题')
assert.doesNotMatch(detail, /\{\{\s*headerTitle\s*\}\}/, '详情顶栏不得使用记录标题')
assert.doesNotMatch(detail, /mp-wv-header__sub/, '详情顶栏不得展示副标题')
assert.match(detail, /class="mp-product-detail-tabs"/, '详情必须提供业务 Tab')
assert.match(detail, /mp-wv-fab-bar[\s\S]*mp-wv-touch-target/, '详情底栏按钮必须使用 44px 触达类')
assert.match(detail, /preview-src-list/, '详情必须保留图片预览')
assert.match(detail, /canDeleteByCreator/, '详情必须保留创建人删除权限')
assert.match(detail, /requestSeq/, '详情必须隔离过期详情响应')
assert.match(detail, /requestedId[\s\S]*route\.params\.id/, '详情必须校验 ID 查询快照')
assert.match(detail, /categoryRequestSeq/, '详情分类树必须隔离过期响应')
assert.match(detail, /status-tag--/, '详情状态必须使用 WebView 浅底语义标签')
assert.doesNotMatch(
detail,
/from 'vue'|from 'vue-router'|from 'element-plus'/,
'不得手工导入自动导入项'
)
assert.match(form, /<MpBusinessHeader/, '产品表单必须使用标准头并保留返回入口')
assert.match(formDialog, /72px/, '移动产品图片必须使用约 72×72 宫格')
assert.match(formDialog, /min-height:\s*44px/, '产品表单返回、底栏和上传操作命中高度不得小于 44px')
console.log('product DOM contract: PASS')
+457
View File
@@ -0,0 +1,457 @@
import assert from 'node:assert/strict'
import { mkdir } from 'node:fs/promises'
import { chromium } from 'playwright'
// 本地 H5 交互回归:所有 API 均由 fixture 拦截,不写真实业务库。
const origin = process.env.PRODUCT_TEST_ORIGIN || 'http://localhost:3006'
const artifacts = '/tmp/shanxia-product-e2e'
await mkdir(artifacts, { recursive: true })
const browser = await chromium.launch({ headless: true, channel: 'chrome' })
const context = await browser.newContext({
viewport: { width: 375, height: 812 },
isMobile: true,
deviceScaleFactor: 1
})
const page = await context.newPage()
const pageErrors = []
const calls = []
const unknownPaths = []
page.on('pageerror', (error) => pageErrors.push(error.message))
const image = `${origin}/fixture-product.svg`
const ownProduct = {
id: 'product-1',
productNo: 'CP-001',
productName: '工业甲醇',
namePinyinAbbr: 'GYJC',
categoryId: 'category-2',
categoryName: '醇类',
model: '优级品',
barcode: '690000000001',
taxRate: 13,
stock: 20,
lowStock: 5,
status: 'on',
isToxic: 1,
isExplosive: 0,
description: '产品说明',
remark: 'fixture 产品',
images: image,
brands: [{ id: 'brand-1', brandName: '山峡牌', status: 'on' }],
aliases: [{ id: 'alias-1', aliasName: '木醇' }],
createBy: 'user-1',
createTime: '2026-10-17 09:00:00'
}
const foreignProduct = {
...ownProduct,
id: 'product-foreign',
productNo: 'CP-002',
productName: '外部创建产品',
status: 'off',
createBy: 'user-2'
}
let failNextPage2 = false
let forbidNextList = false
let failNextCategory = true
await context.addInitScript(() => {
window.wx = {
miniProgram: {
navigateBack() {},
reLaunch() {},
getEnv(callback) {
callback({ miniprogram: true })
}
}
}
})
await context.route('**/fixture-product.svg', (route) =>
route.fulfill({
contentType: 'image/svg+xml',
body: '<svg xmlns="http://www.w3.org/2000/svg" width="160" height="160"><rect width="160" height="160" fill="#dff7ed"/><text x="28" y="86">产品图片</text></svg>'
})
)
await context.route('**/api/**', async (route) => {
const request = route.request()
const url = new URL(request.url())
if (!url.pathname.startsWith('/api/')) return route.continue()
const path = url.pathname.replace(/^\/api/, '')
let body = {}
try {
body = request.postDataJSON() || {}
} catch {
// 上传类请求不参与 JSON body 断言。
}
calls.push({ path, body })
let code = 200
let msg = 'ok'
let data = {}
if (path === '/web/auth/mp-webview-exchange') {
data = {
token: 'fixture-token',
refreshToken: 'fixture-refresh',
userInfo: { id: 'user-1', userId: 'user-1', userName: '测试用户', roles: ['admin'] }
}
} else if (path === '/web/admin/dict-data/all') {
data = {
crm_product_status: [
{ value: 'on', label: '上架', tagType: 'success' },
{ value: 'off', label: '下架', tagType: 'info' }
]
}
} else if (path === '/web/crm/product-categories/tree') {
if (failNextCategory) {
failNextCategory = false
code = 500
msg = '分类树测试失败'
} else {
data = [
{
id: 'category-1',
categoryName: '化工原料',
children: [{ id: 'category-2', categoryName: '醇类', children: [] }]
}
]
}
} else if (path === '/web/crm/products/column-facet-values') {
data = {
list: [
{ value: '优级品', label: '优级品', count: 2 },
{ value: '桶装(首屏外)', label: '桶装(首屏外)', count: 1 }
]
}
} else if (path === '/web/crm/products/list') {
if (forbidNextList) {
forbidNextList = false
code = 403
msg = '无权限'
} else if (Number(body.page) === 2 && failNextPage2) {
failNextPage2 = false
code = 500
msg = '分页测试失败'
} else {
data = {
list:
Number(body.page) === 2
? [{ ...ownProduct, id: 'product-3', productNo: 'CP-003' }]
: [ownProduct, foreignProduct],
total: 22
}
}
} else if (path === '/web/crm/products/detail') {
if (body.id === 'product-slow') {
await new Promise((resolve) => setTimeout(resolve, 450))
data = {
...ownProduct,
id: 'product-slow',
productNo: 'CP-SLOW',
productName: '迟到的旧产品响应'
}
} else {
data = body.id === foreignProduct.id ? foreignProduct : ownProduct
}
} else if (path === '/web/crm/products/update-status') {
ownProduct.status = body.status
data = true
} else if (path === '/web/crm/products/delete') {
data = true
} else if (path === '/web/admin/attachment/upload') {
data = {
id: 'upload-1',
fileName: 'new-product.png',
fileUrl: image,
fileSize: 16,
fileType: 'image/png'
}
} else {
unknownPaths.push(path)
code = 500
msg = `未模拟 API: ${path}`
}
await route.fulfill({
contentType: 'application/json',
body: JSON.stringify({ code, msg, data })
})
})
const lastCall = (path) => calls.findLast((item) => item.path === path)
async function assertNoOverflow(width) {
await page.setViewportSize({ width, height: 812 })
assert.equal(
await page.evaluate(() => document.documentElement.scrollWidth > innerWidth),
false,
`页面在 ${width}px 不应横向溢出`
)
}
async function hideDevtools() {
await page.addStyleTag({
content:
'vite-plugin-vue-devtools,#vue-devtools-container,.vue-devtools__anchor,.vue-devtools-frame,.vue-devtools__anchor-btn{display:none!important}'
})
}
try {
await page.goto(`${origin}/#/m/crm/product?mpTicket=product-fixture`)
await page.getByRole('heading', { name: '产品管理', exact: true }).waitFor()
await page.getByRole('button', { name: `查看产品:${ownProduct.productName}` }).waitFor()
await hideDevtools()
assert.deepEqual(await page.locator('.mp-wv-status-tabs button').allTextContents(), [
'全部',
'上架',
'下架'
])
const listOrder = await Promise.all(
['.mp-wv-header', '.mp-wv-status-tabs', '.mp-wv-filter-bar--three', '.mp-crm-expense-card'].map(
async (selector) => (await page.locator(selector).first().boundingBox())?.y ?? -1
)
)
assert.deepEqual(
[...listOrder].sort((a, b) => a - b),
listOrder
)
assert.equal(await page.locator('.mp-wv-filter-bar--three .mp-wv-filter-trig').count(), 3)
assert.equal(await page.locator('.mp-crm-expense-card .ec-amount').count(), 0)
const firstCard = page.locator('.mp-crm-expense-card').first()
for (const name of ['编辑', '下架', '删除']) {
assert.ok(await firstCard.getByRole('button', { name, exact: true }).isVisible())
}
for (const button of await firstCard.locator('.ec-bottom button').all()) {
const box = await button.boundingBox()
assert.ok(
(box?.width || 0) >= 44 && (box?.height || 0) >= 44,
`表单底栏命中尺寸:${JSON.stringify(box)}`
)
}
assert.ok(
await page
.locator('.mp-crm-expense-card')
.nth(1)
.getByRole('button', { name: '删除', exact: true })
.isDisabled()
)
await page.getByRole('button', { name: '快捷操作' }).click()
for (const name of ['产品分类', '新增产品']) {
const item = page.getByRole('button', { name, exact: true })
assert.ok(await item.isVisible())
const box = await item.boundingBox()
assert.ok((box?.width || 0) >= 44 && (box?.height || 0) >= 44)
}
await page.getByRole('button', { name: '快捷操作' }).click()
const search = page.getByRole('searchbox', { name: '搜索产品' })
await search.fill('甲醇')
await Promise.all([
page.waitForResponse((response) => response.url().endsWith('/web/crm/products/list')),
search.press('Enter')
])
assert.equal(lastCall('/web/crm/products/list').body.keyword, '甲醇')
await page.getByText('化工原料 / 醇类', { exact: true }).first().waitFor()
await Promise.all([
page.waitForResponse((response) => response.url().endsWith('/web/crm/products/list')),
search.fill('')
])
assert.equal(lastCall('/web/crm/products/list').body.keyword, undefined)
await page.getByRole('button', { name: '全部型号', exact: true }).click()
await Promise.all([
page.waitForResponse((response) => response.url().endsWith('/web/crm/products/list')),
page.getByRole('button', { name: '桶装(首屏外)', exact: true }).click()
])
assert.equal(lastCall('/web/crm/products/list').body.model, '桶装(首屏外)')
await page.getByRole('button', { name: '桶装(首屏外)', exact: true }).click()
await Promise.all([
page.waitForResponse((response) => response.url().endsWith('/web/crm/products/list')),
page.getByRole('button', { name: '全部型号', exact: true }).click()
])
await page.getByRole('button', { name: '全部分类', exact: true }).click()
await Promise.all([
page.waitForResponse((response) => response.url().endsWith('/web/crm/products/list')),
page.getByRole('button', { name: '化工原料 / 醇类', exact: true }).click()
])
assert.equal(lastCall('/web/crm/products/list').body.categoryId, 'category-2')
await Promise.all([
page.waitForResponse((response) => response.url().endsWith('/web/crm/products/list')),
page.locator('.mp-wv-status-tabs').getByRole('button', { name: '上架', exact: true }).click()
])
assert.equal(lastCall('/web/crm/products/list').body.statusIn, 'on')
await page.getByRole('button', { name: '更多', exact: true }).click()
const moreSheet = page.getByRole('dialog').filter({ hasText: '更多筛选' })
await moreSheet.locator('input[type="number"]').nth(0).fill('10')
await moreSheet.locator('input[type="number"]').nth(1).fill('30')
await Promise.all([
page.waitForResponse((response) => response.url().endsWith('/web/crm/products/list')),
moreSheet.getByRole('button', { name: '确定', exact: true }).click()
])
assert.equal(lastCall('/web/crm/products/list').body.priceMin, 10)
assert.equal(lastCall('/web/crm/products/list').body.priceMax, 30)
assert.equal(await page.locator('.mp-wv-filter-more__dot').count(), 1)
failNextPage2 = true
const loadMore = page.getByRole('button', { name: /加载更多/ })
await Promise.all([
page.waitForResponse((response) => response.url().endsWith('/web/crm/products/list')),
loadMore.click()
])
const pageError = page.locator('.mp-product-page-error[role="alert"]')
await pageError.getByText('分页测试失败', { exact: true }).waitFor()
await Promise.all([
page.waitForResponse((response) => response.url().endsWith('/web/crm/products/list')),
pageError.getByRole('button', { name: '重试加载', exact: true }).click()
])
const pageTwoCalls = calls.filter(
(item) => item.path === '/web/crm/products/list' && Number(item.body.page) === 2
)
assert.equal(pageTwoCalls.length, 2, '分页失败后重试必须仍请求第 2 页')
await firstCard.getByRole('button', { name: '下架', exact: true }).click()
await Promise.all([
page.waitForResponse((response) => response.url().endsWith('/web/crm/products/update-status')),
page.getByRole('button', { name: '确定', exact: true }).click()
])
assert.equal(lastCall('/web/crm/products/update-status').body.status, 'off')
await page.getByRole('dialog').waitFor({ state: 'hidden' })
await page.locator('.el-message').last().waitFor({ state: 'hidden' })
await page.evaluate(() => window.scrollTo(0, 0))
assert.equal(await page.locator('.el-overlay').filter({ visible: true }).count(), 0)
await assertNoOverflow(375)
await page.screenshot({ path: `${artifacts}/product-list-375.png`, fullPage: true })
await assertNoOverflow(414)
await page.screenshot({ path: `${artifacts}/product-list-414.png`, fullPage: true })
await page.goto(`${origin}/#/m/crm/product/${ownProduct.id}?mpTicket=product-detail-fixture`)
await page.getByRole('heading', { name: '产品详情', exact: true }).waitFor()
await page.reload()
await page.getByRole('heading', { name: '产品详情', exact: true }).waitFor()
await hideDevtools()
assert.equal(await page.locator('.mp-product-detail-tab').count(), 3)
assert.equal(await page.locator('.status-tag--info').filter({ hasText: '下架' }).count(), 1)
for (const button of await page.locator('.mp-wv-fab-bar button').all()) {
const box = await button.boundingBox()
assert.ok((box?.width || 0) >= 44 && (box?.height || 0) >= 44)
}
await page.getByRole('button', { name: '产品图片', exact: true }).click()
await page.locator('.mp-wv-img-grid__item').click()
await page.locator('.el-image-viewer__wrapper').waitFor()
await page.keyboard.press('Escape')
await page.locator('.el-image-viewer__wrapper').waitFor({ state: 'hidden' })
await assertNoOverflow(375)
await page.screenshot({ path: `${artifacts}/product-detail-375.png`, fullPage: true })
await assertNoOverflow(414)
await page.screenshot({ path: `${artifacts}/product-detail-414.png`, fullPage: true })
const slowRequest = page.waitForRequest((request) => {
if (!request.url().endsWith('/web/crm/products/detail')) return false
try {
return request.postDataJSON()?.id === 'product-slow'
} catch {
return false
}
})
const slowResponse = page.waitForResponse((response) => {
if (!response.url().endsWith('/web/crm/products/detail')) return false
try {
return response.request().postDataJSON()?.id === 'product-slow'
} catch {
return false
}
})
await page.evaluate(() => {
location.hash = '#/m/crm/product/product-slow?mpTicket=product-race-fixture'
})
await slowRequest
const fastResponse = page.waitForResponse((response) => {
if (!response.url().endsWith('/web/crm/products/detail')) return false
try {
return response.request().postDataJSON()?.id === 'product-1'
} catch {
return false
}
})
await page.evaluate(() => {
location.hash = '#/m/crm/product/product-1?mpTicket=product-race-fixture'
})
await fastResponse
await slowResponse
assert.ok(await page.getByText('CP-001', { exact: true }).isVisible())
assert.equal(await page.getByText('CP-SLOW', { exact: true }).count(), 0)
await page.goto(`${origin}/#/m/crm/product/${ownProduct.id}/edit?mpTicket=product-edit-fixture`)
await page.getByRole('heading', { name: '编辑产品', exact: true }).waitFor()
const formBack = page.getByRole('button', { name: '返回产品列表', exact: true })
const formBackBox = await formBack.boundingBox()
assert.ok((formBackBox?.width || 0) >= 44 && (formBackBox?.height || 0) >= 44)
for (const button of await page.locator('.mp-plan-form-footer button').all()) {
const box = await button.boundingBox()
assert.ok(
(box?.width || 0) >= 44 && (box?.height || 0) >= 30 && (box?.height || 0) <= 34,
`表单底栏按钮尺寸(可视高约30px):${JSON.stringify(box)}`
)
const hasIcon = await button.locator('.el-icon').count()
assert.equal(hasIcon, 0, '小程序产品表单底栏按钮不应带 icon')
}
for (const name of ['新增品牌', '新增别名', '重新生成']) {
const btn = page.getByRole('button', { name, exact: true })
assert.ok(await btn.isVisible(), `${name}应可见`)
const box = await btn.boundingBox()
assert.ok(
(box?.height || 0) >= 30 && (box?.height || 0) <= 34,
`${name}可视高约30px:${JSON.stringify(box)}`
)
assert.equal(await btn.locator('.el-icon').count(), 0, `${name}不应带 icon`)
}
const uploadCardBox = await page.locator('.attachment-upload .upload-card').boundingBox()
assert.ok(
Math.abs((uploadCardBox?.width || 0) - 72) <= 1,
`上传卡宽度:${JSON.stringify(uploadCardBox)}`
)
assert.ok(
Math.abs((uploadCardBox?.height || 0) - 72) <= 1,
`上传卡高度:${JSON.stringify(uploadCardBox)}`
)
const uploadInput = page.locator('.attachment-upload input[type="file"]').first()
await Promise.all([
page.waitForResponse((response) => response.url().endsWith('/web/admin/attachment/upload')),
uploadInput.setInputFiles({
name: 'new-product.png',
mimeType: 'image/png',
buffer: Buffer.from('fixture-product-image')
})
])
await page.locator('.attachment-name[title="new-product.png"]').waitFor({ state: 'attached' })
const uploadDeleteBox = await page.locator('.attachment-compact-delete').last().boundingBox()
assert.ok(
(uploadDeleteBox?.width || 0) >= 44 && (uploadDeleteBox?.height || 0) >= 44,
`上传删除命中尺寸:${JSON.stringify(uploadDeleteBox)}`
)
await page.locator('.attachment-item .attachment-preview').last().click()
const uploadPreview = page.getByRole('dialog', { name: 'new-product.png' })
await uploadPreview.waitFor()
await uploadPreview.locator('.el-dialog__headerbtn').click()
await uploadPreview.waitFor({ state: 'hidden' })
forbidNextList = true
await page.goto(`${origin}/#/m/crm/product?mpTicket=product-forbidden-fixture`)
await page.getByRole('heading', { name: '产品管理', exact: true }).waitFor()
assert.ok(await page.getByRole('button', { name: '返回工作台', exact: true }).isVisible())
await page.locator('.mp-wv-empty').getByText('无权限', { exact: true }).waitFor()
assert.equal(await page.locator('.el-overlay').filter({ visible: true }).count(), 0)
assert.deepEqual(pageErrors, [])
assert.deepEqual(unknownPaths, [], `存在未模拟 API:${unknownPaths.join(', ')}`)
console.log(`product Playwright: PASS\nscreenshots: ${artifacts}`)
} finally {
await browser.close()
}
@@ -0,0 +1,61 @@
import assert from 'node:assert/strict'
import { readFile } from 'node:fs/promises'
const root = new URL('../src/views/m/crm/quote/', import.meta.url)
const list = await readFile(new URL('MpQuoteList.vue', root), 'utf8')
const detail = await readFile(new URL('detail.vue', root), 'utf8')
const form = await readFile(new URL('form.vue', root), 'utf8')
const quoteScss = await readFile(new URL('quote.scss', root), 'utf8')
assert.match(list, /<MpBusinessHeader/, '报价列表须用 MpBusinessHeader')
assert.match(list, /van-tabs/, '报价列表须有状态 Tab')
assert.match(list, /van-dropdown-menu/, '报价列表须用三栏筛选')
assert.match(list, /mp-quote-list-card/, '报价列表须用扁平卡')
assert.match(list, /更多字段/, '报价卡须提供更多字段展开')
assert.doesNotMatch(list, /MpExpenseCard/, '报价列表不得再使用 MpExpenseCard')
assert.doesNotMatch(list, /MpStatusTabs/, '报价列表不得再使用 MpStatusTabs')
assert.doesNotMatch(list, /MpThreeColumnFilters/, '报价列表不得再使用 MpThreeColumnFilters')
assert.match(list, /mode === 'manage'/, 'Speed Dial 必须只在管理入口出现')
assert.match(list, /提交审批/, '管理草稿卡必须提供提交审批入口')
assert.match(list, /驳回/, '待审批卡必须提供驳回入口')
assert.match(list, /openDetailAction/, '列表动作必须复用详情状态机')
assert.match(
list,
/pendingApprovalUserId|buildQuoteListQuery/,
'审批入口必须保留当前用户待审批过滤'
)
assert.match(list, /approvedByUserId|buildQuoteListQuery/, '审批入口必须保留当前用户已审批过滤')
assert.match(list, /useIntersectionObserver/, '报价列表须滚动加载')
assert.doesNotMatch(list, /加载更多/, '报价列表不得使用加载更多按钮')
assert.match(list, /mp-wv-card-actions--single/, '单按钮卡片不得撑满整行')
assert.match(list, /van-date-picker/, '更多筛选日期须用 Vant 日期')
assert.match(detail, /title="报价单详情"/, '详情顶栏必须使用固定标题')
assert.doesNotMatch(detail, /\{\{\s*headerTitle\s*\}\}/, '详情顶栏不得使用记录标题')
assert.doesNotMatch(detail, /mp-wv-header__sub/, '详情顶栏不得展示副标题')
assert.match(detail, /class="mp-quote-detail-tabs"/, '详情必须提供业务 Tab')
assert.match(detail, /<van-tabs/, '详情 Tab 须为 van-tabs')
assert.match(detail, /<MpApprovalTimeline/, '审批信息必须使用共用时间轴')
assert.match(detail, /<MpAttachmentGrid/, '附件必须使用 72×72 共用宫格')
assert.match(detail, /mp-wv-fab-bar[\s\S]*mp-wv-touch-target/, '详情底栏按钮必须使用 44px 触达类')
assert.match(detail, /onAnchorTab/, '详情 Tab 须为锚点')
assert.match(detail, /--mp-quote-anchor-offset/, '详情锚点须避开吸顶 Tab')
assert.match(detail, /mp-quote-approve-sheet/, '通过/驳回须使用审批弹层')
assert.match(detail, /left-text="关闭"/, '审批弹层顶栏只保留关闭')
assert.match(
quoteScss,
/\.mp-quote-approve-sheet__foot \.van-button[\s\S]*min-height: 44px/,
'审批确认按钮触达须至少 44px'
)
assert.match(quoteScss, /#0a9f6d/, '审批弹层主色须为三墙绿')
assert.doesNotMatch(detail, /#10b981/, '审批详情不得使用 Fresh Mint 主色')
assert.match(detail, /返回报价单审批/, '审批入口返回文案须指向审批列表')
assert.match(detail, /别名/, '详情产品须含别名')
assert.match(quoteScss, /\.mp-quote-detail-page \.mp-wv-fab-bar[\s\S]*position: fixed/, '详情底栏须固定')
assert.match(quoteScss, /\.mp-quote-form-footer[\s\S]*position: fixed/, '表单底栏须固定')
assert.match(detail, /showCrmConfirmDialog/, '详情确认须走 CRM 确认弹窗')
assert.match(detail, /kind: 'danger'/, '删除/驳回须危险确认语义')
assert.match(form, /<MpBusinessHeader/, '表单外壳须用 MpBusinessHeader')
console.log('quote DOM contract: PASS')
+595
View File
@@ -0,0 +1,595 @@
import assert from 'node:assert/strict'
import { mkdir } from 'node:fs/promises'
import { chromium } from 'playwright'
// 本地 H5 交互回归:所有 API 均由 fixture 拦截,不写真实业务库。
const origin = process.env.QUOTE_TEST_ORIGIN || 'http://localhost:3006'
const artifacts = '/tmp/shanxia-quote-e2e'
await mkdir(artifacts, { recursive: true })
const browser = await chromium.launch({ headless: true, channel: 'chrome' })
const context = await browser.newContext({
viewport: { width: 375, height: 812 },
isMobile: true,
deviceScaleFactor: 1
})
const page = await context.newPage()
const pageErrors = []
const calls = []
page.on('pageerror', (error) => pageErrors.push(error.message))
const quote = {
id: 'quote-1',
quoteNo: 'BJ-20261017-001',
quoteTitle: '山峡化工年度报价',
quoteType: 'purchase',
customerId: 'customer-1',
customerName: '宜昌测试客户',
contactName: '张经理',
contactMobile: '13800138000',
version: 'V1',
parentId: '0',
isLatest: 1,
totalAmount: 128600,
discountRate: 95,
discountAmount: 6430,
finalAmount: 122170,
validityDays: 30,
quoteDate: '2026-10-17',
expireDate: '2026-11-16',
status: 'draft',
ownerUserId: 'user-1',
ownerUserName: '测试销售',
paymentTerms: '月结 30 天',
deliveryTerms: '送货上门',
freight: 500,
barrelDeposit: 1000,
attachments: JSON.stringify([{ ossId: '/fixtures/报价说明.pdf', category: 'other' }]),
remark: 'fixture 报价单',
createBy: 'user-1',
createTime: '2026-10-17 09:00:00',
productList: [
{
id: 'product-line-1',
standardProductName: '工业甲醇',
model: '优级品',
quantity: 10,
unit: 'ton',
price: 12000,
subtotal: 120000
}
]
}
let approvals = [
{
id: 'approval-1',
quoteId: quote.id,
quoteNo: quote.quoteNo,
step: 1,
approverId: 'user-1',
approverName: '测试审批人',
approvalResult: 'pending',
approvalOpinion: '',
approvalTime: '',
createTime: '2026-10-17 10:00:00'
}
]
let slowNextPage2 = false
let failNextPage2 = false
let forbidNextList = false
const dict = {
crm_quote_status: [
{ value: 'draft', label: '草稿', tagType: 'info' },
{ value: 'submitted', label: '待审批', tagType: 'warning' },
{ value: 'accepted', label: '已审批', tagType: 'success' },
{ value: 'rejected', label: '已驳回', tagType: 'danger' }
],
crm_product_unit: [{ value: 'ton', label: '吨', tagType: 'info' }]
}
await context.addInitScript(() => {
window.wx = {
miniProgram: {
navigateBack() {},
reLaunch() {},
getEnv(callback) {
callback({ miniprogram: true })
}
}
}
})
await context.route('**/api/**', async (route) => {
const request = route.request()
const url = new URL(request.url())
if (!url.pathname.startsWith('/api/')) return route.continue()
const path = url.pathname.replace(/^\/api/, '')
let body = {}
try {
body = request.postDataJSON() || {}
} catch {
// 非 JSON 请求不参与本用例的 body 断言。
}
calls.push({ path, body })
let data = {}
let code = 200
let msg = 'ok'
if (path === '/web/auth/mp-webview-exchange') {
data = {
token: 'fixture-token',
refreshToken: 'fixture-refresh',
userInfo: {
id: 'user-1',
userId: 'user-1',
userName: '测试用户',
role: 'admin',
roles: ['admin']
}
}
} else if (path === '/web/admin/dict-data/all') {
data = dict
} else if (path === '/web/admin/users/options') {
data = [{ value: 'user-1', label: '测试审批人', userNo: 'approver' }]
} else if (path === '/web/crm/quote/list') {
if (forbidNextList) {
forbidNextList = false
code = 403
msg = '无权限'
} else if (Number(body.pageNum ?? body.page) === 2 && failNextPage2) {
failNextPage2 = false
code = 500
msg = '分页测试失败'
} else {
if (Number(body.pageNum ?? body.page) === 2 && slowNextPage2) {
slowNextPage2 = false
await new Promise((resolve) => setTimeout(resolve, 350))
}
data = {
list:
Number(body.pageNum ?? body.page) === 2
? [{ ...quote, id: 'quote-2', quoteNo: 'BJ-002' }]
: [quote],
total: 21
}
}
} else if (path === '/web/crm/quote/detail') {
data = quote
} else if (path === '/web/crm/quote/product/list') {
data = { list: quote.productList, total: quote.productList.length }
} else if (path === '/web/crm/quote/approval/list') {
data = { list: approvals }
} else if (path === '/web/crm/quote-approver-setting/get') {
data = { approverIds: ['user-1'], status: '0' }
} else if (path === '/web/crm/quote/submit') {
quote.status = 'submitted'
data = true
} else if (path === '/web/crm/quote/approval/approve') {
approvals = approvals.map((item) => ({
...item,
approvalResult: body.approvalResult,
approvalOpinion: body.approvalOpinion,
approvalTime: '2026-10-17 11:00:00'
}))
quote.status = body.approvalResult === 'approved' ? 'accepted' : 'rejected'
data = true
} else if (path === '/web/crm/quote/invalid' || path === '/web/crm/quote/delete') {
data = true
} else if (path === '/web/crm/quote/versions') {
data = [quote]
} else if (path === '/web/admin/attachment/preview-url') {
data = { previewUrl: 'about:blank#quote-preview' }
}
await route.fulfill({
contentType: 'application/json',
body: JSON.stringify({ code, msg, data })
})
})
const click = (name) =>
page.getByRole('button', { name, exact: true }).filter({ visible: true }).click({ force: true })
const lastCall = (path) => calls.findLast((item) => item.path === path)
async function openMoreSheet() {
await page.locator('.mp-wv-fab-bar .mp-wv-btn-more:visible').click({ force: true })
const sheet = page.getByRole('dialog').filter({ hasText: '更多操作' })
await sheet.waitFor()
return sheet
}
async function assertNoOverflow(width) {
await page.setViewportSize({ width, height: 812 })
assert.equal(
await page.evaluate(() => document.documentElement.scrollWidth > innerWidth),
false,
`页面在 ${width}px 不应横向溢出`
)
}
async function assertTouchTarget(locator, label) {
const box = await locator.boundingBox()
assert.ok((box?.width || 0) >= 44, `${label} 宽度应至少 44px`)
assert.ok((box?.height || 0) >= 44, `${label} 高度应至少 44px`)
}
try {
await page.goto(`${origin}/#/m/crm/quote?mpTicket=quote-manage-fixture`)
await page.getByRole('heading', { name: '报价单管理', exact: true }).waitFor()
await page.getByRole('button', { name: `查看报价单:${quote.quoteTitle}` }).waitFor()
const listOrder = await Promise.all(
['.mp-wv-header', '.mp-quote-view-tabs', '.mp-quote-dd', '.mp-quote-list-card'].map(
async (selector) => (await page.locator(selector).first().boundingBox())?.y ?? -1
)
)
assert.deepEqual(
[...listOrder].sort((a, b) => a - b),
listOrder
)
assert.ok(await page.locator('.mp-quote-dd .van-dropdown-menu__item').count() >= 3)
assert.equal(await page.locator('.mp-wv-speed-dial').count(), 1)
const firstManageCard = page.locator('.mp-quote-list-card').first()
assert.ok(await firstManageCard.getByText('更多字段', { exact: true }).isVisible())
assert.ok(await firstManageCard.getByRole('button', { name: '复制', exact: true }).isVisible())
assert.ok(
await firstManageCard.getByRole('button', { name: '提交审批', exact: true }).isVisible()
)
assert.ok(await firstManageCard.getByRole('button', { name: '查看', exact: true }).isVisible())
await assertTouchTarget(
page.getByRole('button', { name: '加载更多', exact: true }),
'加载更多'
)
await click('快捷操作')
await assertTouchTarget(
page.getByRole('button', { name: '新增报价单', exact: true }),
'Speed Dial 新增报价单'
)
await click('快捷操作')
const search = page.getByRole('searchbox', { name: '搜索报价单' })
await search.fill('临时检索')
const searchCallsBeforeEnter = calls.filter((item) => item.path === '/web/crm/quote/list').length
await Promise.all([
page.waitForResponse((response) => response.url().endsWith('/web/crm/quote/list')),
search.press('Enter')
])
assert.equal(
calls.filter((item) => item.path === '/web/crm/quote/list').length,
searchCallsBeforeEnter + 1
)
assert.equal(lastCall('/web/crm/quote/list').body.keyword, '临时检索')
await Promise.all([
page.waitForResponse((response) => response.url().endsWith('/web/crm/quote/list')),
search.fill('')
])
assert.equal(lastCall('/web/crm/quote/list').body.keyword, undefined)
await click('全部类型')
await Promise.all([
page.waitForResponse((response) => response.url().endsWith('/web/crm/quote/list')),
click('采购')
])
assert.equal(lastCall('/web/crm/quote/list').body.quoteType, 'purchase')
await click('更多')
const filterSheet = page.getByRole('dialog').filter({ hasText: '更多筛选' })
assert.ok(await filterSheet.getByText('报价日期', { exact: true }).isVisible())
assert.ok(await filterSheet.getByText('金额(元)', { exact: true }).isVisible())
await filterSheet.locator('input[type="search"]').fill('年度')
await filterSheet.locator('input[type="date"]').nth(0).fill('2026-10-01')
await filterSheet.locator('input[type="date"]').nth(1).fill('2026-10-31')
await filterSheet.locator('input[type="number"]').nth(0).fill('100')
await filterSheet.locator('input[type="number"]').nth(1).fill('200000')
await assertTouchTarget(
filterSheet.getByRole('button', { name: '确定', exact: true }),
'筛选确定'
)
await Promise.all([
page.waitForResponse((response) => response.url().endsWith('/web/crm/quote/list')),
filterSheet.getByRole('button', { name: '确定', exact: true }).click()
])
assert.deepEqual(
{
keyword: lastCall('/web/crm/quote/list').body.keyword,
quoteDateBegin: lastCall('/web/crm/quote/list').body.quoteDateBegin,
quoteDateEnd: lastCall('/web/crm/quote/list').body.quoteDateEnd,
minAmount: lastCall('/web/crm/quote/list').body.minAmount,
maxAmount: lastCall('/web/crm/quote/list').body.maxAmount
},
{
keyword: '年度',
quoteDateBegin: '2026-10-01',
quoteDateEnd: '2026-10-31',
minAmount: 100,
maxAmount: 200000
}
)
slowNextPage2 = true
const stalePageRequest = page.waitForRequest(
(request) =>
request.url().endsWith('/web/crm/quote/list') && request.postDataJSON()?.pageNum === 2
)
void click('加载更多')
await stalePageRequest
await click('采购')
await Promise.all([
page.waitForResponse((response) => response.url().endsWith('/web/crm/quote/list')),
click('销售')
])
await page.waitForTimeout(450)
assert.equal(await page.getByText('BJ-002', { exact: true }).count(), 0)
failNextPage2 = true
await Promise.all([
page.waitForResponse((response) => response.url().endsWith('/web/crm/quote/list')),
click('加载更多')
])
await page.getByText('分页测试失败', { exact: true }).waitFor()
assert.ok(await page.getByRole('button', { name: '加载更多', exact: true }).isVisible())
await click('加载更多')
await page.getByText('BJ-002', { exact: true }).waitFor()
assert.equal(lastCall('/web/crm/quote/list').body.pageNum, 2)
await click('快捷操作')
assert.ok(await page.getByRole('button', { name: '新增报价单', exact: true }).isVisible())
await click('快捷操作')
await page.waitForFunction(() => document.querySelectorAll('.el-message').length === 0)
await page.screenshot({ path: `${artifacts}/manage-list-375.png`, fullPage: true })
await assertNoOverflow(375)
await firstManageCard.getByRole('button', { name: '复制', exact: true }).click()
await page.waitForURL(/\/m\/crm\/quote\/new\?copyFrom=quote-1/)
await page.goto(`${origin}/#/m/crm/quote?mpTicket=quote-manage-actions`)
await page.getByRole('heading', { name: '报价单管理', exact: true }).waitFor()
await firstManageCard.getByRole('button', { name: '提交审批', exact: true }).click()
await page.getByRole('heading', { name: '报价单详情', exact: true }).waitFor()
const submitSheet = page.getByRole('dialog').filter({ hasText: '提交审批' })
await submitSheet.waitFor()
await assertTouchTarget(
submitSheet.getByRole('button', { name: '确认提交', exact: true }),
'提交审批确认'
)
assert.doesNotMatch(page.url(), /action=/)
await submitSheet.getByRole('button', { name: '关闭', exact: true }).click()
assert.equal(await page.locator('.mp-wv-header').getByText(quote.quoteTitle).count(), 0)
assert.equal(await page.locator('.mp-wv-header__sub').count(), 0)
for (const button of await page.locator('.mp-wv-fab-bar .mp-wv-btn').all()) {
const box = await button.boundingBox()
assert.ok((box?.width || 0) >= 44 && (box?.height || 0) >= 44)
}
await click('编辑')
await page.waitForURL(/\/m\/crm\/quote\/quote-1\/edit/)
await page.goBack()
await page.getByRole('heading', { name: '报价单详情', exact: true }).waitFor()
let actionSheet = await openMoreSheet()
const deleteAction = actionSheet.getByRole('button', { name: '删除', exact: true })
assert.equal(await deleteAction.isDisabled(), false)
await deleteAction.click()
const deleteDialog = page.getByRole('dialog', { name: '提示', exact: true })
await deleteDialog.getByRole('button', { name: '取消', exact: true }).click()
await deleteDialog.waitFor({ state: 'hidden' })
await actionSheet.waitFor({ state: 'hidden' })
actionSheet = await openMoreSheet()
await actionSheet.getByRole('button', { name: '作废', exact: true }).click()
const voidDialog = page.getByRole('dialog', { name: '作废报价单', exact: true })
await voidDialog.getByRole('button', { name: '取消', exact: true }).click()
await voidDialog.waitFor({ state: 'hidden' })
await actionSheet.waitFor({ state: 'hidden' })
actionSheet = await openMoreSheet()
await actionSheet.getByRole('button', { name: '复制新增', exact: true }).click()
await page.waitForURL(/\/m\/crm\/quote\/new\?copyFrom=quote-1/)
await page.goBack()
await page.getByRole('heading', { name: '报价单详情', exact: true }).waitFor()
actionSheet = await openMoreSheet()
await actionSheet.getByRole('button', { name: '版本历史', exact: true }).click()
await page.waitForURL(/\/m\/crm\/quote\/quote-1\/versions/)
await page.getByRole('heading', { name: '版本历史', exact: true }).waitFor()
await page.goBack()
await page.getByRole('heading', { name: '报价单详情', exact: true }).waitFor()
await click('产品明细')
await page.getByText('工业甲醇', { exact: true }).waitFor()
await click('审批信息')
await page.locator('.mp-crm-approval-timeline').waitFor()
await click('附件')
const attachment = page.locator('.mp-crm-att-grid .att-item').first()
const attachmentBox = await attachment.boundingBox()
assert.equal(Math.round(attachmentBox?.width || 0), 72)
assert.equal(Math.round(attachmentBox?.height || 0), 72)
assert.ok(await page.getByText('报价说明.pdf', { exact: true }).isVisible())
await Promise.all([
page.waitForResponse((response) =>
response.url().endsWith('/web/admin/attachment/preview-url')
),
attachment.locator('.att-preview').click()
])
assert.equal(lastCall('/web/admin/attachment/preview-url').body.fileName, '报价说明.pdf')
const previewDialog = page.getByRole('dialog', { name: '报价说明.pdf', exact: true })
await previewDialog.waitFor()
await previewDialog.locator('.el-dialog__headerbtn').click()
await previewDialog.waitFor({ state: 'hidden' })
await page
.locator('.mp-quote-detail-tab')
.filter({ hasText: '基础信息' })
.evaluate((button) => button.click())
await page.getByText(quote.quoteNo, { exact: true }).waitFor()
await page.waitForFunction(() => document.querySelectorAll('.el-message').length === 0)
await page.screenshot({ path: `${artifacts}/manage-detail-375.png`, fullPage: true })
await click('提交审批')
await page.getByRole('dialog').filter({ hasText: '提交审批' }).waitFor()
await click('确认提交')
await page.getByText('待审批', { exact: true }).filter({ visible: true }).first().waitFor()
assert.deepEqual(lastCall('/web/crm/quote/submit').body.approverIds, ['user-1'])
approvals = [
{
...approvals[0],
id: 'approval-prior',
step: '1',
approverId: 'user-2',
approverName: '前置审批人',
approvalResult: 'pending'
},
{
...approvals[0],
id: 'approval-current',
step: 2,
approverId: 'user-1',
approverName: '测试审批人',
approvalResult: 'pending'
}
]
await page.goto(`${origin}/#/m/crm/quote/quote-1?from=approve&mpTicket=quote-direct-fixture`)
await page.getByRole('heading', { name: '报价单详情', exact: true }).waitFor()
await page.reload()
await page.getByRole('heading', { name: '报价单详情', exact: true }).waitFor()
assert.equal(await page.getByRole('button', { name: '通过', exact: true }).count(), 0)
assert.equal(await page.getByRole('button', { name: '驳回', exact: true }).count(), 0)
approvals = [
{
...approvals[0],
id: 'approval-rejected-prior',
step: 1,
approverId: 'user-2',
approvalResult: 'rejected'
},
{
...approvals[1],
id: 'approval-current-after-rejected',
step: 2,
approverId: 'user-1',
approvalResult: 'pending'
}
]
await page.reload()
await page.getByRole('heading', { name: '报价单详情', exact: true }).waitFor()
assert.equal(await page.getByRole('button', { name: '通过', exact: true }).count(), 0)
assert.equal(await page.getByRole('button', { name: '驳回', exact: true }).count(), 0)
approvals = [
{
...approvals[1],
id: 'approval-1',
step: 1,
approvalResult: 'pending'
}
]
quote.status = 'draft'
await page.reload()
await page.getByRole('heading', { name: '报价单详情', exact: true }).waitFor()
assert.equal(await page.getByRole('button', { name: '通过', exact: true }).count(), 0)
assert.equal(await page.getByRole('button', { name: '驳回', exact: true }).count(), 0)
quote.status = 'submitted'
await page.goto(`${origin}/#/m/crm/quote/approval?mpTicket=quote-approve-fixture`)
await page.getByRole('heading', { name: '报价单审批', exact: true }).waitFor()
await page.getByRole('button', { name: `查看报价单:${quote.quoteTitle}` }).waitFor()
assert.equal(await page.locator('.mp-wv-speed-dial').count(), 0)
assert.equal(lastCall('/web/crm/quote/list').body.pendingApprovalUserId, 'user-1')
let approvalCard = page.locator('.mp-quote-list-card').first()
for (const label of ['驳回', '通过']) {
const button = approvalCard.getByRole('button', { name: label, exact: true })
assert.ok(await button.isVisible())
}
await approvalCard.getByRole('button', { name: '驳回', exact: true }).click()
await page.getByRole('heading', { name: '报价单详情', exact: true }).waitFor()
assert.match(page.url(), /from=approve/)
const rejectSheet = page.getByRole('dialog').filter({ hasText: '驳回报价单' })
await rejectSheet.waitFor()
const approveCallsBeforeRequired = calls.filter(
(item) => item.path === '/web/crm/quote/approval/approve'
).length
const rejectConfirm = rejectSheet.getByRole('button', { name: '确认驳回', exact: true })
await assertTouchTarget(rejectConfirm, '驳回确认')
await rejectConfirm.evaluate((button) => button.click())
await page.getByText('驳回时请填写拒绝理由', { exact: true }).waitFor()
assert.equal(
calls.filter((item) => item.path === '/web/crm/quote/approval/approve').length,
approveCallsBeforeRequired
)
await rejectSheet.locator('textarea').fill('资料不完整')
await rejectConfirm.evaluate((button) => button.click())
const rejectDialog = page.locator('.van-dialog.mp-crm-dialog').filter({ hasText: '确认驳回' })
await rejectDialog.waitFor()
await rejectDialog.getByRole('button', { name: '确认驳回', exact: true }).click()
await rejectDialog.waitFor({ state: 'hidden' })
await rejectSheet.waitFor({ state: 'hidden' })
assert.equal(lastCall('/web/crm/quote/approval/approve').body.approvalResult, 'rejected')
assert.equal(lastCall('/web/crm/quote/approval/approve').body.approvalOpinion, '资料不完整')
quote.status = 'submitted'
approvals = [
{
...approvals[0],
id: 'approval-1',
step: 1,
approvalResult: 'pending',
approvalOpinion: '',
approvalTime: ''
}
]
await page.goto(`${origin}/#/m/crm/quote/approval?mpTicket=quote-approve-again`)
await page.getByRole('heading', { name: '报价单审批', exact: true }).waitFor()
approvalCard = page.locator('.mp-quote-list-card').first()
await approvalCard.getByRole('button', { name: '通过', exact: true }).click()
const approveSheet = page.getByRole('dialog').filter({ hasText: '通过报价单' })
await approveSheet.waitFor()
const approveConfirm = approveSheet.getByRole('button', { name: '确认通过', exact: true })
await assertTouchTarget(approveConfirm, '通过确认')
await approveConfirm.evaluate((button) => button.click())
const confirmDialog = page.locator('.van-dialog.mp-crm-dialog').filter({ hasText: '确认通过' })
await confirmDialog.waitFor()
await confirmDialog.getByRole('button', { name: '确认', exact: true }).click()
await confirmDialog.waitFor({ state: 'hidden' })
await approveSheet.waitFor({ state: 'hidden' })
await page.getByText('已审批', { exact: true }).filter({ visible: true }).first().waitFor()
assert.equal(lastCall('/web/crm/quote/approval/approve').body.id, 'approval-1')
assert.equal(lastCall('/web/crm/quote/approval/approve').body.approvalResult, 'approved')
await page.waitForFunction(() => document.querySelectorAll('.el-message').length === 0)
await assertNoOverflow(414)
await page.screenshot({ path: `${artifacts}/approve-detail-414.png`, fullPage: true })
await page.getByRole('button', { name: '返回报价单审批', exact: true }).click()
await page.getByRole('heading', { name: '报价单审批', exact: true }).waitFor()
assert.match(page.url(), /\/m\/crm\/quote\/approval/)
await Promise.all([
page.waitForResponse((response) => response.url().endsWith('/web/crm/quote/list')),
click('已审批')
])
assert.equal(lastCall('/web/crm/quote/list').body.approvedByUserId, 'user-1')
assert.equal(await page.getByRole('button', { name: '驳回', exact: true }).count(), 0)
assert.equal(await page.getByRole('button', { name: '通过', exact: true }).count(), 0)
await page.screenshot({ path: `${artifacts}/approve-list-414.png`, fullPage: true })
forbidNextList = true
await page.goto(`${origin}/#/m/crm/quote?mpTicket=quote-forbidden-fixture`)
await page.getByText('无权限', { exact: true }).waitFor()
assert.equal(await page.locator('.mp-quote-list-card').count(), 0)
assert.equal(await page.locator('.mp-wv-speed-dial').count(), 0)
assert.deepEqual(pageErrors, [])
console.log(
JSON.stringify({
result: 'PASS',
assertions:
'管理/审批列表与卡片动作、搜索清空、更多筛选、分页乱序与失败回滚、独立详情直达刷新、列表/Speed Dial/Sheet/FAB 44px触达、空操作底栏、最早审批步骤与前置驳回/报价状态门禁、驳回必填与通过、附件解析预览、403、375/414布局',
apiCalls: calls.length,
screenshots: artifacts
})
)
} catch (error) {
await page.screenshot({ path: `${artifacts}/failure.png`, fullPage: true })
console.error(await page.locator('body').innerText())
console.error('Page errors:', pageErrors)
console.error('API calls:', calls)
throw error
} finally {
await browser.close()
}
+660
View File
@@ -0,0 +1,660 @@
import { chromium } from 'playwright'
import assert from 'node:assert/strict'
import { mkdir } from 'node:fs/promises'
import { installCertFixture } from './mp-pl-plan-cert-fixture.mjs'
const origin = process.env.PLAN_CERT_TEST_ORIGIN || 'http://localhost:3006'
const artifacts = '/tmp/shanxia-plan-cert-e2e'
await mkdir(artifacts, { recursive: true })
const browser = await chromium.launch({ headless: true, channel: 'chrome' })
const context = await browser.newContext({ viewport: { width: 375, height: 812 }, isMobile: true })
await context.addInitScript(() => {
const start = () => {
const root = document.documentElement
if (!root) return
const hide = () => {
const el = document.getElementById('__vue-devtools-container__')
if (el) el.style.setProperty('display', 'none', 'important')
}
hide()
new MutationObserver(hide).observe(root, { childList: true, subtree: true })
}
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', start)
else start()
})
const fixture = await installCertFixture(context)
const page = await context.newPage()
const pageErrors = []
let releaseLinkedList
page.on('pageerror', (error) => pageErrors.push(error.message))
page.setDefaultTimeout(12000)
const button = (name) => page.getByRole('button', { name, exact: true }).filter({ visible: true })
const card = (id) => page.locator(`.cert-card[data-plan-id="plan-${id}"]`)
const sheet = (title) =>
page.locator('.van-popup, .mp-sheet').filter({
has: page.getByText(title, { exact: true }),
visible: true
})
const noOverflow = async (scope, label) =>
assert.ok(await scope.evaluate((el) => el.scrollWidth <= el.clientWidth + 1), `${label} 横向溢出`)
const assertCenteredSheetActions = async (scope, label) => {
const actions = scope.locator('.mp-customer-filter-vant__foot')
const styles = await actions.evaluate((el) => {
const buttons = [...el.querySelectorAll('button')].map((button) => ({
height: button.getBoundingClientRect().height
}))
return { buttons }
})
assert.equal(styles.buttons.length, 2, `${label}底栏必须保留重置和确定`)
for (const style of styles.buttons) {
assert.ok(style.height >= 30, `${label}按钮须与报价单筛选底栏同高`)
}
}
const waitPatch = (suffix, action) =>
Promise.all([
page.waitForResponse((r) => r.request().method() === 'PATCH' && r.url().endsWith(suffix)),
action()
])
const cleanScreenshot = async (name) => {
await page.locator('.el-message').last().waitFor({ state: 'hidden' })
await page.screenshot({ path: `${artifacts}/${name}.png`, animations: 'disabled' })
}
const latestList = () => fixture.calls.filter((c) => c.path === '/transport/plan/').at(-1)
const quickDate = () => page.locator('.mp-customer-dd .van-dropdown-menu__item').nth(0)
const quickReady = () => page.locator('.mp-customer-dd .van-dropdown-menu__item').nth(1)
const quickMore = () => page.locator('.mp-customer-dd .van-dropdown-menu__item').nth(2)
const quickOption = (label) =>
page.locator('.van-dropdown-item__option').filter({ hasText: label }).first()
const waitList = (action) =>
Promise.all([
page.waitForResponse((r) => new URL(r.url()).pathname === '/api/transport/plan/'),
action()
])
try {
await page.goto(`${origin}/#/m/pl/plan-cert/plan-1?mpTicket=cert-fixture`)
const directDetail = page.locator('.cert-detail-page')
await directDetail.getByText('YS001', { exact: true }).waitFor()
await page.reload()
await directDetail.getByText('YS001', { exact: true }).waitFor()
assert.equal(
await directDetail.getByRole('heading', { name: '危化品证详情', exact: true }).count(),
1,
'独立详情必须支持携带 mpTicket 直达和刷新'
)
await page.goto(`${origin}/#/m/pl/plan-cert?mpTicket=cert-fixture`)
const tabs = ['未上传证书', '全部', '入库单', '出库单', '直销单']
await page.getByRole('tab', { name: tabs[0], exact: true }).waitFor()
const header = page.locator('.mp-wv-header')
assert.equal(await header.count(), 1, '列表必须复用标准 mp-wv-header')
assert.equal(await page.locator('.cert-header').count(), 0, '不得保留自定义 cert-header')
assert.equal(await header.locator('.mp-wv-header__sub').count(), 0, '标准列表顶栏不得显示副标题')
assert.equal(
await header.locator('.mp-wv-search').count(),
1,
'检索框必须放在绿顶栏内、状态 Tab 下方'
)
assert.equal(
await header.locator('.mp-customer-view-tabs').count(),
1,
'状态 Tab 必须放在绿顶栏内'
)
assert.equal(await page.locator('.cert-search-bar').count(), 0, '不得另做检索条')
assert.equal(
await header.locator('h1').evaluate((el) => getComputedStyle(el).fontSize),
'17px',
'页面标题字号必须与标准一致'
)
assert.deepEqual(await page.getByRole('tab').allTextContents(), tabs)
assert.deepEqual(
(await page.locator('.mp-customer-dd .van-dropdown-menu__title').allTextContents()).map((text) =>
text.replace(/\s+/g, '')
),
['全部日期', '全部齐备状态', '更多'],
'检索框下方必须紧跟日期、齐备状态、更多三栏筛选'
)
const headerBox = await header.boundingBox()
const tabsBox = await header.locator('.mp-customer-view-tabs').boundingBox()
const searchBox = await header.locator('.mp-wv-search').boundingBox()
const filterBox = await header.locator('.mp-customer-dd').boundingBox()
assert.ok(tabsBox.y >= headerBox.y, '状态 Tab 必须落在绿顶栏区域内')
assert.ok(tabsBox.y + tabsBox.height <= headerBox.y + headerBox.height + 1, '状态 Tab 不得溢出绿顶栏')
assert.ok(tabsBox.y + tabsBox.height <= searchBox.y + 1, '状态 Tab 必须在检索框上方')
assert.ok(searchBox.y < filterBox.y, '检索框必须在三栏筛选上方')
assert.ok(searchBox.y + searchBox.height <= filterBox.y + 1, '检索框与三栏筛选必须紧贴')
assert.ok(filterBox.y + filterBox.height <= headerBox.y + headerBox.height + 1, '三栏筛选必须落在绿顶栏内')
assert.equal(Math.round(headerBox.x), 0, '绿顶栏必须横向铺满视口')
assert.equal(Math.round(headerBox.width), 375, '绿顶栏不得叠加 Shell 左右留白')
for (const [label, box] of [
['检索框', searchBox],
['三栏筛选', filterBox]
]) {
assert.ok(box.x >= headerBox.x, `${label}必须落在绿顶栏内`)
assert.ok(box.x + box.width <= headerBox.x + headerBox.width + 1, `${label}不得溢出绿顶栏`)
}
assert.equal(await page.locator('.cert-shortcuts').count(), 0, '不得保留横向日期 Chip')
assert.equal(await page.locator('.cert-tools').count(), 0, '不得保留筛选/刷新/重置工具条')
await page.getByText('YS001', { exact: true }).first().waitFor()
assert.ok(await card(1).evaluate((el) => el.classList.contains('expense-card')))
const listCardBox = await card(1).boundingBox()
assert.ok(listCardBox.x >= 10, '列表卡片左右必须留白')
assert.ok(listCardBox.width <= 355, '列表卡片不得铺满视口')
const summary = page.locator('.cert-total').filter({ hasText: /共 \d+ 条计划/ })
assert.equal(await summary.count(), 1, '列表底部必须展示条数汇总')
const summaryBox = await summary.boundingBox()
assert.ok(summaryBox.y > listCardBox.y, '条数汇总必须在列表卡片之后')
assert.equal(await card(1).locator('.ec-top').count(), 1)
assert.equal(await card(1).locator('.list-card-kv').count(), 1)
assert.equal(await card(1).locator('.ec-bottom').count(), 1)
assert.equal(latestList().params.hasHazardProduct, '1')
assert.equal(latestList().params.certUploadStatus, 'incomplete')
assert.equal(latestList().params.hazardCertReady, '0')
assert.ok(!latestList().params.followStatus.split(',').includes('cancelled'))
const firstStatusTabBox = await page
.getByRole('tab', { name: '未上传证书', exact: true })
.boundingBox()
assert.ok(firstStatusTabBox.height >= 44, '状态 Tab 命中高度必须至少为 44px')
assert.ok(
await page.getByRole('tab', { name: '未上传证书', exact: true }).evaluate((el) => {
const text = el.querySelector('.van-tab__text') || el
const line = el.closest('.van-tabs')?.querySelector('.van-tabs__line')
const textBox = text.getBoundingClientRect()
const lineBox = line?.getBoundingClientRect()
return (
getComputedStyle(text).whiteSpace === 'nowrap' &&
textBox.height < 28 &&
!!lineBox &&
lineBox.top >= textBox.bottom
)
}),
'未上传证书必须单行显示,下划线在文字下方'
)
await quickReady().click()
await waitList(() => quickOption('已齐备').click())
assert.equal(
await page.getByRole('tab', { name: '全部', exact: true }).getAttribute('aria-selected'),
'true',
'未上传 Tab 选择已齐备后必须切换到全部,避免展示条件与请求冲突'
)
assert.equal(latestList().params.hazardCertReady, '1')
await waitList(() => page.getByRole('tab', { name: '未上传证书', exact: true }).click())
assert.equal(await button('导出').count(), 0)
for (const [label, type] of [
['全部', undefined],
['入库单', 'inbound'],
['出库单', 'outbound'],
['直销单', 'direct']
]) {
await waitList(() => page.getByRole('tab', { name: label, exact: true }).click())
assert.equal(latestList().params.planType, type)
assert.equal(latestList().params.hasHazardProduct, '1')
assert.equal(latestList().params.certUploadStatus, undefined)
}
await waitList(() => page.getByRole('tab', { name: '全部', exact: true }).click())
await quickReady().click()
await waitList(() => quickOption('未齐备').click())
assert.equal(latestList().params.hazardCertReady, '0')
await quickReady().click()
await waitList(() => quickOption('全部齐备状态').click())
assert.equal(latestList().params.hazardCertReady, undefined)
for (const width of [375, 414]) {
await page.setViewportSize({ width, height: 812 })
assert.ok(
await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth),
`列表 ${width}px 横向溢出`
)
await page.screenshot({ path: `${artifacts}/list-${width}.png`, fullPage: true })
}
await page.setViewportSize({ width: 375, height: 812 })
await page.getByRole('checkbox', { name: '选择 YS001', exact: true }).check()
await quickDate().click()
await waitList(() => quickOption('今天').click())
assert.equal(latestList().params.planDateFrom, new Date().toLocaleDateString('sv-SE'))
assert.equal(
await page.getByRole('checkbox', { name: '选择 YS001', exact: true }).isChecked(),
false
)
await page.getByRole('searchbox', { name: '搜索计划' }).fill('YS002')
await waitList(() => page.getByRole('searchbox', { name: '搜索计划' }).press('Enter'))
assert.equal(latestList().params.q, 'YS002')
await card(2).waitFor()
assert.equal(await page.locator('.cert-card').count(), 1)
await page.getByRole('searchbox', { name: '搜索计划' }).fill('')
await waitList(() => page.getByRole('searchbox', { name: '搜索计划' }).press('Enter'))
// 同一筛选面板覆盖动态枚举、日期、数值、文本、合同侧别与排序。
await quickMore().click()
const filter = sheet('更多筛选')
assert.ok(await filter.locator('.filter-chip').count(), '更多筛选中的静态枚举必须使用 Chip')
const field = (label) =>
filter.locator('.el-form-item').filter({ has: page.getByText(label, { exact: true }) })
await field('车牌号').locator('.el-select').click()
await page.getByRole('option', { name: '鄂E12345', exact: true }).waitFor()
const facetCall = fixture.calls.filter((c) => c.path.endsWith('column-facet-values')).at(-1)
assert.equal(facetCall.body.planDateFrom, new Date().toLocaleDateString('sv-SE'))
await field('车牌号').locator('.el-select').click()
await field('计划日期').locator('input').nth(0).fill('2026-10-20')
await field('计划日期').locator('input').nth(1).fill('2026-10-01')
await button('确定').click()
await page.getByText('计划日期开始不能晚于结束', { exact: true }).waitFor()
assert.equal(await filter.isVisible(), true)
await field('计划日期').locator('input').nth(0).fill('2026-10-01')
await field('计划日期').locator('input').nth(1).fill('2026-10-31')
await field('人员').locator('input').fill('测试司机')
await filter.getByRole('spinbutton', { name: '计划量最小值' }).fill('5')
await filter.getByRole('spinbutton', { name: '计划量最大值' }).fill('20')
await field('装货客户').locator('.el-select').click()
await page.getByRole('option', { name: '测试供应商', exact: true }).click()
await field('装货客户').locator('.el-select').click()
await field('合同').locator('.el-select').click()
await page.getByRole('option', { name: '供', exact: true }).click()
await page.getByRole('option', { name: 'HT-001', exact: true }).click()
await field('合同').locator('.el-select').click()
await field('排序字段').locator('.el-select').click()
await page.getByRole('option', { name: '计划日期', exact: true }).click()
assert.equal(
await field('排序字段')
.locator('input')
.evaluate((el) => getComputedStyle(el).backgroundColor),
'rgba(0, 0, 0, 0)',
'select内部输入不得用白底遮住选中标签'
)
for (const width of [375, 414]) {
await page.setViewportSize({ width, height: 812 })
await noOverflow(filter.locator('.mp-customer-filter-vant__body'), `筛选${width}`)
await cleanScreenshot(`filters-${width}`)
}
await assertCenteredSheetActions(filter, '筛选Sheet')
await waitList(() => button('确定').click())
assert.equal(latestList().params.planDateFrom, '2026-10-01')
assert.equal(latestList().params.personnelSummary, '测试司机')
assert.equal(latestList().params.productPlanQtyMin, '5')
assert.equal(latestList().params.productPlanQtyMax, '20')
assert.equal(latestList().params.stopKindIn, 'load')
assert.equal(latestList().params.contractNoIn, 'HT-001')
assert.match(latestList().params.stopCustomers, /测试供应商/)
assert.equal(latestList().params.sortField, 'planDate')
await quickMore().click()
await waitList(() => button('重置').click())
await waitList(() => page.getByRole('tab', { name: '未上传证书', exact: true }).click())
await page.setViewportSize({ width: 375, height: 812 })
await card(24).waitFor()
assert.ok(
fixture.calls.some(
(call) =>
call.path === '/transport/plan/' &&
call.params.page === '2' &&
call.params.certUploadStatus === 'incomplete' &&
call.params.q == null
),
'滚到底必须沿用当前已提交的查询请求下一页'
)
assert.equal(await page.locator('.cert-card').count(), 22)
assert.equal(await button('加载更多').count(), 0, '不得再使用加载更多按钮')
// 请求乱序:慢入库响应不能覆盖后发的出库页。
let releaseList
const listGate = new Promise((resolve) => {
releaseList = resolve
})
fixture.listDelay = (params) => (params.planType === 'inbound' ? listGate : undefined)
await page.getByRole('tab', { name: '入库单', exact: true }).click()
await waitList(() => page.getByRole('tab', { name: '出库单', exact: true }).click())
await card(2).waitFor()
await Promise.all([
page.waitForResponse((r) => new URL(r.url()).searchParams.get('planType') === 'inbound'),
Promise.resolve().then(() => releaseList())
])
fixture.listDelay = null
assert.equal(await card(1).count(), 0)
await waitList(() => page.getByRole('tab', { name: '未上传证书', exact: true }).click())
// 逐项读取最新状态,批量报告成功/失败/跳过。
assert.equal(
await card(4).getByRole('button', { name: '上传证书', exact: true }).isDisabled(),
true
)
for (const id of [1, 2, 4])
await page.getByRole('checkbox', { name: `选择 YS00${id}`, exact: true }).check()
fixture.failReadyIds = ['plan-2']
await page.locator('.cert-batch').getByRole('button', { name: '证书齐备', exact: true }).click()
await button('确认齐备').waitFor()
await waitList(() => button('确认齐备').click())
await page.getByText('成功 1 条,失败 1 条,跳过 1 条', { exact: true }).waitFor()
assert.equal(fixture.plans[0].hazardCertReady, 1)
assert.equal(fixture.plans[1].hazardCertReady, 0)
assert.equal(fixture.calls.filter((c) => c.path.endsWith('hazard-cert-ready')).length, 2)
fixture.failReadyIds = []
await waitList(() => page.getByRole('tab', { name: '全部', exact: true }).click())
await card(1).getByRole('button', { name: '取消齐备', exact: true }).click()
await waitList(() => button('确认取消').click())
assert.equal(fixture.plans[0].hazardCertReady, 0)
// 上传只提交证书白名单;阻止上传中保存/关闭,失败保留数据可重试。
fixture.plans[0].products[0].purchaseCertUrl = '/fixtures/existing.pdf'
await card(1).getByRole('button', { name: '上传证书', exact: true }).click()
const upload = sheet('上传证书')
await upload.locator('input[type=file]').first().waitFor({ state: 'attached' })
assert.equal(await upload.locator('input[type=file]').count(), 3)
await upload.locator('.attachment-item').first().waitFor()
const firstAttachmentBox = await upload.locator('.attachment-item').first().boundingBox()
const uploadCardBox = await upload.locator('.upload-card').first().boundingBox()
assert.equal(Math.round(firstAttachmentBox.width), 72, '附件项宽度必须为 72px')
assert.equal(Math.round(firstAttachmentBox.height), 72, '附件项高度必须为 72px')
assert.equal(Math.round(uploadCardBox.width), 72, '上传入口宽度必须为 72px')
assert.equal(Math.round(uploadCardBox.height), 72, '上传入口高度必须为 72px')
const attachmentLayout = await upload
.locator('.attachment-list')
.first()
.evaluate((list) => ({
list: list.getBoundingClientRect().toJSON(),
display: getComputedStyle(list).display,
flexDirection: getComputedStyle(list).flexDirection,
gap: getComputedStyle(list).gap,
children: [...list.children].map((child) => child.getBoundingClientRect().toJSON())
}))
assert.equal(
Math.round(attachmentLayout.children[0].y),
Math.round(attachmentLayout.children[1].y),
`上传入口必须作为宫格首项与已上传附件同行:${JSON.stringify(attachmentLayout)}`
)
assert.equal(await upload.locator('.attachment-preview__ext').first().textContent(), 'PDF')
assert.equal(await upload.locator('.attachment-preview__ext').first().isVisible(), true)
assert.equal(await upload.locator('.attachment-name').first().isVisible(), true)
assert.equal(await upload.locator('.attachment-name').first().textContent(), 'existing.pdf')
let releaseUpload
fixture.uploadGate = new Promise((resolve) => {
releaseUpload = resolve
})
await upload
.locator('input[type=file]')
.first()
.setInputFiles({
name: '测试证书.pdf',
mimeType: 'application/pdf',
buffer: Buffer.from('%PDF-1.4\n%%EOF')
})
await upload.locator('.is-uploading').waitFor()
const certWrites = () => fixture.calls.filter((c) => c.path.endsWith('product-certs'))
await upload.getByRole('button', { name: '保存证书', exact: true }).click()
await page.getByText('附件正在上传,请稍候再保存', { exact: true }).waitFor()
assert.equal(certWrites().length, 0)
await upload.locator('.van-nav-bar__left').click()
assert.equal(await upload.isVisible(), true)
releaseUpload()
fixture.uploadGate = null
await upload.locator('.is-uploading').waitFor({ state: 'detached' })
await noOverflow(upload.locator('.mp-customer-filter-vant__body'), '上传sheet')
const saveBox = await upload.getByRole('button', { name: '保存证书', exact: true }).boundingBox()
assert.ok(saveBox.height >= 44, '上传确认按钮命中高度必须至少44px')
assert.ok(saveBox.y + saveBox.height >= 760, '上传确认按钮必须贴在视口底部')
const editAttachment = upload.locator('.attachment-item').first()
const editDownload = editAttachment.locator('[title="下载"]')
const editDelete = editAttachment.locator('[title="删除"]')
const [editDownloadBox, editDeleteBox] = await Promise.all([
editDownload.boundingBox(),
editDelete.boundingBox()
])
assert.ok(editDownloadBox.width >= 44 && editDownloadBox.height >= 44)
assert.ok(editDeleteBox.width >= 44 && editDeleteBox.height >= 44)
assert.ok(
editDownloadBox.x + editDownloadBox.width <= editDeleteBox.x ||
editDeleteBox.x + editDeleteBox.width <= editDownloadBox.x ||
editDownloadBox.y + editDownloadBox.height <= editDeleteBox.y ||
editDeleteBox.y + editDeleteBox.height <= editDownloadBox.y,
`编辑态附件的下载与删除命中区不得重叠:${JSON.stringify({ editDownloadBox, editDeleteBox })}`
)
await cleanScreenshot('upload-375')
// 预览、下载、删除卡片(删除后取消不写业务记录)。
await upload
.locator('.attachment-preview')
.first()
.click({ position: { x: 10, y: 10 } })
const preview = page.getByRole('dialog', { name: 'existing.pdf', exact: true })
await preview.waitFor()
assert.ok((await preview.boundingBox()).width <= 375)
await preview.screenshot({
path: `${artifacts}/attachment-preview-375.png`,
animations: 'disabled'
})
await preview.locator('.el-dialog__headerbtn').click()
const download = page.waitForEvent('download')
await upload.locator('[title="下载"]').first().click()
assert.equal((await download).suggestedFilename(), 'existing.pdf')
fixture.failSave = true
await waitPatch('product-certs', () =>
upload.getByRole('button', { name: '保存证书', exact: true }).click()
)
await upload.getByText('保存失败,已保留填写内容,请重试', { exact: true }).waitFor()
assert.equal(await upload.locator('.attachment-item').count(), 2)
await waitPatch('product-certs', () =>
upload.getByRole('button', { name: '保存证书', exact: true }).click()
)
for (const p of certWrites().at(-1).body.products)
assert.deepEqual(
Object.keys(p).sort(),
['id', 'legalUseCertUrl', 'purchaseCertUrl', 'transportCertUrl'].sort()
)
assert.match(fixture.plans[0].products[0].purchaseCertUrl, /existing\.pdf/)
assert.match(fixture.plans[0].products[0].purchaseCertUrl, /cert\.pdf/)
await page.waitForURL(/#\/m\/pl\/plan-cert\/plan-1(?:\?|$)/)
const detail = page.locator('.cert-detail-page')
await detail.getByText('证书迁移测试备注', { exact: true }).waitFor()
assert.equal(await sheet('计划详情').count(), 0, '详情不得继续使用 Bottom Sheet')
assert.equal(
await detail.locator('[class*="ticket-"]').count(),
0,
'详情不得显示票根或顶部特殊区'
)
assert.equal(await detail.locator('.mp-wv-header__sub').count(), 0, '详情顶栏不得显示记录摘要')
assert.equal(
await detail.getByRole('heading', { name: '危化品证详情', exact: true }).count(),
1,
'详情必须使用固定标准标题'
)
assert.deepEqual(await detail.getByRole('tab').allTextContents(), [
'基础信息',
'运输与段次',
'证书与附件'
])
await noOverflow(detail, '计划详情')
await cleanScreenshot('detail-375')
await page.setViewportSize({ width: 414, height: 812 })
await noOverflow(detail, '计划详情414')
await cleanScreenshot('detail-414')
// 详情页独立编排上传、齐备与取消齐备,成功后原位刷新而不返回列表。
const detailUrl = page.url()
await detail.getByRole('button', { name: '上传证书', exact: true }).click()
await upload.locator('input[type=file]').first().waitFor({ state: 'attached' })
await waitPatch('product-certs', () =>
upload.getByRole('button', { name: '保存证书', exact: true }).click()
)
assert.equal(page.url(), detailUrl, '详情上传成功后必须停留在原详情路由')
await detail.getByRole('button', { name: '证书齐备', exact: true }).click()
await button('确认齐备').waitFor()
await waitPatch('hazard-cert-ready', () => button('确认齐备').click())
assert.equal(page.url(), detailUrl, '详情标记齐备后必须停留在原详情路由')
await detail.getByRole('button', { name: '取消齐备', exact: true }).click()
await button('确认取消').waitFor()
await waitPatch('hazard-cert-ready', () => button('确认取消').click())
assert.equal(page.url(), detailUrl, '详情取消齐备后必须停留在原详情路由')
await detail.getByRole('button', { name: '返回危化品证列表', exact: true }).click()
await page.waitForURL(/#\/m\/pl\/plan-cert(?:\?|$)/)
await card(1).getByRole('button', { name: '上传证书', exact: true }).click()
await upload.locator('.attachment-item').first().waitFor()
await upload.locator('[title="删除"]').first().click()
assert.equal(await upload.locator('.attachment-item').count(), 1)
await cleanScreenshot('upload-414')
const writesBeforeCancel = certWrites().length
await upload.locator('.van-nav-bar__left').click()
assert.equal(certWrites().length, writesBeforeCancel)
assert.match(fixture.plans[0].products[0].purchaseCertUrl, /existing\.pdf/)
// 合同仅查看;列表合同入口通过独立详情路由打开,关联计划仍留在详情页。
await card(1).locator('summary').click()
await card(1).getByRole('button', { name: 'HT-001', exact: true }).first().click()
const contract = sheet('合同详情(只读)')
await contract.getByText('测试账号001', { exact: true }).waitFor()
await contract.getByText('测试关联商机', { exact: true }).waitFor()
await contract.getByText('BJ-001', { exact: true }).waitFor()
await contract.getByText(/别名 测试别名/).waitFor()
assert.equal(await contract.getByText('金额统计', { exact: true }).count(), 0)
assert.equal(await contract.locator('.attachment-item').count(), 2)
await noOverflow(contract.locator('.mp-sheet-body'), '合同详情')
await contract.getByRole('button', { name: 'YS002', exact: true }).click()
await page.waitForURL(/#\/m\/pl\/plan-cert\/plan-2(?:\?|$)/)
await detail.getByText('YS002', { exact: true }).waitFor()
await detail.getByRole('button', { name: '返回危化品证列表', exact: true }).click()
await page.waitForURL(/#\/m\/pl\/plan-cert(?:\?|$)/)
// 价格权限仅开启合同金额展示,不引入编辑或审批动作。
fixture.codes.push('pl:contract:view-product-price')
await page.reload()
await card(1).waitFor()
await card(1).locator('summary').click()
await card(1).getByRole('button', { name: 'HT-001', exact: true }).first().click()
await contract.getByRole('heading', { name: '金额统计', exact: true }).waitFor()
assert.equal(await contract.getByRole('button', { name: /编辑|审批|作废/ }).count(), 0)
await contract.getByRole('button', { name: '关闭', exact: true }).click()
await detail.getByRole('button', { name: '返回危化品证列表', exact: true }).click()
await page.waitForURL(/#\/m\/pl\/plan-cert(?:\?|$)/)
// 已安排计划的回传和复制动作;未安排计划不显示复制运输摘要。
await card(7).getByRole('button', { name: '查看详情', exact: true }).click()
await detail.getByRole('tab', { name: '运输与段次', exact: true }).click()
await detail.getByText('司机回传测试备注', { exact: true }).first().waitFor()
const feedbackCard = detail.locator('.pl-stop-feedback-ticket__attach .attachment-item').first()
const feedbackPreview = feedbackCard.locator('.attachment-preview')
const feedbackDownload = feedbackCard.locator('.attachment-compact-download')
await feedbackPreview.scrollIntoViewIfNeeded()
const previewBox = await feedbackPreview.boundingBox(),
downloadBox = await feedbackDownload.boundingBox()
assert.ok(previewBox.width >= 44 && previewBox.height >= 44)
assert.ok(downloadBox.width >= 44 && downloadBox.height >= 44)
assert.ok(downloadBox.y >= previewBox.y + previewBox.height, '反馈下载与预览触达区不得重叠')
await feedbackPreview.click()
const feedbackDialog = page.getByRole('dialog', { name: 'driver.png', exact: true })
await feedbackDialog.locator('img').waitFor()
await feedbackDialog.screenshot({
path: `${artifacts}/feedback-preview-414.png`,
animations: 'disabled'
})
await feedbackDialog.locator('.el-dialog__headerbtn').click()
const feedbackFile = page.waitForEvent('download')
await feedbackDownload.click()
assert.equal((await feedbackFile).suggestedFilename(), 'driver.png')
await detail.getByRole('button', { name: '复制司机链接', exact: true }).click()
assert.equal(await page.evaluate(() => window.__copiedText), 'https://example.test/driver')
await detail.getByRole('button', { name: '复制给司机', exact: true }).click()
assert.match(await page.evaluate(() => window.__copiedText), /测试易制毒产品/)
await detail.getByRole('button', { name: '复制给现场', exact: true }).click()
assert.match(await page.evaluate(() => window.__copiedText), /https:\/\/example.test\/site/)
await detail.getByRole('button', { name: '复制磅单二维码', exact: true }).click()
await page.locator('.pound-qr-panel img').waitFor()
await noOverflow(page.locator('.pound-qr-panel'), '磅单二维码')
await page.locator('.pound-qr-panel').getByRole('button', { name: '关闭' }).click()
await detail.getByRole('button', { name: '返回危化品证列表', exact: true }).click()
await page.waitForURL(/#\/m\/pl\/plan-cert(?:\?|$)/)
// 切换合同时,旧合同未结束的关联查询不能阻止新合同查询。
const secondPlan = fixture.plans[1]
for (const stop of [secondPlan.load, ...secondPlan.deliveries]) {
for (const c of stop.contracts) {
c.contractId = 'contract-2'
c.contractNo = 'HT-002'
}
for (const p of stop.products) {
p.contractId = 'contract-2'
p.contractNo = 'HT-002'
}
}
await page.reload()
await card(1).waitFor()
fixture.linkedListGate = new Promise((resolve) => {
releaseLinkedList = resolve
})
await card(1).locator('summary').click()
await Promise.all([
page.waitForRequest((r) => new URL(r.url()).searchParams.get('contractId') === 'contract-1'),
card(1).getByRole('button', { name: 'HT-001', exact: true }).first().click()
])
await contract.getByRole('button', { name: '关闭', exact: true }).click()
await detail.getByRole('button', { name: '返回危化品证列表', exact: true }).click()
await page.waitForURL(/#\/m\/pl\/plan-cert(?:\?|$)/)
await card(2).locator('summary').click()
await card(2).getByRole('button', { name: 'HT-002', exact: true }).first().click()
await contract.getByRole('heading', { name: 'HT-002', exact: true }).waitFor()
assert.ok(
fixture.calls.some(
(c) => c.path === '/transport/plan/' && c.params.contractId === 'contract-2'
),
'新合同必须发起自己的关联列表请求'
)
await contract.getByRole('button', { name: 'YS002', exact: true }).waitFor()
releaseLinkedList()
fixture.linkedListGate = null
await contract.getByRole('button', { name: '关闭', exact: true }).click()
await detail.getByRole('button', { name: '返回危化品证列表', exact: true }).click()
await page.waitForURL(/#\/m\/pl\/plan-cert(?:\?|$)/)
fixture.failList = true
await card(2).locator('summary').click()
await card(2).getByRole('button', { name: 'HT-002', exact: true }).first().click()
await contract.getByRole('button', { name: '重试关联计划', exact: true }).waitFor()
await waitList(() => contract.getByRole('button', { name: '重试关联计划', exact: true }).click())
assert.equal(latestList().params.contractId, 'contract-2')
assert.equal(latestList().params.page, '1')
await contract.getByRole('button', { name: 'YS002', exact: true }).waitFor()
await contract.getByRole('button', { name: '关闭', exact: true }).click()
await detail.getByRole('button', { name: '返回危化品证列表', exact: true }).click()
await page.waitForURL(/#\/m\/pl\/plan-cert(?:\?|$)/)
// 独立详情在只读/权限失败时仍先展示 Tab,且不暴露写操作。
fixture.codes = ['mini:pl:plan-cert:list']
await page.goto(`${origin}/#/m/pl/plan-cert/plan-1`)
const readonlyDetail = page.locator('.cert-detail-page')
await readonlyDetail.getByText('当前仅有查看权限', { exact: true }).waitFor()
assert.equal(await readonlyDetail.locator('.cert-detail-actions').count(), 0)
assert.equal(
await readonlyDetail.locator('.detail-tabs').evaluate(
(tabs, hint) => {
return Boolean(tabs.compareDocumentPosition(hint) & Node.DOCUMENT_POSITION_FOLLOWING)
},
await readonlyDetail.getByText('当前仅有查看权限', { exact: true }).elementHandle()
),
true,
'权限提示必须下沉到详情 Tab 之后'
)
fixture.failPermissions = true
await page.reload()
await readonlyDetail.getByRole('button', { name: '重试权限', exact: true }).waitFor()
assert.equal(await readonlyDetail.locator('.cert-detail-actions').count(), 0)
fixture.failPermissions = false
await readonlyDetail.getByRole('button', { name: '重试权限', exact: true }).click()
await readonlyDetail.getByText('当前仅有查看权限', { exact: true }).waitFor()
// 列表同样在只读/权限失败时关闭上传与齐备入口。
await page.goto(`${origin}/#/m/pl/plan-cert`)
await page.getByText('当前仅有查看权限', { exact: true }).waitFor()
assert.equal(await button('上传证书').count(), 0)
assert.equal(await button('证书齐备').count(), 0)
fixture.failPermissions = true
await page.reload()
await button('重试权限').waitFor()
assert.equal(await button('上传证书').count(), 0)
fixture.failPermissions = false
await button('重试权限').click()
await page.getByText('当前仅有查看权限', { exact: true }).waitFor()
assert.deepEqual(fixture.unknown, [])
assert.deepEqual(pageErrors, [])
console.log(JSON.stringify({ result: 'passed', calls: fixture.calls.length, artifacts }))
} catch (error) {
console.error(error)
await page.screenshot({ path: `${artifacts}/failure.png`, fullPage: true })
console.error(
JSON.stringify({ pageErrors, unknown: fixture.unknown, recent: fixture.calls.slice(-5) })
)
throw error
} finally {
releaseLinkedList?.()
await context.close()
await browser.close()
}
@@ -0,0 +1,103 @@
import assert from 'node:assert/strict'
import { chromium } from 'playwright'
import { installCertFixture } from './mp-pl-plan-cert-fixture.mjs'
// 挂载真实 Web 弹窗与附件组件,仅替换 API 边界,不写入业务数据库。
const origin = process.env.PLAN_CERT_TEST_ORIGIN || 'http://localhost:3006'
const browser = await chromium.launch({ headless: true, channel: 'chrome' })
const context = await browser.newContext({ viewport: { width: 1440, height: 1000 } })
const fixture = await installCertFixture(context)
const page = await context.newPage()
const errors = []
page.on('pageerror', (error) => errors.push(error.message))
page.setDefaultTimeout(15000)
let releaseUpload
const saves = () =>
fixture.calls.filter((c) => c.method === 'PATCH' && c.path.endsWith('/product-certs'))
try {
await page.goto(`${origin}/#/m/pl/plan-cert?mpTicket=cert-fixture`)
await page.getByText('YS001', { exact: true }).first().waitFor()
await page.evaluate(async () => {
const { createVNode, render, defineComponent, ref, h } = await import(
'/node_modules/.vite/deps/vue.js'
)
const { default: Dialog } = await import(
'/src/components/business/pl-plan-cert-upload-dialog/index.vue'
)
const host = document.createElement('div')
document.body.appendChild(host)
const Wrapper = defineComponent({
setup() {
const visible = ref(true)
return () => [
h(
'button',
{
id: 'reopen-web-cert',
onClick: () => {
visible.value = true
}
},
'重新打开 Web 证书'
),
h(Dialog, {
visible: visible.value,
planId: 'plan-1',
'onUpdate:visible': (v) => {
visible.value = v
}
})
]
}
})
const vnode = createVNode(Wrapper)
vnode.appContext = document.querySelector('#app').__vue_app__._context
render(vnode, host)
})
const dialog = page.getByRole('dialog').filter({ hasText: '上传危化品证书' })
await dialog.getByText('测试易制毒产品', { exact: true }).waitFor()
assert.equal(await dialog.locator('input[type="file"]').count(), 3)
// 使用最后一个产品的附件,确保保护覆盖所有嵌套循环中的上传组件。
fixture.uploadGate = new Promise((resolve) => {
releaseUpload = resolve
})
await dialog
.locator('input[type="file"]')
.last()
.setInputFiles({
name: 'legal-cert.pdf',
mimeType: 'application/pdf',
buffer: Buffer.from('%PDF-1.4\nfixture')
})
await dialog.locator('.is-uploading').waitFor()
await dialog.getByRole('button', { name: '保存', exact: true }).click()
// toast 表明真实处理函数已完成,不以固定等待推断没有请求。
await page
.getByText(/^(附件正在上传,请稍候再保存|证书保存成功)$/)
.first()
.waitFor()
assert.equal(saves().length, 0, '附件未上传完成时不能提交旧 URL')
assert.equal(
await page.getByText('附件正在上传,请稍候再保存', { exact: true }).isVisible(),
true
)
assert.equal(await dialog.isVisible(), true)
releaseUpload()
await dialog.locator('.is-uploading').waitFor({ state: 'hidden' })
await dialog.getByRole('button', { name: '保存', exact: true }).click()
await dialog.waitFor({ state: 'hidden' })
assert.equal(saves().length, 1)
assert.ok(JSON.stringify(saves()[0].body).includes('/fixtures/cert.pdf'))
// 关闭销毁后重新打开,不遗留上传引用;正常保存仍可用。
await page.locator('#reopen-web-cert').click()
await dialog.getByText('测试易制毒产品', { exact: true }).waitFor()
await dialog.getByRole('button', { name: '保存', exact: true }).click()
await dialog.waitFor({ state: 'hidden' })
assert.equal(saves().length, 2)
assert.deepEqual(errors, [])
assert.deepEqual(fixture.unknown, [])
console.log('PASS: Web 附件上传中阻止保存、上传后提交新 URL、销毁重开正常保存')
} finally {
releaseUpload?.()
await browser.close()
}