2
0

order-management.page.ts 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629
  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. // 先定位到 alertdialog,然后在其中查找取消按钮
  476. const dialog = this.page.locator('[role="alertdialog"]');
  477. const cancelButton = dialog.getByRole('button', { name: '取消' });
  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. 打开上传弹窗(第三个对话框)- 选择文件类型
  912. * 3. 在上传弹窗中,点击 FileSelector 的触发按钮
  913. * 4. 打开 FileSelector 对话框(第四个对话框)
  914. * 5. 在 FileSelector 对话框中使用 uploadFileToField 上传文件
  915. * 6. 点击上传后的文件进行选择
  916. * 7. 点击"确认选择"按钮
  917. * 8. 在上传弹窗中点击"提交"按钮
  918. *
  919. * @param personIdentifier 人员标识(可以是 ID 或姓名,方法会自动匹配)
  920. * @param fileName 文件名(相对于 web/tests/fixtures 目录)
  921. * @param mimeType 文件类型(默认为 image/jpeg,未使用,保留用于未来扩展)
  922. * @param fileType 文件类型(税务文件、薪资单、工作成果、合同签署、残疾证明、其他),默认为"其他"
  923. */
  924. async uploadAttachment(
  925. personIdentifier: string,
  926. fileName: string,
  927. _mimeType: string = 'image/jpeg',
  928. fileType: string = '其他'
  929. ) {
  930. // 动态导入 uploadFileToField 工具
  931. const { uploadFileToField } = await import('@d8d/e2e-test-utils');
  932. // 找到资源上传对话框(第二个对话框)
  933. const dialogs = this.page.locator('[role="dialog"]');
  934. const uploadDialog = dialogs.nth(1);
  935. // 在对话框中找到对应残疾人的行
  936. // 使用 ID 或姓名匹配
  937. const personRow = uploadDialog.locator('tr').filter({ hasText: personIdentifier });
  938. const rowCount = await personRow.count();
  939. if (rowCount === 0) {
  940. console.debug(`未找到人员 ${personIdentifier} 的行`);
  941. // 尝试打印所有行内容用于调试
  942. const allRows = uploadDialog.locator('tbody tr');
  943. const allRowCount = await allRows.count();
  944. console.debug(`资源上传对话框共有 ${allRowCount} 行`);
  945. for (let i = 0; i < Math.min(allRowCount, 3); i++) {
  946. const rowText = await allRows.nth(i).textContent();
  947. console.debug(`行 ${i} 内容:`, rowText);
  948. }
  949. return;
  950. }
  951. console.debug(`找到人员 ${personIdentifier} 的行`);
  952. // 在该人员行中找到对应文件类型的"上传文件"按钮
  953. // 文件类型列顺序:税务文件、薪资单、工作成果、合同签署、残疾证明、其他
  954. const uploadButton = personRow.getByRole('button', { name: '上传文件' });
  955. const buttonCount = await uploadButton.count();
  956. if (buttonCount === 0) {
  957. console.debug(`未找到"上传文件"按钮`);
  958. return;
  959. }
  960. console.debug(`找到 ${buttonCount} 个"上传文件"按钮`);
  961. // 根据文件类型选择对应的上传按钮
  962. let buttonIndex = 5; // 默认为"其他"(最后一个)
  963. switch (fileType) {
  964. case '税务文件':
  965. buttonIndex = 0;
  966. break;
  967. case '薪资单':
  968. buttonIndex = 1;
  969. break;
  970. case '工作成果':
  971. buttonIndex = 2;
  972. break;
  973. case '合同签署':
  974. buttonIndex = 3;
  975. break;
  976. case '残疾证明':
  977. buttonIndex = 4;
  978. break;
  979. case '其他':
  980. default:
  981. buttonIndex = 5;
  982. break;
  983. }
  984. // 点击对应的上传文件按钮,这会打开上传弹窗(第三个对话框)
  985. const targetButton = uploadButton.nth(buttonIndex);
  986. // 调试信息:检查按钮是否可见
  987. const isVisible = await targetButton.isVisible().catch(() => false);
  988. console.debug(`目标上传文件按钮可见性: ${isVisible}`);
  989. if (!isVisible) {
  990. console.debug(`上传文件按钮不可见,尝试滚动到视图`);
  991. await personRow.scrollIntoViewIfNeeded();
  992. await this.page.waitForTimeout(TIMEOUTS.SHORT);
  993. }
  994. await targetButton.click();
  995. console.debug(`已点击第 ${buttonIndex} 个上传文件按钮`);
  996. // 等待上传弹窗打开(第三个对话框)
  997. await this.page.waitForTimeout(TIMEOUTS.MEDIUM);
  998. // 在上传弹窗中点击 FileSelector 的触发按钮
  999. // FileSelector 组件的触发按钮文本是"选择或上传文件"
  1000. const fileSelectorTrigger = this.page.getByRole('button', { name: /选择或上传文件/ }).or(
  1001. this.page.getByText('选择或上传文件')
  1002. );
  1003. const triggerCount = await fileSelectorTrigger.count();
  1004. console.debug(`找到 ${triggerCount} 个 FileSelector 触发按钮`);
  1005. if (triggerCount === 0) {
  1006. console.debug('未找到 FileSelector 触发按钮');
  1007. return;
  1008. }
  1009. // 点击最新的 FileSelector 触发按钮(如果有多于一个的话)
  1010. await fileSelectorTrigger.nth(triggerCount - 1).click();
  1011. console.debug('已点击 FileSelector 触发按钮');
  1012. // FileSelector 对话框的 data-testid 是 "file-selector-dialog"
  1013. const fileSelectorDialog = this.page.getByTestId('file-selector-dialog');
  1014. // 等待 FileSelector 对话框打开(第四个对话框)
  1015. try {
  1016. await fileSelectorDialog.waitFor({ state: 'visible', timeout: TIMEOUTS.DIALOG });
  1017. console.debug('FileSelector 对话框已打开');
  1018. } catch (_error) {
  1019. console.debug('FileSelector 对话框未打开(超时)');
  1020. // 打印调试信息
  1021. const allDialogs = await this.page.locator('[role="dialog"]').count();
  1022. console.debug(`当前页面对话框数量: ${allDialogs}`);
  1023. return;
  1024. }
  1025. // 使用 uploadFileToField 上传文件
  1026. // MinioUploader 使用 data-testid="minio-uploader-input"(因为 testId 未被传递)
  1027. try {
  1028. await uploadFileToField(
  1029. this.page,
  1030. '[data-testid="minio-uploader-input"]',
  1031. fileName,
  1032. {
  1033. fixturesDir: 'tests/fixtures',
  1034. timeout: TIMEOUTS.DIALOG
  1035. }
  1036. );
  1037. console.debug(`文件 ${fileName} 上传操作已完成`);
  1038. } catch (uploadError) {
  1039. console.debug('文件上传失败:', uploadError);
  1040. // 即使上传失败,也尝试关闭对话框
  1041. await fileSelectorDialog.getByRole('button', { name: '取消' }).click().catch(() => {});
  1042. return;
  1043. }
  1044. // 等待上传处理完成,等待文件出现在对话框中
  1045. await this.page.waitForTimeout(TIMEOUTS.LONG);
  1046. // 点击上传后的文件进行选择(查找第一个可点击的文件)
  1047. // 上传成功后,文件会被添加到文件列表中并显示为选中状态(border-primary)
  1048. const uploadedFile = fileSelectorDialog.locator('.border-primary').or(
  1049. fileSelectorDialog.locator('img').first()
  1050. );
  1051. const fileExists = await uploadedFile.count() > 0;
  1052. if (fileExists) {
  1053. await uploadedFile.first().click();
  1054. console.debug('已点击上传后的文件');
  1055. } else {
  1056. // 如果没找到选中的文件,尝试查看对话框内容
  1057. const allImages = fileSelectorDialog.locator('img');
  1058. const imgCount = await allImages.count();
  1059. console.debug(`对话框中图片数量: ${imgCount}`);
  1060. // 尝试点击任何图片
  1061. if (imgCount > 0) {
  1062. await allImages.first().click();
  1063. console.debug('已点击第一张图片');
  1064. }
  1065. }
  1066. await this.page.waitForTimeout(TIMEOUTS.SHORT);
  1067. // 点击"确认选择"按钮
  1068. const confirmButton = fileSelectorDialog.getByRole('button', { name: '确认选择' });
  1069. const confirmButtonCount = await confirmButton.count();
  1070. if (confirmButtonCount > 0) {
  1071. await confirmButton.click();
  1072. console.debug('已点击确认选择按钮');
  1073. } else {
  1074. console.debug('未找到"确认选择"按钮');
  1075. }
  1076. // 等待 FileSelector 对话框关闭(回到上传弹窗)
  1077. await this.page.waitForTimeout(TIMEOUTS.MEDIUM);
  1078. // 在上传弹窗中点击"提交"按钮
  1079. const submitButton = this.page.getByRole('button', { name: /^提交$/ });
  1080. const submitButtonCount = await submitButton.count();
  1081. if (submitButtonCount > 0) {
  1082. await submitButton.click();
  1083. console.debug('已点击提交按钮');
  1084. // 等待提交完成(上传弹窗关闭)
  1085. await this.page.waitForTimeout(TIMEOUTS.LONG);
  1086. } else {
  1087. console.debug('未找到提交按钮');
  1088. }
  1089. console.debug(`附件上传流程完成: ${fileName}`);
  1090. }
  1091. /**
  1092. * 关闭资源上传对话框
  1093. */
  1094. async closeUploadDialog() {
  1095. // 资源上传对话框有"关闭"按钮
  1096. // 需要精确定位到第二个对话框(资源上传对话框)的关闭按钮
  1097. const dialogs = this.page.locator('[role="dialog"]');
  1098. const dialogCount = await dialogs.count();
  1099. if (dialogCount >= 2) {
  1100. // 资源上传对话框通常是第二个对话框
  1101. const uploadDialog = dialogs.nth(1);
  1102. const closeButton = uploadDialog.getByRole('button', { name: '关闭' });
  1103. const buttonCount = await closeButton.count();
  1104. if (buttonCount > 0) {
  1105. await closeButton.first().click();
  1106. console.debug('已关闭资源上传对话框');
  1107. } else {
  1108. console.debug('未找到资源上传对话框的关闭按钮,尝试按 Escape');
  1109. await this.page.keyboard.press('Escape');
  1110. }
  1111. } else {
  1112. // 如果只有一个对话框,尝试点击通用的关闭按钮
  1113. const closeButton = this.page.getByRole('button', { name: '关闭' });
  1114. const buttonCount = await closeButton.count();
  1115. if (buttonCount > 0) {
  1116. await closeButton.first().click();
  1117. console.debug('已关闭对话框(使用通用关闭按钮)');
  1118. }
  1119. }
  1120. await this.page.waitForTimeout(TIMEOUTS.MEDIUM);
  1121. }
  1122. // ===== 高级操作 =====
  1123. /**
  1124. * 创建订单(完整流程)
  1125. * @param data 订单数据
  1126. * @returns 表单提交结果
  1127. */
  1128. async createOrder(data: OrderData): Promise<FormSubmitResult> {
  1129. await this.openCreateDialog();
  1130. await this.fillOrderForm(data);
  1131. const result = await this.submitForm();
  1132. await this.waitForDialogClosed();
  1133. return result;
  1134. }
  1135. /**
  1136. * 编辑订单(完整流程)
  1137. * @param orderName 订单名称
  1138. * @param data 更新的订单数据
  1139. * @returns 表单提交结果
  1140. */
  1141. async editOrder(orderName: string, data: OrderData): Promise<FormSubmitResult> {
  1142. await this.openEditDialog(orderName);
  1143. await this.fillOrderForm(data);
  1144. const result = await this.submitForm();
  1145. await this.waitForDialogClosed();
  1146. return result;
  1147. }
  1148. /**
  1149. * 删除订单(完整流程)
  1150. * @param orderName 订单名称
  1151. * @returns 是否成功删除
  1152. */
  1153. async deleteOrder(orderName: string): Promise<boolean> {
  1154. await this.openDeleteDialog(orderName);
  1155. await this.confirmDelete();
  1156. // 等待并检查 Toast 消息
  1157. await this.page.waitForTimeout(TIMEOUTS.LONG);
  1158. const successToast = this.page.locator('[data-sonner-toast][data-type="success"]');
  1159. const hasSuccess = await successToast.count() > 0;
  1160. return hasSuccess;
  1161. }
  1162. // ===== 订单状态流转操作 =====
  1163. /**
  1164. * 打开激活订单确认对话框
  1165. * @param orderName 订单名称
  1166. */
  1167. async openActivateDialog(orderName: string): Promise<void> {
  1168. // 找到订单行并点击"打开菜单"按钮(与编辑/删除操作相同的模式)
  1169. const orderRow = this.orderTable.locator('tbody tr').filter({ hasText: orderName });
  1170. const menuButton = orderRow.getByRole('button', { name: '打开菜单' });
  1171. await menuButton.click();
  1172. // 等待菜单出现并点击"激活"选项
  1173. const activateOption = this.page.getByRole('menuitem', { name: /激活|激活订单/ });
  1174. await activateOption.waitFor({ state: 'visible', timeout: TIMEOUTS.ELEMENT_VISIBLE_SHORT });
  1175. await activateOption.click();
  1176. // 等待确认对话框出现
  1177. await this.page.waitForSelector('[role="alertdialog"]', { state: 'visible', timeout: TIMEOUTS.DIALOG });
  1178. }
  1179. /**
  1180. * 确认激活订单
  1181. */
  1182. async confirmActivate(): Promise<void> {
  1183. // 尝试多种可能的按钮名称
  1184. const confirmButton = this.page.locator('[role="alertdialog"]').getByRole('button', {
  1185. name: /^(确认激活|激活|确定|确认)$/
  1186. });
  1187. await confirmButton.click();
  1188. // 等待确认对话框关闭和网络请求完成
  1189. await this.page.waitForSelector('[role="alertdialog"]', { state: 'hidden', timeout: TIMEOUTS.DIALOG })
  1190. .catch(() => console.debug('激活确认对话框关闭超时'));
  1191. // networkidle 可能因为持续的网络活动而失败,使用更宽松的超时
  1192. await this.page.waitForLoadState('networkidle', { timeout: TIMEOUTS.TABLE_LOAD })
  1193. .catch(() => console.debug('networkidle 超时,继续执行'));
  1194. await this.page.waitForTimeout(TIMEOUTS.LONG);
  1195. }
  1196. /**
  1197. * 激活订单(完整流程)
  1198. * @param orderName 订单名称
  1199. * @returns 是否成功激活
  1200. */
  1201. async activateOrder(orderName: string): Promise<boolean> {
  1202. await this.openActivateDialog(orderName);
  1203. await this.confirmActivate();
  1204. // 等待并检查 Toast 消息
  1205. await this.page.waitForTimeout(TIMEOUTS.LONG);
  1206. const successToast = this.page.locator('[data-sonner-toast][data-type="success"]');
  1207. const hasSuccess = await successToast.count() > 0;
  1208. return hasSuccess;
  1209. }
  1210. /**
  1211. * 打开关闭订单确认对话框
  1212. * @param orderName 订单名称
  1213. */
  1214. async openCloseDialog(orderName: string): Promise<void> {
  1215. // 找到订单行并点击"打开菜单"按钮
  1216. const orderRow = this.orderTable.locator('tbody tr').filter({ hasText: orderName });
  1217. const menuButton = orderRow.getByRole('button', { name: '打开菜单' });
  1218. await menuButton.click();
  1219. // 等待菜单出现并点击"关闭"选项
  1220. const closeOption = this.page.getByRole('menuitem', { name: /关闭|关闭订单|完成/ });
  1221. await closeOption.waitFor({ state: 'visible', timeout: TIMEOUTS.ELEMENT_VISIBLE_SHORT });
  1222. await closeOption.click();
  1223. // 等待确认对话框出现
  1224. await this.page.waitForSelector('[role="alertdialog"]', { state: 'visible', timeout: TIMEOUTS.DIALOG });
  1225. }
  1226. /**
  1227. * 确认关闭订单
  1228. */
  1229. async confirmClose(): Promise<void> {
  1230. // 尝试多种可能的按钮名称
  1231. const confirmButton = this.page.locator('[role="alertdialog"]').getByRole('button', {
  1232. name: /^(确认关闭|关闭|确定|确认)$/
  1233. });
  1234. await confirmButton.click();
  1235. // 等待确认对话框关闭和网络请求完成
  1236. await this.page.waitForSelector('[role="alertdialog"]', { state: 'hidden', timeout: TIMEOUTS.DIALOG })
  1237. .catch(() => console.debug('关闭确认对话框关闭超时'));
  1238. await this.page.waitForLoadState('networkidle', { timeout: TIMEOUTS.TABLE_LOAD });
  1239. await this.page.waitForTimeout(TIMEOUTS.LONG);
  1240. }
  1241. /**
  1242. * 关闭订单(完整流程)
  1243. * @param orderName 订单名称
  1244. * @returns 是否成功关闭
  1245. */
  1246. async closeOrder(orderName: string): Promise<boolean> {
  1247. await this.openCloseDialog(orderName);
  1248. await this.confirmClose();
  1249. // 等待并检查 Toast 消息
  1250. await this.page.waitForTimeout(TIMEOUTS.LONG);
  1251. const successToast = this.page.locator('[data-sonner-toast][data-type="success"]');
  1252. const hasSuccess = await successToast.count() > 0;
  1253. return hasSuccess;
  1254. }
  1255. /**
  1256. * 获取订单的当前状态(从列表页面)
  1257. * @param orderName 订单名称
  1258. * @returns 订单状态值或 null
  1259. */
  1260. async getOrderStatus(orderName: string): Promise<OrderStatus | null> {
  1261. const orderRow = this.orderTable.locator('tbody tr').filter({ hasText: orderName });
  1262. // 等待行可见
  1263. await orderRow.waitFor({ state: 'visible', timeout: TIMEOUTS.ELEMENT_VISIBLE_SHORT }).catch(() => {
  1264. console.debug(`订单 "${orderName}" 行不可见`);
  1265. });
  1266. const rowCount = await orderRow.count();
  1267. if (rowCount === 0) {
  1268. console.debug(`订单 "${orderName}" 不存在`);
  1269. return null;
  1270. }
  1271. // 尝试多种策略定位状态列
  1272. // 策略1: 查找包含状态文本的单元格(但排除订单名称列)
  1273. const allCells = orderRow.locator('td');
  1274. const cellCount = await allCells.count();
  1275. for (let i = 1; i < cellCount; i++) { // 跳过第一列(通常是订单名称)
  1276. const cell = allCells.nth(i);
  1277. const cellText = await cell.textContent();
  1278. if (cellText) {
  1279. // 检查是否包含完整的状态标签(避免部分匹配)
  1280. for (const [statusValue, statusLabel] of Object.entries(ORDER_STATUS_LABELS)) {
  1281. // 使用更严格的匹配:必须是状态标签本身或包含完整标签
  1282. const trimmedText = cellText.trim();
  1283. if (trimmedText === statusLabel || trimmedText.includes(`${statusLabel}`)) {
  1284. // 验证不是订单名称列(额外检查)
  1285. const firstCellText = await allCells.nth(0).textContent();
  1286. if (firstCellText && !firstCellText.includes(orderName.substring(0, 3))) {
  1287. // 第一列不包含订单名称开头,说明列结构可能不同
  1288. return statusValue as OrderStatus;
  1289. }
  1290. // 跳过第一列后找到的状态标签才返回
  1291. return statusValue as OrderStatus;
  1292. }
  1293. }
  1294. }
  1295. }
  1296. // 策略2: 如果上述方法失败,尝试查找状态徽章/标签元素
  1297. // 查找具有状态样式特征的元素
  1298. const statusBadge = orderRow.locator('[class*="status"], [class*="badge"], span').filter({
  1299. hasText: Object.values(ORDER_STATUS_LABELS)
  1300. });
  1301. if (await statusBadge.count() > 0) {
  1302. const badgeText = await statusBadge.first().textContent();
  1303. if (badgeText) {
  1304. for (const [_statusValue, statusLabel] of Object.entries(ORDER_STATUS_LABELS)) {
  1305. if (badgeText.includes(statusLabel)) {
  1306. return statusValue as OrderStatus;
  1307. }
  1308. }
  1309. }
  1310. }
  1311. console.debug(`无法从订单 "${orderName}" 中解析状态`);
  1312. return null;
  1313. }
  1314. /**
  1315. * 验证订单状态
  1316. * @param orderName 订单名称
  1317. * @param expectedStatus 期望的状态
  1318. */
  1319. async expectOrderStatus(orderName: string, expectedStatus: OrderStatus): Promise<void> {
  1320. const actualStatus = await this.getOrderStatus(orderName);
  1321. if (actualStatus === null) {
  1322. throw new Error(`订单 "${orderName}" 未找到或状态列无法识别`);
  1323. }
  1324. if (actualStatus !== expectedStatus) {
  1325. throw new Error(
  1326. `订单 "${orderName}" 状态不匹配: 期望 "${ORDER_STATUS_LABELS[expectedStatus]}", 实际 "${ORDER_STATUS_LABELS[actualStatus]}"`
  1327. );
  1328. }
  1329. }
  1330. /**
  1331. * 检查激活按钮是否可用
  1332. *
  1333. * **注意**: 此方法会打开和关闭菜单,属于有副作用的操作
  1334. *
  1335. * @param orderName 订单名称
  1336. * @returns 按钮是否可用
  1337. */
  1338. async checkActivateButtonEnabled(orderName: string): Promise<boolean> {
  1339. // 找到订单行并打开菜单
  1340. const orderRow = this.orderTable.locator('tbody tr').filter({ hasText: orderName });
  1341. // 检查订单是否存在
  1342. const orderCount = await orderRow.count();
  1343. if (orderCount === 0) {
  1344. console.debug(`订单 "${orderName}" 不存在`);
  1345. return false;
  1346. }
  1347. const menuButton = orderRow.getByRole('button', { name: '打开菜单' });
  1348. try {
  1349. await menuButton.click();
  1350. } catch (_error) {
  1351. console.debug(`无法打开订单 "${orderName}" 的菜单:`, error);
  1352. return false;
  1353. }
  1354. // 检查激活菜单项是否可点击
  1355. const activateOption = this.page.getByRole('menuitem', { name: /激活|激活订单/ });
  1356. const isVisible = await activateOption.isVisible().catch(() => false);
  1357. let isEnabled = false;
  1358. if (isVisible) {
  1359. // 检查是否有禁用属性或样式
  1360. const isDisabled = await activateOption.isDisabled().catch(() => false);
  1361. isEnabled = !isDisabled;
  1362. }
  1363. // 关闭菜单以便后续操作
  1364. await this.page.keyboard.press('Escape');
  1365. await this.page.waitForTimeout(TIMEOUTS.SHORT);
  1366. return isEnabled;
  1367. }
  1368. /**
  1369. * 检查关闭按钮是否可用
  1370. *
  1371. * **注意**: 此方法会打开和关闭菜单,属于有副作用的操作
  1372. *
  1373. * @param orderName 订单名称
  1374. * @returns 按钮是否可用
  1375. */
  1376. async checkCloseButtonEnabled(orderName: string): Promise<boolean> {
  1377. // 找到订单行并打开菜单
  1378. const orderRow = this.orderTable.locator('tbody tr').filter({ hasText: orderName });
  1379. // 检查订单是否存在
  1380. const orderCount = await orderRow.count();
  1381. if (orderCount === 0) {
  1382. console.debug(`订单 "${orderName}" 不存在`);
  1383. return false;
  1384. }
  1385. const menuButton = orderRow.getByRole('button', { name: '打开菜单' });
  1386. try {
  1387. await menuButton.click();
  1388. } catch (_error) {
  1389. console.debug(`无法打开订单 "${orderName}" 的菜单:`, error);
  1390. return false;
  1391. }
  1392. // 检查关闭菜单项是否可点击
  1393. const closeOption = this.page.getByRole('menuitem', { name: /关闭|关闭订单|完成/ });
  1394. const isVisible = await closeOption.isVisible().catch(() => false);
  1395. let isEnabled = false;
  1396. if (isVisible) {
  1397. // 检查是否有禁用属性或样式
  1398. const isDisabled = await closeOption.isDisabled().catch(() => false);
  1399. isEnabled = !isDisabled;
  1400. }
  1401. // 关闭菜单以便后续操作
  1402. await this.page.keyboard.press('Escape');
  1403. await this.page.waitForTimeout(TIMEOUTS.SHORT);
  1404. return isEnabled;
  1405. }
  1406. }