order-management.page.ts 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579
  1. import { TIMEOUTS } from '../../utils/timeouts';
  2. import { Page, Locator } from '@playwright/test';
  3. import { selectRadixOption } from '@d8d/e2e-test-utils';
  4. /**
  5. * 订单状态常量
  6. */
  7. export const ORDER_STATUS = {
  8. DRAFT: 'draft',
  9. CONFIRMED: 'confirmed',
  10. IN_PROGRESS: 'in_progress',
  11. COMPLETED: 'completed',
  12. } as const;
  13. /**
  14. * 订单状态类型
  15. */
  16. export type OrderStatus = typeof ORDER_STATUS[keyof typeof ORDER_STATUS];
  17. /**
  18. * 订单状态显示名称映射
  19. */
  20. export const ORDER_STATUS_LABELS: Record<OrderStatus, string> = {
  21. draft: '草稿',
  22. confirmed: '已确认',
  23. in_progress: '进行中',
  24. completed: '已完成',
  25. } as const;
  26. /**
  27. * 工作状态常量
  28. */
  29. export const WORK_STATUS = {
  30. NOT_WORKING: 'not_working',
  31. PRE_WORKING: 'pre_working',
  32. WORKING: 'working',
  33. RESIGNED: 'resigned',
  34. } as const;
  35. /**
  36. * 工作状态类型
  37. */
  38. export type WorkStatus = typeof WORK_STATUS[keyof typeof WORK_STATUS];
  39. /**
  40. * 工作状态显示名称映射
  41. */
  42. export const WORK_STATUS_LABELS: Record<WorkStatus, string> = {
  43. not_working: '未入职',
  44. pre_working: '已入职',
  45. working: '工作中',
  46. resigned: '已离职',
  47. } as const;
  48. /**
  49. * 订单数据接口
  50. */
  51. export interface OrderData {
  52. /** 订单名称 */
  53. name: string;
  54. /** 预计开始日期 */
  55. expectedStartDate?: string;
  56. /** 平台ID */
  57. platformId?: number;
  58. /** 平台名称 */
  59. platformName?: string;
  60. /** 公司ID */
  61. companyId?: number;
  62. /** 公司名称 */
  63. companyName?: string;
  64. /** 渠道ID */
  65. channelId?: number;
  66. /** 渠道名称 */
  67. channelName?: string;
  68. /** 订单状态 */
  69. status?: OrderStatus;
  70. /** 工作状态 */
  71. workStatus?: WorkStatus;
  72. }
  73. /**
  74. * 订单人员数据接口
  75. */
  76. export interface OrderPersonData {
  77. /** 残疾人ID */
  78. disabledPersonId: number;
  79. /** 残疾人姓名 */
  80. disabledPersonName?: string;
  81. /** 入职日期 */
  82. hireDate?: string;
  83. /** 薪资 */
  84. salary?: number;
  85. /** 工作状态 */
  86. workStatus?: WorkStatus;
  87. /** 实际入职日期 */
  88. actualHireDate?: string;
  89. /** 离职日期 */
  90. resignDate?: string;
  91. }
  92. /**
  93. * 网络响应数据接口
  94. */
  95. export interface NetworkResponse {
  96. /** 请求URL */
  97. url: string;
  98. /** 请求方法 */
  99. method: string;
  100. /** 响应状态码 */
  101. status: number;
  102. /** 是否成功 */
  103. ok: boolean;
  104. /** 响应头 */
  105. responseHeaders: Record<string, string>;
  106. /** 响应体 */
  107. responseBody: unknown;
  108. }
  109. /**
  110. * 表单提交结果接口
  111. */
  112. export interface FormSubmitResult {
  113. /** 提交是否成功 */
  114. success: boolean;
  115. /** 是否有错误 */
  116. hasError: boolean;
  117. /** 是否有成功消息 */
  118. hasSuccess: boolean;
  119. /** 错误消息 */
  120. errorMessage?: string;
  121. /** 成功消息 */
  122. successMessage?: string;
  123. /** 网络响应列表 */
  124. responses?: NetworkResponse[];
  125. }
  126. /**
  127. * 订单管理 Page Object
  128. *
  129. * 用于订单管理功能的 E2E 测试
  130. * 页面路径: /admin/orders(待确认)
  131. *
  132. * @example
  133. * ```typescript
  134. * const orderPage = new OrderManagementPage(page);
  135. * await orderPage.goto();
  136. * await orderPage.createOrder({ name: '测试订单' });
  137. * ```
  138. */
  139. export class OrderManagementPage {
  140. readonly page: Page;
  141. // ===== 页面级选择器 =====
  142. /** 页面标题 */
  143. readonly pageTitle: Locator;
  144. /** 新增订单按钮 */
  145. readonly addOrderButton: Locator;
  146. /** 订单列表表格 */
  147. readonly orderTable: Locator;
  148. /** 搜索输入框 */
  149. readonly searchInput: Locator;
  150. /** 搜索按钮 */
  151. readonly searchButton: Locator;
  152. constructor(page: Page) {
  153. this.page = page;
  154. // 初始化页面级选择器
  155. // 使用更精确的选择器来定位页面标题(避免与侧边栏按钮冲突)
  156. this.pageTitle = page.locator('[data-slot="card-title"]').getByText('订单管理', { exact: true });
  157. // 使用 data-testid 定位创建订单按钮(按钮文本是"创建订单"不是"新增订单")
  158. this.addOrderButton = page.getByTestId('create-order-button');
  159. this.orderTable = page.locator('table');
  160. // 使用 data-testid 定位搜索输入框
  161. this.searchInput = page.getByTestId('search-order-name-input');
  162. // 使用 data-testid 定位搜索按钮
  163. this.searchButton = page.getByTestId('search-button');
  164. }
  165. // ===== 导航和基础验证 =====
  166. /**
  167. * 导航到订单管理页面
  168. */
  169. async goto() {
  170. await this.page.goto('/admin/orders');
  171. await this.page.waitForLoadState('domcontentloaded');
  172. // 等待页面标题出现
  173. await this.pageTitle.waitFor({ state: 'visible', timeout: TIMEOUTS.PAGE_LOAD });
  174. // 等待表格数据加载
  175. await this.page.waitForSelector('table tbody tr', { state: 'visible', timeout: TIMEOUTS.PAGE_LOAD_LONG });
  176. await this.expectToBeVisible();
  177. }
  178. /**
  179. * 验证页面关键元素可见
  180. */
  181. async expectToBeVisible() {
  182. await this.pageTitle.waitFor({ state: 'visible', timeout: TIMEOUTS.PAGE_LOAD });
  183. await this.addOrderButton.waitFor({ state: 'visible', timeout: TIMEOUTS.TABLE_LOAD });
  184. }
  185. // ===== 搜索和筛选功能 =====
  186. /**
  187. * 按订单名称搜索
  188. * @param name 订单名称
  189. */
  190. async searchByName(name: string) {
  191. await this.searchInput.fill(name);
  192. await this.searchButton.click();
  193. await this.page.waitForLoadState('networkidle');
  194. await this.page.waitForTimeout(TIMEOUTS.LONG);
  195. }
  196. /**
  197. * 打开高级筛选对话框
  198. */
  199. async openFilterDialog() {
  200. const filterButton = this.page.getByRole('button', { name: /筛选|高级筛选/ });
  201. await filterButton.click();
  202. await this.page.waitForSelector('[role="dialog"]', { state: 'visible', timeout: TIMEOUTS.DIALOG });
  203. }
  204. /**
  205. * 设置筛选条件
  206. * @param filters 筛选条件
  207. */
  208. async setFilters(filters: {
  209. status?: OrderStatus;
  210. workStatus?: WorkStatus;
  211. platformId?: number;
  212. platformName?: string;
  213. companyId?: number;
  214. companyName?: string;
  215. channelId?: number;
  216. channelName?: string;
  217. dateRange?: { start?: string; end?: string };
  218. }) {
  219. // 订单状态筛选
  220. if (filters.status) {
  221. const statusFilter = this.page.getByLabel(/订单状态/);
  222. await statusFilter.click();
  223. const statusLabel = ORDER_STATUS_LABELS[filters.status];
  224. await this.page.getByRole('option', { name: statusLabel }).click();
  225. }
  226. // 工作状态筛选
  227. if (filters.workStatus) {
  228. const workStatusFilter = this.page.getByLabel(/工作状态/);
  229. await workStatusFilter.click();
  230. const workStatusLabel = WORK_STATUS_LABELS[filters.workStatus];
  231. await this.page.getByRole('option', { name: workStatusLabel }).click();
  232. }
  233. // 平台筛选
  234. if (filters.platformName) {
  235. await selectRadixOption(this.page, '平台', filters.platformName);
  236. }
  237. // 公司筛选
  238. if (filters.companyName) {
  239. await selectRadixOption(this.page, '公司', filters.companyName);
  240. }
  241. // 渠道筛选
  242. if (filters.channelName) {
  243. await selectRadixOption(this.page, '渠道', filters.channelName);
  244. }
  245. // 日期范围筛选
  246. if (filters.dateRange) {
  247. if (filters.dateRange.start) {
  248. const startDateInput = this.page.getByLabel(/开始日期|起始日期/);
  249. await startDateInput.fill(filters.dateRange.start);
  250. }
  251. if (filters.dateRange.end) {
  252. const endDateInput = this.page.getByLabel(/结束日期|截止日期/);
  253. await endDateInput.fill(filters.dateRange.end);
  254. }
  255. }
  256. }
  257. /**
  258. * 应用筛选条件
  259. */
  260. async applyFilters() {
  261. const applyButton = this.page.getByRole('button', { name: /应用|确定|筛选/ });
  262. await applyButton.click();
  263. await this.page.waitForLoadState('networkidle');
  264. await this.page.waitForTimeout(TIMEOUTS.LONG);
  265. }
  266. /**
  267. * 清空筛选条件
  268. */
  269. async clearFilters() {
  270. const clearButton = this.page.getByRole('button', { name: /重置|清空/ });
  271. await clearButton.click();
  272. await this.page.waitForTimeout(TIMEOUTS.MEDIUM);
  273. }
  274. // ===== 订单 CRUD 操作 =====
  275. /**
  276. * 打开创建订单对话框
  277. */
  278. async openCreateDialog() {
  279. await this.addOrderButton.click();
  280. await this.page.waitForSelector('[role="dialog"]', { state: 'visible', timeout: TIMEOUTS.DIALOG });
  281. }
  282. /**
  283. * 打开编辑订单对话框
  284. * @param orderName 订单名称
  285. */
  286. async openEditDialog(orderName: string) {
  287. // 找到订单行并点击"打开菜单"按钮
  288. const orderRow = this.orderTable.locator('tbody tr').filter({ hasText: orderName });
  289. const menuButton = orderRow.getByRole('button', { name: '打开菜单' });
  290. await menuButton.click();
  291. // 等待菜单出现并点击"编辑"选项
  292. // 使用 data-testid 或 role 定位编辑选项
  293. const editOption = this.page.getByRole('menuitem', { name: '编辑' });
  294. await editOption.waitFor({ state: 'visible', timeout: TIMEOUTS.ELEMENT_VISIBLE_SHORT });
  295. await editOption.click();
  296. // 等待编辑对话框出现
  297. await this.page.waitForSelector('[role="dialog"]', { state: 'visible', timeout: TIMEOUTS.DIALOG });
  298. }
  299. /**
  300. * 打开删除确认对话框
  301. * @param orderName 订单名称
  302. */
  303. async openDeleteDialog(orderName: string) {
  304. // 找到订单行并点击"打开菜单"按钮(与编辑操作相同的模式)
  305. const orderRow = this.orderTable.locator('tbody tr').filter({ hasText: orderName });
  306. const menuButton = orderRow.getByRole('button', { name: '打开菜单' });
  307. await menuButton.click();
  308. // 等待菜单出现并点击"删除"选项
  309. const deleteOption = this.page.getByRole('menuitem', { name: '删除' });
  310. await deleteOption.waitFor({ state: 'visible', timeout: TIMEOUTS.ELEMENT_VISIBLE_SHORT });
  311. await deleteOption.click();
  312. // 等待删除确认对话框出现
  313. await this.page.waitForSelector('[role="alertdialog"]', { state: 'visible', timeout: TIMEOUTS.DIALOG });
  314. }
  315. /**
  316. * 填写订单表单
  317. * @param data 订单数据
  318. */
  319. async fillOrderForm(data: OrderData) {
  320. // 等待表单出现
  321. await this.page.waitForSelector('form', { state: 'visible', timeout: TIMEOUTS.DIALOG });
  322. // 填写订单名称
  323. if (data.name) {
  324. await this.page.getByLabel(/订单名称|名称/).fill(data.name);
  325. }
  326. // 填写预计开始日期
  327. if (data.expectedStartDate) {
  328. const dateInput = this.page.getByLabel(/预计开始日期|开始日期/);
  329. await dateInput.fill(data.expectedStartDate);
  330. }
  331. // 选择平台
  332. if (data.platformName) {
  333. await selectRadixOption(this.page, '平台', data.platformName);
  334. }
  335. // 选择公司
  336. if (data.companyName) {
  337. await selectRadixOption(this.page, '公司', data.companyName);
  338. }
  339. // 选择渠道
  340. if (data.channelName) {
  341. await selectRadixOption(this.page, '渠道', data.channelName);
  342. }
  343. // 选择订单状态(如果是编辑模式)
  344. if (data.status) {
  345. const statusLabel = ORDER_STATUS_LABELS[data.status];
  346. await selectRadixOption(this.page, '订单状态', statusLabel);
  347. }
  348. // 选择工作状态(如果是编辑模式)
  349. if (data.workStatus) {
  350. const workStatusLabel = WORK_STATUS_LABELS[data.workStatus];
  351. await selectRadixOption(this.page, '工作状态', workStatusLabel);
  352. }
  353. }
  354. /**
  355. * 提交表单
  356. * @returns 表单提交结果
  357. */
  358. async submitForm(): Promise<FormSubmitResult> {
  359. // 收集网络响应
  360. const responses: NetworkResponse[] = [];
  361. // 监听所有网络请求
  362. const responseHandler = async (response: Response) => {
  363. const url = response.url();
  364. // 监听订单管理相关的 API 请求
  365. if (url.includes('/orders') || url.includes('order')) {
  366. const _requestBody = response.request()?.postData();
  367. const responseBody = await response.text().catch(() => '');
  368. let jsonBody = null;
  369. try {
  370. jsonBody = JSON.parse(responseBody);
  371. } catch {
  372. // 不是 JSON 响应
  373. }
  374. responses.push({
  375. url,
  376. method: response.request()?.method() ?? 'UNKNOWN',
  377. status: response.status(),
  378. ok: response.ok(),
  379. responseHeaders: await response.allHeaders().catch(() => ({})),
  380. responseBody: jsonBody || responseBody,
  381. });
  382. }
  383. };
  384. this.page.on('response', responseHandler);
  385. try {
  386. // 点击提交按钮(创建或更新)
  387. const submitButton = this.page.getByRole('button', { name: /^(创建|更新|保存)$/ });
  388. await submitButton.click();
  389. // 等待网络请求完成(使用较宽松的超时,因为有些操作可能不触发网络请求)
  390. try {
  391. await this.page.waitForLoadState('domcontentloaded', { timeout: TIMEOUTS.DIALOG });
  392. } catch {
  393. // domcontentloaded 超时不是致命错误,继续检查 Toast 消息
  394. console.debug('domcontentloaded 超时,继续检查 Toast 消息');
  395. }
  396. } finally {
  397. // 确保监听器总是被移除,防止内存泄漏
  398. this.page.off('response', responseHandler);
  399. }
  400. // 等待 Toast 消息显示
  401. await this.page.waitForTimeout(TIMEOUTS.VERY_LONG);
  402. // 检查 Toast 消息
  403. const errorToast = this.page.locator('[data-sonner-toast][data-type="error"]');
  404. const successToast = this.page.locator('[data-sonner-toast][data-type="success"]');
  405. const hasError = await errorToast.count() > 0;
  406. const hasSuccess = await successToast.count() > 0;
  407. let errorMessage: string | null = null;
  408. let successMessage: string | null = null;
  409. if (hasError) {
  410. errorMessage = await errorToast.first().textContent();
  411. }
  412. if (hasSuccess) {
  413. successMessage = await successToast.first().textContent();
  414. }
  415. return {
  416. success: hasSuccess || (!hasError && !hasSuccess),
  417. hasError,
  418. hasSuccess,
  419. errorMessage: errorMessage ?? undefined,
  420. successMessage: successMessage ?? undefined,
  421. responses,
  422. };
  423. }
  424. /**
  425. * 取消对话框
  426. */
  427. async cancelDialog() {
  428. const cancelButton = this.page.getByRole('button', { name: '取消' });
  429. await cancelButton.click();
  430. await this.waitForDialogClosed();
  431. }
  432. /**
  433. * 等待对话框关闭
  434. */
  435. async waitForDialogClosed() {
  436. // 先等待一段时间让对话框有机会关闭
  437. await this.page.waitForTimeout(TIMEOUTS.LONG);
  438. // 检查是否还有对话框可见
  439. const dialogs = this.page.locator('[role="dialog"]');
  440. const dialogCount = await dialogs.count();
  441. if (dialogCount === 0) {
  442. // 没有对话框了,已经关闭
  443. console.debug('对话框已关闭(无对话框元素)');
  444. return;
  445. }
  446. // 尝试等待对话框隐藏或从 DOM 中移除
  447. try {
  448. await dialogs.first().waitFor({ state: 'hidden', timeout: TIMEOUTS.ELEMENT_VISIBLE_SHORT });
  449. console.debug('对话框已关闭');
  450. } catch {
  451. // 超时不是致命错误,对话框可能已经以其他方式关闭
  452. console.debug('对话框关闭等待超时,继续执行');
  453. }
  454. await this.page.waitForTimeout(TIMEOUTS.MEDIUM);
  455. }
  456. /**
  457. * 确认删除操作
  458. */
  459. async confirmDelete() {
  460. // 尝试多种可能的按钮名称
  461. const confirmButton = this.page.locator('[role="alertdialog"]').getByRole('button', {
  462. name: /^(确认删除|删除|确定|确认)$/
  463. });
  464. await confirmButton.click();
  465. // 等待确认对话框关闭和网络请求完成
  466. await this.page.waitForSelector('[role="alertdialog"]', { state: 'hidden', timeout: TIMEOUTS.DIALOG })
  467. .catch(() => console.debug('删除确认对话框关闭超时'));
  468. await this.page.waitForLoadState('networkidle', { timeout: TIMEOUTS.TABLE_LOAD });
  469. await this.page.waitForTimeout(TIMEOUTS.LONG);
  470. }
  471. /**
  472. * 取消删除操作
  473. */
  474. async cancelDelete() {
  475. const cancelButton = this.page.getByRole('button', { name: '取消' }).and(
  476. this.page.locator('[role="alertdialog"]')
  477. );
  478. await cancelButton.click();
  479. await this.page.waitForSelector('[role="alertdialog"]', { state: 'hidden', timeout: TIMEOUTS.DIALOG })
  480. .catch(() => console.debug('删除确认对话框关闭超时(取消操作)'));
  481. }
  482. /**
  483. * 验证订单是否存在
  484. * @param orderName 订单名称
  485. * @returns 订单是否存在
  486. */
  487. async orderExists(orderName: string): Promise<boolean> {
  488. const orderRow = this.orderTable.locator('tbody tr').filter({ hasText: orderName });
  489. return (await orderRow.count()) > 0;
  490. }
  491. // ===== 订单详情 =====
  492. /**
  493. * 打开订单详情对话框
  494. * @param orderName 订单名称
  495. */
  496. async openDetailDialog(orderName: string) {
  497. // 找到订单行
  498. const orderRow = this.orderTable.locator('tbody tr').filter({ hasText: orderName });
  499. // 先点击操作菜单触发按钮("打开菜单" 或 MoreHorizontal 图标)
  500. const menuTrigger = orderRow.getByRole('button', { name: /打开菜单/ });
  501. await menuTrigger.click();
  502. // 等待菜单显示
  503. await this.page.waitForTimeout(TIMEOUTS.VERY_SHORT);
  504. // 点击"查看详情"菜单项
  505. const detailButton = this.page.getByRole('menuitem', { name: /查看详情/ });
  506. await detailButton.click();
  507. await this.page.waitForSelector('[role="dialog"]', { state: 'visible', timeout: TIMEOUTS.DIALOG });
  508. }
  509. /**
  510. * 获取订单详情对话框中的基本信息
  511. * @returns 订单基本信息
  512. */
  513. async getOrderDetailInfo(): Promise<{
  514. name?: string;
  515. status?: string;
  516. workStatus?: string;
  517. expectedStartDate?: string;
  518. platform?: string;
  519. company?: string;
  520. channel?: string;
  521. }> {
  522. const dialog = this.page.locator('[role="dialog"]');
  523. const result: Record<string, string | undefined> = {};
  524. // 使用 data-testid 直接定位元素(更可靠)
  525. // DOM 结构: <div className="flex items-center justify-between">
  526. // <span className="text-sm font-medium">标签:</span>
  527. // <span data-testid="order-detail-xxx">值</span>
  528. // </div>
  529. // 订单名称 - 使用 data-testid
  530. const nameElement = dialog.locator('[data-testid="order-detail-name"]');
  531. if (await nameElement.count() > 0) {
  532. result.name = (await nameElement.textContent())?.trim();
  533. }
  534. // 订单状态
  535. const statusElement = dialog.locator('[data-testid="order-detail-status"]');
  536. if (await statusElement.count() > 0) {
  537. result.status = (await statusElement.textContent())?.trim();
  538. }
  539. // 工作状态 - 查找包含"工作状态"标签的行
  540. const workStatusRow = dialog.locator('div').filter({ hasText: /工作状态:/ }).first();
  541. if (await workStatusRow.count() > 0) {
  542. const workStatusElement = workStatusRow.locator('span').nth(1);
  543. result.workStatus = (await workStatusElement.textContent())?.trim();
  544. }
  545. // 预计开始日期 - 使用 data-testid
  546. const expectedStartDateElement = dialog.locator('[data-testid="order-detail-expected-start"]');
  547. if (await expectedStartDateElement.count() > 0) {
  548. result.expectedStartDate = (await expectedStartDateElement.textContent())?.trim();
  549. }
  550. // 平台 - 使用 data-testid
  551. const platformElement = dialog.locator('[data-testid="order-detail-platform"]');
  552. if (await platformElement.count() > 0) {
  553. result.platform = (await platformElement.textContent())?.trim();
  554. }
  555. // 公司 - 使用 data-testid
  556. const companyElement = dialog.locator('[data-testid="order-detail-company"]');
  557. if (await companyElement.count() > 0) {
  558. result.company = (await companyElement.textContent())?.trim();
  559. }
  560. // 渠道 - 使用 data-testid
  561. const channelElement = dialog.locator('[data-testid="order-detail-channel"]');
  562. if (await channelElement.count() > 0) {
  563. result.channel = (await channelElement.textContent())?.trim();
  564. }
  565. return result;
  566. }
  567. /**
  568. * 从订单详情对话框中获取关联人员列表
  569. * @returns 人员信息列表
  570. */
  571. async getPersonListFromDetail(): Promise<Array<{
  572. name?: string;
  573. workStatus?: string;
  574. hireDate?: string;
  575. salary?: string;
  576. }>> {
  577. const dialog = this.page.locator('[role="dialog"]');
  578. const result: Array<{ name?: string; workStatus?: string; hireDate?: string; salary?: string }> = [];
  579. // 查找所有表格,对话框中可能有两个表格:
  580. // 1. "待添加人员列表" - 临时表格,包含未确认的人员
  581. // 2. "绑定人员列表" - 实际已绑定到订单的人员
  582. // 我们需要第二个"绑定人员列表"表格
  583. const allTables = dialog.locator('table');
  584. const tableCount = await allTables.count();
  585. // 查找"绑定人员列表"表格(通常是包含"工作状态"列的表格)
  586. let personTable;
  587. for (let i = 0; i < tableCount; i++) {
  588. const table = allTables.nth(i);
  589. const tableText = await table.textContent();
  590. // 绑定人员列表表格包含"工作状态"列,而待添加人员列表没有
  591. if (tableText && tableText.includes('工作状态')) {
  592. personTable = table;
  593. break;
  594. }
  595. }
  596. const personList = dialog.locator('[class*="person"], [class*="employee"], [data-testid*="person"]');
  597. // 优先使用表格形式
  598. if (personTable) {
  599. const rows = personTable.locator('tbody tr');
  600. const rowCount = await rows.count();
  601. for (let i = 0; i < rowCount; i++) {
  602. const row = rows.nth(i);
  603. const cells = row.locator('td');
  604. const cellCount = await cells.count();
  605. const personInfo: { name?: string; workStatus?: string; hireDate?: string; salary?: string } = {};
  606. // 根据列数量和数据类型提取信息
  607. // 表格列:ID 姓名 性别 残疾类型 联系电话 入职日期 离职日期 工作状态 薪资
  608. for (let j = 0; j < cellCount; j++) {
  609. const cellText = await cells.nth(j).textContent();
  610. if (!cellText) continue;
  611. const trimmedText = cellText.trim();
  612. // 尝试识别列内容
  613. // ID 在第一列(j === 0),姓名在第二列(j === 1)
  614. if (j === 1 && trimmedText) {
  615. personInfo.name = trimmedText;
  616. }
  617. // 工作状态检查
  618. for (const [_statusValue, statusLabel] of Object.entries(WORK_STATUS_LABELS)) {
  619. if (trimmedText.includes(statusLabel)) {
  620. personInfo.workStatus = statusLabel;
  621. break;
  622. }
  623. }
  624. // 日期检查(符合日期格式)
  625. if (/^\d{4}-\d{2}-\d{2}$/.test(trimmedText) || /^\d{4}\/\d{2}\/\d{2}$/.test(trimmedText)) {
  626. if (!personInfo.hireDate) {
  627. personInfo.hireDate = trimmedText;
  628. }
  629. }
  630. // 薪资检查(在最后一列,包含数字且可能是薪资)
  631. // 薪资通常是较大的数字,不应该是11位电话号码
  632. if (j === cellCount - 1 && /^\d+(\.\d+)?$/.test(trimmedText.replace(/,/g, ''))) {
  633. const numValue = trimmedText.replace(/,/g, '');
  634. // 排除11位电话号码(如13800019729)
  635. if (numValue.length < 11) {
  636. personInfo.salary = trimmedText;
  637. }
  638. }
  639. }
  640. if (personInfo.name || personInfo.workStatus) {
  641. result.push(personInfo);
  642. }
  643. }
  644. } else if (await personList.count() > 0) {
  645. // 如果是列表形式而非表格
  646. const listItems = personList.locator('[class*="item"], [class*="row"], li, div');
  647. const itemCount = await listItems.count();
  648. for (let i = 0; i < itemCount; i++) {
  649. const item = listItems.nth(i);
  650. const itemText = await item.textContent();
  651. if (itemText && itemText.trim()) {
  652. result.push({ name: itemText.trim() });
  653. }
  654. }
  655. }
  656. return result;
  657. }
  658. /**
  659. * 从订单详情对话框中获取附件列表
  660. * @returns 附件信息列表
  661. */
  662. async getAttachmentListFromDetail(): Promise<Array<{
  663. fileName?: string;
  664. uploadDate?: string;
  665. uploader?: string;
  666. }>> {
  667. const dialog = this.page.locator('[role="dialog"]');
  668. const result: Array<{ fileName?: string; uploadDate?: string; uploader?: string }> = [];
  669. // 查找附件列表区域
  670. // 尝试多种可能的定位策略
  671. const attachmentTable = dialog.locator('table').filter({ hasText: /附件|文件/ });
  672. const attachmentList = dialog.locator('[class*="attachment"], [class*="file"], [data-testid*="attachment"]');
  673. // 优先使用表格形式
  674. if (await attachmentTable.count() > 0) {
  675. const rows = attachmentTable.locator('tbody tr');
  676. const rowCount = await rows.count();
  677. for (let i = 0; i < rowCount; i++) {
  678. const row = rows.nth(i);
  679. const cells = row.locator('td');
  680. const cellCount = await cells.count();
  681. const attachmentInfo: { fileName?: string; uploadDate?: string; uploader?: string } = {};
  682. for (let j = 0; j < cellCount; j++) {
  683. const cellText = await cells.nth(j).textContent();
  684. if (!cellText) continue;
  685. const trimmedText = cellText.trim();
  686. // 文件名通常在第一列
  687. if (j === 0 && trimmedText) {
  688. attachmentInfo.fileName = trimmedText;
  689. }
  690. // 日期检查
  691. if (/^\d{4}-\d{2}-\d{2}/.test(trimmedText) || /^\d{4}\/\d{2}\/\d{2}/.test(trimmedText)) {
  692. if (!attachmentInfo.uploadDate) {
  693. attachmentInfo.uploadDate = trimmedText;
  694. }
  695. }
  696. // 上传者通常是文本用户名
  697. if (j > 0 && trimmedText && !attachmentInfo.uploader && !attachmentInfo.uploadDate && !/^\d{4}/.test(trimmedText)) {
  698. attachmentInfo.uploader = trimmedText;
  699. }
  700. }
  701. if (attachmentInfo.fileName) {
  702. result.push(attachmentInfo);
  703. }
  704. }
  705. } else if (await attachmentList.count() > 0) {
  706. // 如果是列表形式
  707. const listItems = attachmentList.locator('[class*="item"], [class*="row"], li, div');
  708. const itemCount = await listItems.count();
  709. for (let i = 0; i < itemCount; i++) {
  710. const item = listItems.nth(i);
  711. const itemText = await item.textContent();
  712. if (itemText && itemText.trim()) {
  713. result.push({ fileName: itemText.trim() });
  714. }
  715. }
  716. }
  717. return result;
  718. }
  719. /**
  720. * 关闭订单详情对话框
  721. */
  722. async closeDetailDialog(): Promise<void> {
  723. // 尝试多种关闭方式
  724. // 方式1: 点击右上角 X 按钮
  725. const closeButton = this.page.locator('[role="dialog"]').getByRole('button', { name: '关闭' }).first();
  726. const closeButtonCount = await closeButton.count();
  727. if (closeButtonCount > 0) {
  728. await closeButton.click();
  729. } else {
  730. // 方式2: 点击取消按钮
  731. const cancelButton = this.page.locator('[role="dialog"]').getByRole('button', { name: '取消' }).first();
  732. const cancelButtonCount = await cancelButton.count();
  733. if (cancelButtonCount > 0) {
  734. await cancelButton.click();
  735. } else {
  736. // 方式3: 按 Escape 键
  737. await this.page.keyboard.press('Escape');
  738. }
  739. }
  740. // 等待对话框关闭
  741. await this.waitForDialogClosed();
  742. }
  743. // ===== 人员关联管理 =====
  744. /**
  745. * 打开人员管理对话框
  746. *
  747. * **使用场景:**
  748. * - **从订单列表页打开**: 传入 `orderName` 参数,方法会先找到对应订单行,再点击人员管理按钮
  749. * - **从订单详情页打开**: 不传参数,方法会直接点击页面中的人员管理按钮
  750. *
  751. * @param orderName 订单名称(可选)。从列表页打开时需要传入,从详情页打开时不传
  752. *
  753. * @example
  754. * ```typescript
  755. * // 从订单列表页打开
  756. * await orderPage.openPersonManagementDialog('测试订单');
  757. *
  758. * // 从订单详情页打开
  759. * await orderPage.openDetailDialog('测试订单');
  760. * await orderPage.openPersonManagementDialog();
  761. * ```
  762. */
  763. async openPersonManagementDialog(orderName?: string) {
  764. // 人员管理功能直接集成在订单详情对话框中
  765. // 如果提供了订单名称,打开订单详情对话框
  766. if (orderName) {
  767. await this.openDetailDialog(orderName);
  768. }
  769. // 人员管理功能已在详情对话框中,无需额外操作
  770. }
  771. /**
  772. * 添加人员到订单
  773. * @param personData 人员数据
  774. */
  775. async addPersonToOrder(personData: OrderPersonData) {
  776. // 点击添加人员按钮
  777. const addButton = this.page.getByRole('button', { name: /添加人员|新增人员/ });
  778. await addButton.click();
  779. await this.page.waitForTimeout(TIMEOUTS.SHORT);
  780. // 选择残疾人(支持通过名称选择)
  781. if (personData.disabledPersonName) {
  782. await selectRadixOption(this.page, '残疾人|选择残疾人', personData.disabledPersonName);
  783. } else if (personData.disabledPersonId) {
  784. // 如果只提供了 ID,尝试在对话框中选择第一个残疾人
  785. const firstCheckbox = this.page.locator('[role="dialog"]').locator('table tbody tr').first().locator('input[type="checkbox"]').first();
  786. try {
  787. await firstCheckbox.waitFor({ state: 'visible', timeout: TIMEOUTS.ELEMENT_VISIBLE_SHORT });
  788. await firstCheckbox.check();
  789. } catch {
  790. console.debug('没有可用的残疾人数据');
  791. }
  792. }
  793. // 填写入职日期
  794. if (personData.hireDate) {
  795. const hireDateInput = this.page.getByLabel(/入职日期/);
  796. await hireDateInput.fill(personData.hireDate);
  797. }
  798. // 填写薪资
  799. if (personData.salary !== undefined) {
  800. const salaryInput = this.page.getByLabel(/薪资|工资/);
  801. await salaryInput.fill(String(personData.salary));
  802. }
  803. // 选择工作状态
  804. if (personData.workStatus) {
  805. const workStatusLabel = WORK_STATUS_LABELS[personData.workStatus];
  806. await selectRadixOption(this.page, '工作状态', workStatusLabel);
  807. }
  808. // 提交
  809. const submitButton = this.page.getByRole('button', { name: /^(添加|确定|保存)$/ });
  810. await submitButton.click();
  811. await this.page.waitForLoadState('networkidle');
  812. await this.page.waitForTimeout(TIMEOUTS.LONG);
  813. }
  814. /**
  815. * 修改人员工作状态
  816. * @param personName 人员姓名
  817. * @param newStatus 新的工作状态
  818. */
  819. async updatePersonWorkStatus(personName: string, newStatus: WorkStatus) {
  820. const dialog = this.page.locator('[role="dialog"]');
  821. // 等待对话框完全加载
  822. await dialog.waitFor({ state: 'visible', timeout: TIMEOUTS.DIALOG });
  823. // 从 error-context.md 可知:
  824. // 1. 对话框中有"绑定人员列表"表格
  825. // 2. 表格列:ID 姓名 性别 残疾类型 联系电话 入职日期 离职日期 工作状态 薪资
  826. // 3. 工作状态列直接是 combobox,不需要点击编辑按钮
  827. // 查找所有表格
  828. const allTables = dialog.locator('table');
  829. const allTableCount = await allTables.count();
  830. console.debug(`对话框中总共有 ${allTableCount} 个表格`);
  831. let personTable = allTables.first();
  832. // 找到包含"绑定人员"或"工作状态"列的表格(第二个表格是绑定人员列表)
  833. for (let i = 0; i < allTableCount; i++) {
  834. const table = allTables.nth(i);
  835. const tableText = await table.textContent();
  836. if (tableText && (tableText.includes('绑定人员') || tableText.includes('工作状态'))) {
  837. personTable = table;
  838. console.debug(`找到人员表格(索引 ${i})`);
  839. break;
  840. }
  841. }
  842. // 在表格中查找包含指定人员名称的行
  843. const targetRow = personTable.locator('tbody tr').filter({ hasText: personName }).first();
  844. const rowCount = await targetRow.count();
  845. console.debug(`找到 ${rowCount} 个匹配的人员行`);
  846. if (rowCount === 0) {
  847. throw new Error(`未找到人员 ${personName}`);
  848. }
  849. // 等待行可见
  850. await targetRow.waitFor({ state: 'visible', timeout: TIMEOUTS.DIALOG });
  851. // 从 error-context.md 可知,工作状态在单元格中是一个 combobox
  852. // 表格列:ID 姓名 性别 残疾类型 联系电话 入职日期 离职日期 工作状态 薪资
  853. // 工作状态是倒数第二列(薪资是最后一列)
  854. const cells = targetRow.locator('td');
  855. const cellCount = await cells.count();
  856. console.debug(`人员行有 ${cellCount} 个单元格`);
  857. // 工作状态在倒数第二列
  858. const workStatusCell = cells.nth(cellCount - 2);
  859. const workStatusCombobox = workStatusCell.getByRole('combobox');
  860. const comboboxCount = await workStatusCombobox.count();
  861. console.debug(`工作状态 combobox 数量: ${comboboxCount}`);
  862. if (comboboxCount === 0) {
  863. throw new Error(`未找到人员 ${personName} 的工作状态选择器`);
  864. }
  865. await workStatusCombobox.click({ timeout: TIMEOUTS.DIALOG });
  866. console.debug('工作状态 combobox 已点击');
  867. // 等待下拉选项显示
  868. await this.page.waitForTimeout(TIMEOUTS.MEDIUM);
  869. // 使用中文标签选择选项
  870. // 注意:UI 中的工作状态选项与 WORK_STATUS_LABELS 不同
  871. // UI 选项:未入职、已入职、工作中、已离职
  872. // WORK_STATUS_LABELS:未就业、待就业、已就业、已离职
  873. const statusMapping: Record<WorkStatus, string> = {
  874. not_working: '未入职',
  875. pre_working: '已入职',
  876. working: '工作中',
  877. resigned: '已离职',
  878. };
  879. const newWorkStatusLabel = statusMapping[newStatus];
  880. console.debug(`尝试选择状态: ${newWorkStatusLabel}`);
  881. const optionLocator = this.page.getByRole('option', { name: newWorkStatusLabel });
  882. const optionCount = await optionLocator.count();
  883. console.debug(`找到 ${optionCount} 个选项`);
  884. if (optionCount === 0) {
  885. throw new Error(`未找到工作状态选项: ${newWorkStatusLabel}`);
  886. }
  887. await optionLocator.first().click({ timeout: TIMEOUTS.DIALOG });
  888. console.debug(`工作状态已更新为: ${newWorkStatusLabel}`);
  889. // 使用较短的超时时间等待网络空闲
  890. await this.page.waitForLoadState('domcontentloaded', { timeout: TIMEOUTS.DIALOG })
  891. .catch(() => console.debug('domcontentloaded 等待超时,继续'));
  892. await this.page.waitForTimeout(TIMEOUTS.MEDIUM);
  893. }
  894. // ===== 附件管理 =====
  895. /**
  896. * 打开资源上传对话框
  897. * "资源上传"按钮在订单详情对话框中
  898. */
  899. async openAddAttachmentDialog() {
  900. // 使用"资源上传"按钮
  901. const attachmentButton = this.page.getByRole('button', { name: /资源上传/ });
  902. await attachmentButton.click();
  903. // 等待第二个对话框(资源上传对话框)打开
  904. await this.page.waitForTimeout(TIMEOUTS.MEDIUM);
  905. }
  906. /**
  907. * 上传附件
  908. *
  909. * 实际的 UI 流程:
  910. * 1. 点击人员行中对应文件类型的"上传文件"按钮
  911. * 2. 打开 FileSelector 对话框(第三个对话框)
  912. * 3. 在 FileSelector 对话框中使用 uploadFileToField 上传文件
  913. * 4. 点击上传后的文件进行选择
  914. * 5. 点击"确认选择"按钮
  915. *
  916. * @param personIdentifier 人员标识(可以是 ID 或姓名,方法会自动匹配)
  917. * @param fileName 文件名(相对于 web/tests/fixtures 目录)
  918. * @param mimeType 文件类型(默认为 image/jpeg,未使用,保留用于未来扩展)
  919. * @param fileType 文件类型(税务文件、薪资单、工作成果、合同签署、残疾证明、其他),默认为"其他"
  920. */
  921. async uploadAttachment(
  922. personIdentifier: string,
  923. fileName: string,
  924. _mimeType: string = 'image/jpeg',
  925. fileType: string = '其他'
  926. ) {
  927. // 动态导入 uploadFileToField 工具
  928. const { uploadFileToField } = await import('@d8d/e2e-test-utils');
  929. // 找到资源上传对话框(第二个对话框)
  930. const dialogs = this.page.locator('[role="dialog"]');
  931. const uploadDialog = dialogs.nth(1);
  932. // 在对话框中找到对应残疾人的行
  933. // 使用 ID 或姓名匹配
  934. const personRow = uploadDialog.locator('tr').filter({ hasText: personIdentifier });
  935. const rowCount = await personRow.count();
  936. if (rowCount === 0) {
  937. console.debug(`未找到人员 ${personIdentifier} 的行`);
  938. // 尝试打印所有行内容用于调试
  939. const allRows = uploadDialog.locator('tbody tr');
  940. const allRowCount = await allRows.count();
  941. console.debug(`资源上传对话框共有 ${allRowCount} 行`);
  942. for (let i = 0; i < Math.min(allRowCount, 3); i++) {
  943. const rowText = await allRows.nth(i).textContent();
  944. console.debug(`行 ${i} 内容:`, rowText);
  945. }
  946. return;
  947. }
  948. console.debug(`找到人员 ${personIdentifier} 的行`);
  949. // 在该人员行中找到对应文件类型的"上传文件"按钮
  950. // 文件类型列顺序:税务文件、薪资单、工作成果、合同签署、残疾证明、其他
  951. const uploadButton = personRow.getByRole('button', { name: '上传文件' });
  952. const buttonCount = await uploadButton.count();
  953. if (buttonCount === 0) {
  954. console.debug(`未找到"上传文件"按钮`);
  955. return;
  956. }
  957. console.debug(`找到 ${buttonCount} 个"上传文件"按钮`);
  958. // 根据文件类型选择对应的上传按钮
  959. let buttonIndex = 5; // 默认为"其他"(最后一个)
  960. switch (fileType) {
  961. case '税务文件':
  962. buttonIndex = 0;
  963. break;
  964. case '薪资单':
  965. buttonIndex = 1;
  966. break;
  967. case '工作成果':
  968. buttonIndex = 2;
  969. break;
  970. case '合同签署':
  971. buttonIndex = 3;
  972. break;
  973. case '残疾证明':
  974. buttonIndex = 4;
  975. break;
  976. case '其他':
  977. default:
  978. buttonIndex = 5;
  979. break;
  980. }
  981. // 点击对应的上传文件按钮,这会打开 FileSelector 对话框
  982. const targetButton = uploadButton.nth(buttonIndex);
  983. await targetButton.click();
  984. // 等待 FileSelector 对话框打开(第三个对话框)
  985. await this.page.waitForTimeout(TIMEOUTS.MEDIUM);
  986. // FileSelector 对话框的 data-testid 是 "file-selector-dialog"
  987. const fileSelectorDialog = this.page.getByTestId('file-selector-dialog');
  988. const dialogVisible = await fileSelectorDialog.count() > 0;
  989. if (!dialogVisible) {
  990. console.debug('FileSelector 对话框未打开');
  991. return;
  992. }
  993. console.debug('FileSelector 对话框已打开');
  994. // 使用 uploadFileToField 上传文件
  995. // MinioUploader 使用 data-testid="minio-uploader-input"(因为 testId 未被传递)
  996. try {
  997. await uploadFileToField(
  998. this.page,
  999. '[data-testid="minio-uploader-input"]',
  1000. fileName,
  1001. {
  1002. fixturesDir: 'tests/fixtures',
  1003. timeout: TIMEOUTS.DIALOG
  1004. }
  1005. );
  1006. console.debug(`文件 ${fileName} 上传操作已完成`);
  1007. } catch (error) {
  1008. console.debug('文件上传失败:', error);
  1009. // 即使上传失败,也尝试关闭对话框
  1010. await fileSelectorDialog.getByRole('button', { name: '取消' }).click().catch(() => {});
  1011. return;
  1012. }
  1013. // 等待上传处理完成,等待文件出现在对话框中
  1014. await this.page.waitForTimeout(TIMEOUTS.LONG);
  1015. // 点击上传后的文件进行选择(查找第一个可点击的文件)
  1016. // 上传成功后,文件会被添加到文件列表中并显示为选中状态(border-primary)
  1017. const uploadedFile = fileSelectorDialog.locator('.border-primary').or(
  1018. fileSelectorDialog.locator('img').first()
  1019. );
  1020. const fileExists = await uploadedFile.count() > 0;
  1021. if (fileExists) {
  1022. await uploadedFile.first().click();
  1023. console.debug('已点击上传后的文件');
  1024. } else {
  1025. // 如果没找到选中的文件,尝试查看对话框内容
  1026. const allImages = fileSelectorDialog.locator('img');
  1027. const imgCount = await allImages.count();
  1028. console.debug(`对话框中图片数量: ${imgCount}`);
  1029. // 尝试点击任何图片
  1030. if (imgCount > 0) {
  1031. await allImages.first().click();
  1032. console.debug('已点击第一张图片');
  1033. }
  1034. }
  1035. await this.page.waitForTimeout(TIMEOUTS.SHORT);
  1036. // 点击"确认选择"按钮
  1037. const confirmButton = fileSelectorDialog.getByRole('button', { name: '确认选择' });
  1038. const confirmButtonCount = await confirmButton.count();
  1039. if (confirmButtonCount > 0) {
  1040. await confirmButton.click();
  1041. console.debug('已点击确认选择按钮');
  1042. } else {
  1043. console.debug('未找到"确认选择"按钮');
  1044. }
  1045. // 等待对话框关闭
  1046. await this.page.waitForTimeout(TIMEOUTS.MEDIUM);
  1047. console.debug(`附件上传流程完成: ${fileName}`);
  1048. }
  1049. /**
  1050. * 关闭资源上传对话框
  1051. */
  1052. async closeUploadDialog() {
  1053. // 资源上传对话框有"关闭"按钮
  1054. // 需要精确定位到第二个对话框(资源上传对话框)的关闭按钮
  1055. const dialogs = this.page.locator('[role="dialog"]');
  1056. const dialogCount = await dialogs.count();
  1057. if (dialogCount >= 2) {
  1058. // 资源上传对话框通常是第二个对话框
  1059. const uploadDialog = dialogs.nth(1);
  1060. const closeButton = uploadDialog.getByRole('button', { name: '关闭' });
  1061. const buttonCount = await closeButton.count();
  1062. if (buttonCount > 0) {
  1063. await closeButton.first().click();
  1064. console.debug('已关闭资源上传对话框');
  1065. } else {
  1066. console.debug('未找到资源上传对话框的关闭按钮,尝试按 Escape');
  1067. await this.page.keyboard.press('Escape');
  1068. }
  1069. } else {
  1070. // 如果只有一个对话框,尝试点击通用的关闭按钮
  1071. const closeButton = this.page.getByRole('button', { name: '关闭' });
  1072. const buttonCount = await closeButton.count();
  1073. if (buttonCount > 0) {
  1074. await closeButton.first().click();
  1075. console.debug('已关闭对话框(使用通用关闭按钮)');
  1076. }
  1077. }
  1078. await this.page.waitForTimeout(TIMEOUTS.MEDIUM);
  1079. }
  1080. // ===== 高级操作 =====
  1081. /**
  1082. * 创建订单(完整流程)
  1083. * @param data 订单数据
  1084. * @returns 表单提交结果
  1085. */
  1086. async createOrder(data: OrderData): Promise<FormSubmitResult> {
  1087. await this.openCreateDialog();
  1088. await this.fillOrderForm(data);
  1089. const result = await this.submitForm();
  1090. await this.waitForDialogClosed();
  1091. return result;
  1092. }
  1093. /**
  1094. * 编辑订单(完整流程)
  1095. * @param orderName 订单名称
  1096. * @param data 更新的订单数据
  1097. * @returns 表单提交结果
  1098. */
  1099. async editOrder(orderName: string, data: OrderData): Promise<FormSubmitResult> {
  1100. await this.openEditDialog(orderName);
  1101. await this.fillOrderForm(data);
  1102. const result = await this.submitForm();
  1103. await this.waitForDialogClosed();
  1104. return result;
  1105. }
  1106. /**
  1107. * 删除订单(完整流程)
  1108. * @param orderName 订单名称
  1109. * @returns 是否成功删除
  1110. */
  1111. async deleteOrder(orderName: string): Promise<boolean> {
  1112. await this.openDeleteDialog(orderName);
  1113. await this.confirmDelete();
  1114. // 等待并检查 Toast 消息
  1115. await this.page.waitForTimeout(TIMEOUTS.LONG);
  1116. const successToast = this.page.locator('[data-sonner-toast][data-type="success"]');
  1117. const hasSuccess = await successToast.count() > 0;
  1118. return hasSuccess;
  1119. }
  1120. // ===== 订单状态流转操作 =====
  1121. /**
  1122. * 打开激活订单确认对话框
  1123. * @param orderName 订单名称
  1124. */
  1125. async openActivateDialog(orderName: string): Promise<void> {
  1126. // 找到订单行并点击"打开菜单"按钮(与编辑/删除操作相同的模式)
  1127. const orderRow = this.orderTable.locator('tbody tr').filter({ hasText: orderName });
  1128. const menuButton = orderRow.getByRole('button', { name: '打开菜单' });
  1129. await menuButton.click();
  1130. // 等待菜单出现并点击"激活"选项
  1131. const activateOption = this.page.getByRole('menuitem', { name: /激活|激活订单/ });
  1132. await activateOption.waitFor({ state: 'visible', timeout: TIMEOUTS.ELEMENT_VISIBLE_SHORT });
  1133. await activateOption.click();
  1134. // 等待确认对话框出现
  1135. await this.page.waitForSelector('[role="alertdialog"]', { state: 'visible', timeout: TIMEOUTS.DIALOG });
  1136. }
  1137. /**
  1138. * 确认激活订单
  1139. */
  1140. async confirmActivate(): Promise<void> {
  1141. // 尝试多种可能的按钮名称
  1142. const confirmButton = this.page.locator('[role="alertdialog"]').getByRole('button', {
  1143. name: /^(确认激活|激活|确定|确认)$/
  1144. });
  1145. await confirmButton.click();
  1146. // 等待确认对话框关闭和网络请求完成
  1147. await this.page.waitForSelector('[role="alertdialog"]', { state: 'hidden', timeout: TIMEOUTS.DIALOG })
  1148. .catch(() => console.debug('激活确认对话框关闭超时'));
  1149. // networkidle 可能因为持续的网络活动而失败,使用更宽松的超时
  1150. await this.page.waitForLoadState('networkidle', { timeout: TIMEOUTS.TABLE_LOAD })
  1151. .catch(() => console.debug('networkidle 超时,继续执行'));
  1152. await this.page.waitForTimeout(TIMEOUTS.LONG);
  1153. }
  1154. /**
  1155. * 激活订单(完整流程)
  1156. * @param orderName 订单名称
  1157. * @returns 是否成功激活
  1158. */
  1159. async activateOrder(orderName: string): Promise<boolean> {
  1160. await this.openActivateDialog(orderName);
  1161. await this.confirmActivate();
  1162. // 等待并检查 Toast 消息
  1163. await this.page.waitForTimeout(TIMEOUTS.LONG);
  1164. const successToast = this.page.locator('[data-sonner-toast][data-type="success"]');
  1165. const hasSuccess = await successToast.count() > 0;
  1166. return hasSuccess;
  1167. }
  1168. /**
  1169. * 打开关闭订单确认对话框
  1170. * @param orderName 订单名称
  1171. */
  1172. async openCloseDialog(orderName: string): Promise<void> {
  1173. // 找到订单行并点击"打开菜单"按钮
  1174. const orderRow = this.orderTable.locator('tbody tr').filter({ hasText: orderName });
  1175. const menuButton = orderRow.getByRole('button', { name: '打开菜单' });
  1176. await menuButton.click();
  1177. // 等待菜单出现并点击"关闭"选项
  1178. const closeOption = this.page.getByRole('menuitem', { name: /关闭|关闭订单|完成/ });
  1179. await closeOption.waitFor({ state: 'visible', timeout: TIMEOUTS.ELEMENT_VISIBLE_SHORT });
  1180. await closeOption.click();
  1181. // 等待确认对话框出现
  1182. await this.page.waitForSelector('[role="alertdialog"]', { state: 'visible', timeout: TIMEOUTS.DIALOG });
  1183. }
  1184. /**
  1185. * 确认关闭订单
  1186. */
  1187. async confirmClose(): Promise<void> {
  1188. // 尝试多种可能的按钮名称
  1189. const confirmButton = this.page.locator('[role="alertdialog"]').getByRole('button', {
  1190. name: /^(确认关闭|关闭|确定|确认)$/
  1191. });
  1192. await confirmButton.click();
  1193. // 等待确认对话框关闭和网络请求完成
  1194. await this.page.waitForSelector('[role="alertdialog"]', { state: 'hidden', timeout: TIMEOUTS.DIALOG })
  1195. .catch(() => console.debug('关闭确认对话框关闭超时'));
  1196. await this.page.waitForLoadState('networkidle', { timeout: TIMEOUTS.TABLE_LOAD });
  1197. await this.page.waitForTimeout(TIMEOUTS.LONG);
  1198. }
  1199. /**
  1200. * 关闭订单(完整流程)
  1201. * @param orderName 订单名称
  1202. * @returns 是否成功关闭
  1203. */
  1204. async closeOrder(orderName: string): Promise<boolean> {
  1205. await this.openCloseDialog(orderName);
  1206. await this.confirmClose();
  1207. // 等待并检查 Toast 消息
  1208. await this.page.waitForTimeout(TIMEOUTS.LONG);
  1209. const successToast = this.page.locator('[data-sonner-toast][data-type="success"]');
  1210. const hasSuccess = await successToast.count() > 0;
  1211. return hasSuccess;
  1212. }
  1213. /**
  1214. * 获取订单的当前状态(从列表页面)
  1215. * @param orderName 订单名称
  1216. * @returns 订单状态值或 null
  1217. */
  1218. async getOrderStatus(orderName: string): Promise<OrderStatus | null> {
  1219. const orderRow = this.orderTable.locator('tbody tr').filter({ hasText: orderName });
  1220. // 等待行可见
  1221. await orderRow.waitFor({ state: 'visible', timeout: TIMEOUTS.ELEMENT_VISIBLE_SHORT }).catch(() => {
  1222. console.debug(`订单 "${orderName}" 行不可见`);
  1223. });
  1224. const rowCount = await orderRow.count();
  1225. if (rowCount === 0) {
  1226. console.debug(`订单 "${orderName}" 不存在`);
  1227. return null;
  1228. }
  1229. // 尝试多种策略定位状态列
  1230. // 策略1: 查找包含状态文本的单元格(但排除订单名称列)
  1231. const allCells = orderRow.locator('td');
  1232. const cellCount = await allCells.count();
  1233. for (let i = 1; i < cellCount; i++) { // 跳过第一列(通常是订单名称)
  1234. const cell = allCells.nth(i);
  1235. const cellText = await cell.textContent();
  1236. if (cellText) {
  1237. // 检查是否包含完整的状态标签(避免部分匹配)
  1238. for (const [statusValue, statusLabel] of Object.entries(ORDER_STATUS_LABELS)) {
  1239. // 使用更严格的匹配:必须是状态标签本身或包含完整标签
  1240. const trimmedText = cellText.trim();
  1241. if (trimmedText === statusLabel || trimmedText.includes(`${statusLabel}`)) {
  1242. // 验证不是订单名称列(额外检查)
  1243. const firstCellText = await allCells.nth(0).textContent();
  1244. if (firstCellText && !firstCellText.includes(orderName.substring(0, 3))) {
  1245. // 第一列不包含订单名称开头,说明列结构可能不同
  1246. return statusValue as OrderStatus;
  1247. }
  1248. // 跳过第一列后找到的状态标签才返回
  1249. return statusValue as OrderStatus;
  1250. }
  1251. }
  1252. }
  1253. }
  1254. // 策略2: 如果上述方法失败,尝试查找状态徽章/标签元素
  1255. // 查找具有状态样式特征的元素
  1256. const statusBadge = orderRow.locator('[class*="status"], [class*="badge"], span').filter({
  1257. hasText: Object.values(ORDER_STATUS_LABELS)
  1258. });
  1259. if (await statusBadge.count() > 0) {
  1260. const badgeText = await statusBadge.first().textContent();
  1261. if (badgeText) {
  1262. for (const [_statusValue, statusLabel] of Object.entries(ORDER_STATUS_LABELS)) {
  1263. if (badgeText.includes(statusLabel)) {
  1264. return statusValue as OrderStatus;
  1265. }
  1266. }
  1267. }
  1268. }
  1269. console.debug(`无法从订单 "${orderName}" 中解析状态`);
  1270. return null;
  1271. }
  1272. /**
  1273. * 验证订单状态
  1274. * @param orderName 订单名称
  1275. * @param expectedStatus 期望的状态
  1276. */
  1277. async expectOrderStatus(orderName: string, expectedStatus: OrderStatus): Promise<void> {
  1278. const actualStatus = await this.getOrderStatus(orderName);
  1279. if (actualStatus === null) {
  1280. throw new Error(`订单 "${orderName}" 未找到或状态列无法识别`);
  1281. }
  1282. if (actualStatus !== expectedStatus) {
  1283. throw new Error(
  1284. `订单 "${orderName}" 状态不匹配: 期望 "${ORDER_STATUS_LABELS[expectedStatus]}", 实际 "${ORDER_STATUS_LABELS[actualStatus]}"`
  1285. );
  1286. }
  1287. }
  1288. /**
  1289. * 检查激活按钮是否可用
  1290. *
  1291. * **注意**: 此方法会打开和关闭菜单,属于有副作用的操作
  1292. *
  1293. * @param orderName 订单名称
  1294. * @returns 按钮是否可用
  1295. */
  1296. async checkActivateButtonEnabled(orderName: string): Promise<boolean> {
  1297. // 找到订单行并打开菜单
  1298. const orderRow = this.orderTable.locator('tbody tr').filter({ hasText: orderName });
  1299. // 检查订单是否存在
  1300. const orderCount = await orderRow.count();
  1301. if (orderCount === 0) {
  1302. console.debug(`订单 "${orderName}" 不存在`);
  1303. return false;
  1304. }
  1305. const menuButton = orderRow.getByRole('button', { name: '打开菜单' });
  1306. try {
  1307. await menuButton.click();
  1308. } catch (error) {
  1309. console.debug(`无法打开订单 "${orderName}" 的菜单:`, error);
  1310. return false;
  1311. }
  1312. // 检查激活菜单项是否可点击
  1313. const activateOption = this.page.getByRole('menuitem', { name: /激活|激活订单/ });
  1314. const isVisible = await activateOption.isVisible().catch(() => false);
  1315. let isEnabled = false;
  1316. if (isVisible) {
  1317. // 检查是否有禁用属性或样式
  1318. const isDisabled = await activateOption.isDisabled().catch(() => false);
  1319. isEnabled = !isDisabled;
  1320. }
  1321. // 关闭菜单以便后续操作
  1322. await this.page.keyboard.press('Escape');
  1323. await this.page.waitForTimeout(TIMEOUTS.SHORT);
  1324. return isEnabled;
  1325. }
  1326. /**
  1327. * 检查关闭按钮是否可用
  1328. *
  1329. * **注意**: 此方法会打开和关闭菜单,属于有副作用的操作
  1330. *
  1331. * @param orderName 订单名称
  1332. * @returns 按钮是否可用
  1333. */
  1334. async checkCloseButtonEnabled(orderName: string): Promise<boolean> {
  1335. // 找到订单行并打开菜单
  1336. const orderRow = this.orderTable.locator('tbody tr').filter({ hasText: orderName });
  1337. // 检查订单是否存在
  1338. const orderCount = await orderRow.count();
  1339. if (orderCount === 0) {
  1340. console.debug(`订单 "${orderName}" 不存在`);
  1341. return false;
  1342. }
  1343. const menuButton = orderRow.getByRole('button', { name: '打开菜单' });
  1344. try {
  1345. await menuButton.click();
  1346. } catch (error) {
  1347. console.debug(`无法打开订单 "${orderName}" 的菜单:`, error);
  1348. return false;
  1349. }
  1350. // 检查关闭菜单项是否可点击
  1351. const closeOption = this.page.getByRole('menuitem', { name: /关闭|关闭订单|完成/ });
  1352. const isVisible = await closeOption.isVisible().catch(() => false);
  1353. let isEnabled = false;
  1354. if (isVisible) {
  1355. // 检查是否有禁用属性或样式
  1356. const isDisabled = await closeOption.isDisabled().catch(() => false);
  1357. isEnabled = !isDisabled;
  1358. }
  1359. // 关闭菜单以便后续操作
  1360. await this.page.keyboard.press('Escape');
  1361. await this.page.waitForTimeout(TIMEOUTS.SHORT);
  1362. return isEnabled;
  1363. }
  1364. }