order-management.page.ts 44 KB

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