order-management.page.ts 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686
  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 }).first();
  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 }).first();
  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.platformName) {
  328. await selectRadixOption(this.page, '平台', data.platformName);
  329. }
  330. // 选择公司
  331. if (data.companyName) {
  332. await selectRadixOption(this.page, '公司', data.companyName);
  333. }
  334. // 选择渠道
  335. if (data.channelName) {
  336. await selectRadixOption(this.page, '渠道', data.channelName);
  337. }
  338. // 填写预计开始日期
  339. if (data.expectedStartDate) {
  340. const dateInput = this.page.getByLabel(/预计开始日期|开始日期/);
  341. await dateInput.fill(data.expectedStartDate);
  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. const selectPersonButton = this.page.getByRole('button', { name: '选择残疾人' });
  356. const hasSelectPersonButton = await selectPersonButton.count();
  357. if (hasSelectPersonButton > 0) {
  358. console.debug('[创建订单] 检测到需要选择残疾人,点击"选择残疾人"按钮');
  359. await selectPersonButton.click();
  360. await this.page.waitForTimeout(TIMEOUTS.MEDIUM);
  361. // 等待残疾人选择器对话框打开
  362. // 选择第一个可用的残疾人(通常是测试数据)
  363. // 尝试多种方式定位残疾人列表
  364. const firstCheckbox = this.page.locator('input[type="checkbox"]').first();
  365. const checkboxCount = await firstCheckbox.count();
  366. if (checkboxCount > 0) {
  367. // 使用第一个复选框
  368. await firstCheckbox.click();
  369. console.debug('[创建订单] 已选择第一个残疾人');
  370. // 查找确认按钮并点击(可能是"确定"、"确认"等)
  371. const confirmButton = this.page.getByRole('button', { name: /^(确定|确认|选择)$/ });
  372. const confirmCount = await confirmButton.count();
  373. if (confirmCount > 0) {
  374. await confirmButton.first().click();
  375. console.debug('[创建订单] 已确认选择残疾人');
  376. } else {
  377. // 如果没有确认按钮,尝试按 Enter 键
  378. await this.page.keyboard.press('Enter');
  379. console.debug('[创建订单] 按 Enter 键确认选择');
  380. }
  381. } else {
  382. console.debug('[创建订单] 未找到残疾人复选框,尝试其他方式');
  383. // 尝试查找残疾人列表项并点击第一个
  384. const firstPersonItem = this.page.locator('[role="option"], .option-item, .person-item').first();
  385. const itemCount = await firstPersonItem.count();
  386. if (itemCount > 0) {
  387. await firstPersonItem.click();
  388. console.debug('[创建订单] 已点击第一个残疾人选项');
  389. } else {
  390. // 如果还是没有,尝试关闭对话框并继续(有些实现可能有默认选择)
  391. console.debug('[创建订单] 未找到残疾人选项,尝试关闭对话框并继续');
  392. await this.page.keyboard.press('Escape');
  393. }
  394. }
  395. await this.page.waitForTimeout(TIMEOUTS.MEDIUM);
  396. } else {
  397. console.debug('[创建订单] 未检测到"选择残疾人"按钮,可能已有人选或不在创建模式');
  398. }
  399. }
  400. /**
  401. * 提交表单
  402. * @returns 表单提交结果
  403. */
  404. async submitForm(): Promise<FormSubmitResult> {
  405. // 收集网络响应
  406. const responses: NetworkResponse[] = [];
  407. // 监听所有网络请求
  408. const responseHandler = async (response: Response) => {
  409. const url = response.url();
  410. // 监听订单管理相关的 API 请求
  411. if (url.includes('/orders') || url.includes('order')) {
  412. const _requestBody = response.request()?.postData();
  413. const responseBody = await response.text().catch(() => '');
  414. let jsonBody = null;
  415. try {
  416. jsonBody = JSON.parse(responseBody);
  417. } catch {
  418. // 不是 JSON 响应
  419. }
  420. responses.push({
  421. url,
  422. method: response.request()?.method() ?? 'UNKNOWN',
  423. status: response.status(),
  424. ok: response.ok(),
  425. responseHeaders: await response.allHeaders().catch(() => ({})),
  426. responseBody: jsonBody || responseBody,
  427. });
  428. }
  429. };
  430. this.page.on('response', responseHandler);
  431. try {
  432. // 点击提交按钮(创建或更新)
  433. const submitButton = this.page.getByRole('button', { name: /^(创建|更新|保存)$/ });
  434. await submitButton.click();
  435. // 等待网络请求完成(使用较宽松的超时,因为有些操作可能不触发网络请求)
  436. try {
  437. await this.page.waitForLoadState('domcontentloaded', { timeout: TIMEOUTS.DIALOG });
  438. } catch {
  439. // domcontentloaded 超时不是致命错误,继续检查 Toast 消息
  440. console.debug('domcontentloaded 超时,继续检查 Toast 消息');
  441. }
  442. } finally {
  443. // 确保监听器总是被移除,防止内存泄漏
  444. this.page.off('response', responseHandler);
  445. }
  446. // 等待 Toast 消息显示
  447. await this.page.waitForTimeout(TIMEOUTS.VERY_LONG);
  448. // 检查 Toast 消息
  449. const errorToast = this.page.locator('[data-sonner-toast][data-type="error"]');
  450. const successToast = this.page.locator('[data-sonner-toast][data-type="success"]');
  451. const hasError = await errorToast.count() > 0;
  452. const hasSuccess = await successToast.count() > 0;
  453. let errorMessage: string | null = null;
  454. let successMessage: string | null = null;
  455. if (hasError) {
  456. errorMessage = await errorToast.first().textContent();
  457. }
  458. if (hasSuccess) {
  459. successMessage = await successToast.first().textContent();
  460. }
  461. return {
  462. success: hasSuccess || (!hasError && !hasSuccess),
  463. hasError,
  464. hasSuccess,
  465. errorMessage: errorMessage ?? undefined,
  466. successMessage: successMessage ?? undefined,
  467. responses,
  468. };
  469. }
  470. /**
  471. * 取消对话框
  472. */
  473. async cancelDialog() {
  474. const cancelButton = this.page.getByRole('button', { name: '取消' });
  475. await cancelButton.click();
  476. await this.waitForDialogClosed();
  477. }
  478. /**
  479. * 等待对话框关闭
  480. */
  481. async waitForDialogClosed() {
  482. // 先等待一段时间让对话框有机会关闭
  483. await this.page.waitForTimeout(TIMEOUTS.LONG);
  484. // 检查是否还有对话框可见
  485. const dialogs = this.page.locator('[role="dialog"]');
  486. const dialogCount = await dialogs.count();
  487. if (dialogCount === 0) {
  488. // 没有对话框了,已经关闭
  489. console.debug('对话框已关闭(无对话框元素)');
  490. return;
  491. }
  492. // 尝试等待对话框隐藏或从 DOM 中移除
  493. try {
  494. await dialogs.first().waitFor({ state: 'hidden', timeout: TIMEOUTS.ELEMENT_VISIBLE_SHORT });
  495. console.debug('对话框已关闭');
  496. } catch {
  497. // 超时不是致命错误,对话框可能已经以其他方式关闭
  498. console.debug('对话框关闭等待超时,继续执行');
  499. }
  500. await this.page.waitForTimeout(TIMEOUTS.MEDIUM);
  501. }
  502. /**
  503. * 确认删除操作
  504. */
  505. async confirmDelete() {
  506. // 尝试多种可能的按钮名称
  507. const confirmButton = this.page.locator('[role="alertdialog"]').getByRole('button', {
  508. name: /^(确认删除|删除|确定|确认)$/
  509. });
  510. await confirmButton.click();
  511. // 等待确认对话框关闭和网络请求完成
  512. await this.page.waitForSelector('[role="alertdialog"]', { state: 'hidden', timeout: TIMEOUTS.DIALOG })
  513. .catch(() => console.debug('删除确认对话框关闭超时'));
  514. await this.page.waitForLoadState('networkidle', { timeout: TIMEOUTS.TABLE_LOAD });
  515. await this.page.waitForTimeout(TIMEOUTS.LONG);
  516. }
  517. /**
  518. * 取消删除操作
  519. */
  520. async cancelDelete() {
  521. // 先定位到 alertdialog,然后在其中查找取消按钮
  522. const dialog = this.page.locator('[role="alertdialog"]');
  523. const cancelButton = dialog.getByRole('button', { name: '取消' });
  524. await cancelButton.click();
  525. await this.page.waitForSelector('[role="alertdialog"]', { state: 'hidden', timeout: TIMEOUTS.DIALOG })
  526. .catch(() => console.debug('删除确认对话框关闭超时(取消操作)'));
  527. }
  528. /**
  529. * 验证订单是否存在
  530. * @param orderName 订单名称
  531. * @returns 订单是否存在
  532. */
  533. async orderExists(orderName: string): Promise<boolean> {
  534. const orderRow = this.orderTable.locator('tbody tr').filter({ hasText: orderName }).first();
  535. return (await orderRow.count()) > 0;
  536. }
  537. // ===== 订单详情 =====
  538. /**
  539. * 打开订单详情对话框
  540. * @param orderName 订单名称
  541. */
  542. async openDetailDialog(orderName: string) {
  543. // 找到订单行
  544. const orderRow = this.orderTable.locator('tbody tr').filter({ hasText: orderName }).first();
  545. // 先点击操作菜单触发按钮("打开菜单" 或 MoreHorizontal 图标)
  546. const menuTrigger = orderRow.getByRole('button', { name: /打开菜单/ });
  547. await menuTrigger.click();
  548. // 等待菜单显示
  549. await this.page.waitForTimeout(TIMEOUTS.VERY_SHORT);
  550. // 点击"查看详情"菜单项
  551. const detailButton = this.page.getByRole('menuitem', { name: /查看详情/ });
  552. await detailButton.click();
  553. await this.page.waitForSelector('[role="dialog"]', { state: 'visible', timeout: TIMEOUTS.DIALOG });
  554. }
  555. /**
  556. * 获取订单详情对话框中的基本信息
  557. * @returns 订单基本信息
  558. */
  559. async getOrderDetailInfo(): Promise<{
  560. name?: string;
  561. status?: string;
  562. workStatus?: string;
  563. expectedStartDate?: string;
  564. platform?: string;
  565. company?: string;
  566. channel?: string;
  567. }> {
  568. const dialog = this.page.locator('[role="dialog"]');
  569. const result: Record<string, string | undefined> = {};
  570. // 使用 data-testid 直接定位元素(更可靠)
  571. // DOM 结构: <div className="flex items-center justify-between">
  572. // <span className="text-sm font-medium">标签:</span>
  573. // <span data-testid="order-detail-xxx">值</span>
  574. // </div>
  575. // 订单名称 - 使用 data-testid
  576. const nameElement = dialog.locator('[data-testid="order-detail-name"]');
  577. if (await nameElement.count() > 0) {
  578. result.name = (await nameElement.textContent())?.trim();
  579. }
  580. // 订单状态
  581. const statusElement = dialog.locator('[data-testid="order-detail-status"]');
  582. if (await statusElement.count() > 0) {
  583. result.status = (await statusElement.textContent())?.trim();
  584. }
  585. // 工作状态 - 查找包含"工作状态"标签的行
  586. const workStatusRow = dialog.locator('div').filter({ hasText: /工作状态:/ }).first();
  587. if (await workStatusRow.count() > 0) {
  588. const workStatusElement = workStatusRow.locator('span').nth(1);
  589. result.workStatus = (await workStatusElement.textContent())?.trim();
  590. }
  591. // 预计开始日期 - 使用 data-testid
  592. const expectedStartDateElement = dialog.locator('[data-testid="order-detail-expected-start"]');
  593. if (await expectedStartDateElement.count() > 0) {
  594. result.expectedStartDate = (await expectedStartDateElement.textContent())?.trim();
  595. }
  596. // 平台 - 使用 data-testid
  597. const platformElement = dialog.locator('[data-testid="order-detail-platform"]');
  598. if (await platformElement.count() > 0) {
  599. result.platform = (await platformElement.textContent())?.trim();
  600. }
  601. // 公司 - 使用 data-testid
  602. const companyElement = dialog.locator('[data-testid="order-detail-company"]');
  603. if (await companyElement.count() > 0) {
  604. result.company = (await companyElement.textContent())?.trim();
  605. }
  606. // 渠道 - 使用 data-testid
  607. const channelElement = dialog.locator('[data-testid="order-detail-channel"]');
  608. if (await channelElement.count() > 0) {
  609. result.channel = (await channelElement.textContent())?.trim();
  610. }
  611. return result;
  612. }
  613. /**
  614. * 从订单详情对话框中获取关联人员列表
  615. * @returns 人员信息列表
  616. */
  617. async getPersonListFromDetail(): Promise<Array<{
  618. name?: string;
  619. workStatus?: string;
  620. hireDate?: string;
  621. salary?: string;
  622. phone?: string;
  623. }>> {
  624. const dialog = this.page.locator('[role="dialog"]');
  625. const result: Array<{ name?: string; workStatus?: string; hireDate?: string; salary?: string; phone?: string }> = [];
  626. // 查找所有表格,对话框中可能有两个表格:
  627. // 1. "待添加人员列表" - 临时表格,包含未确认的人员
  628. // 2. "绑定人员列表" - 实际已绑定到订单的人员
  629. // 我们需要第二个"绑定人员列表"表格
  630. const allTables = dialog.locator('table');
  631. const tableCount = await allTables.count();
  632. // 查找"绑定人员列表"表格(通常是包含"工作状态"列的表格)
  633. let personTable;
  634. for (let i = 0; i < tableCount; i++) {
  635. const table = allTables.nth(i);
  636. const tableText = await table.textContent();
  637. // 绑定人员列表表格包含"工作状态"列,而待添加人员列表没有
  638. if (tableText && tableText.includes('工作状态')) {
  639. personTable = table;
  640. break;
  641. }
  642. }
  643. const personList = dialog.locator('[class*="person"], [class*="employee"], [data-testid*="person"]');
  644. // 优先使用表格形式
  645. if (personTable) {
  646. const rows = personTable.locator('tbody tr');
  647. const rowCount = await rows.count();
  648. for (let i = 0; i < rowCount; i++) {
  649. const row = rows.nth(i);
  650. const cells = row.locator('td');
  651. const cellCount = await cells.count();
  652. const personInfo: { name?: string; workStatus?: string; hireDate?: string; salary?: string; phone?: string } = {};
  653. // 根据列数量和数据类型提取信息
  654. // 表格列:ID 姓名 性别 残疾类型 联系电话 入职日期 离职日期 工作状态 薪资
  655. for (let j = 0; j < cellCount; j++) {
  656. const cellText = await cells.nth(j).textContent();
  657. if (!cellText) continue;
  658. const trimmedText = cellText.trim();
  659. // 尝试识别列内容
  660. // ID 在第一列(j === 0),姓名在第二列(j === 1)
  661. if (j === 1 && trimmedText) {
  662. personInfo.name = trimmedText;
  663. }
  664. // 联系电话在第 5 列(j === 4),是 11 位数字
  665. if (j === 4 && /^\d{11}$/.test(trimmedText)) {
  666. personInfo.phone = trimmedText;
  667. }
  668. // 工作状态检查
  669. for (const [_statusValue, statusLabel] of Object.entries(WORK_STATUS_LABELS)) {
  670. if (trimmedText.includes(statusLabel)) {
  671. personInfo.workStatus = statusLabel;
  672. break;
  673. }
  674. }
  675. // 日期检查(符合日期格式)
  676. if (/^\d{4}-\d{2}-\d{2}$/.test(trimmedText) || /^\d{4}\/\d{2}\/\d{2}$/.test(trimmedText)) {
  677. if (!personInfo.hireDate) {
  678. personInfo.hireDate = trimmedText;
  679. }
  680. }
  681. // 薪资检查(在最后一列,包含数字且可能是薪资)
  682. // 薪资通常是较大的数字,不应该是11位电话号码
  683. if (j === cellCount - 1 && /^\d+(\.\d+)?$/.test(trimmedText.replace(/,/g, ''))) {
  684. const numValue = trimmedText.replace(/,/g, '');
  685. // 排除11位电话号码(如13800019729)
  686. if (numValue.length < 11) {
  687. personInfo.salary = trimmedText;
  688. }
  689. }
  690. }
  691. if (personInfo.name || personInfo.workStatus) {
  692. result.push(personInfo);
  693. }
  694. }
  695. } else if (await personList.count() > 0) {
  696. // 如果是列表形式而非表格
  697. const listItems = personList.locator('[class*="item"], [class*="row"], li, div');
  698. const itemCount = await listItems.count();
  699. for (let i = 0; i < itemCount; i++) {
  700. const item = listItems.nth(i);
  701. const itemText = await item.textContent();
  702. if (itemText && itemText.trim()) {
  703. result.push({ name: itemText.trim() });
  704. }
  705. }
  706. }
  707. return result;
  708. }
  709. /**
  710. * 从订单详情对话框中获取附件列表
  711. * @returns 附件信息列表
  712. */
  713. async getAttachmentListFromDetail(): Promise<Array<{
  714. fileName?: string;
  715. uploadDate?: string;
  716. uploader?: string;
  717. }>> {
  718. const dialog = this.page.locator('[role="dialog"]');
  719. const result: Array<{ fileName?: string; uploadDate?: string; uploader?: string }> = [];
  720. // 查找附件列表区域
  721. // 尝试多种可能的定位策略
  722. const attachmentTable = dialog.locator('table').filter({ hasText: /附件|文件/ });
  723. const attachmentList = dialog.locator('[class*="attachment"], [class*="file"], [data-testid*="attachment"]');
  724. // 优先使用表格形式
  725. if (await attachmentTable.count() > 0) {
  726. const rows = attachmentTable.locator('tbody tr');
  727. const rowCount = await rows.count();
  728. for (let i = 0; i < rowCount; i++) {
  729. const row = rows.nth(i);
  730. const cells = row.locator('td');
  731. const cellCount = await cells.count();
  732. const attachmentInfo: { fileName?: string; uploadDate?: string; uploader?: string } = {};
  733. for (let j = 0; j < cellCount; j++) {
  734. const cellText = await cells.nth(j).textContent();
  735. if (!cellText) continue;
  736. const trimmedText = cellText.trim();
  737. // 文件名通常在第一列
  738. if (j === 0 && trimmedText) {
  739. attachmentInfo.fileName = trimmedText;
  740. }
  741. // 日期检查
  742. if (/^\d{4}-\d{2}-\d{2}/.test(trimmedText) || /^\d{4}\/\d{2}\/\d{2}/.test(trimmedText)) {
  743. if (!attachmentInfo.uploadDate) {
  744. attachmentInfo.uploadDate = trimmedText;
  745. }
  746. }
  747. // 上传者通常是文本用户名
  748. if (j > 0 && trimmedText && !attachmentInfo.uploader && !attachmentInfo.uploadDate && !/^\d{4}/.test(trimmedText)) {
  749. attachmentInfo.uploader = trimmedText;
  750. }
  751. }
  752. if (attachmentInfo.fileName) {
  753. result.push(attachmentInfo);
  754. }
  755. }
  756. } else if (await attachmentList.count() > 0) {
  757. // 如果是列表形式
  758. const listItems = attachmentList.locator('[class*="item"], [class*="row"], li, div');
  759. const itemCount = await listItems.count();
  760. for (let i = 0; i < itemCount; i++) {
  761. const item = listItems.nth(i);
  762. const itemText = await item.textContent();
  763. if (itemText && itemText.trim()) {
  764. result.push({ fileName: itemText.trim() });
  765. }
  766. }
  767. }
  768. return result;
  769. }
  770. /**
  771. * 关闭订单详情对话框
  772. */
  773. async closeDetailDialog(): Promise<void> {
  774. // 尝试多种关闭方式
  775. // 方式1: 点击右上角 X 按钮
  776. const closeButton = this.page.locator('[role="dialog"]').getByRole('button', { name: '关闭' }).first();
  777. const closeButtonCount = await closeButton.count();
  778. if (closeButtonCount > 0) {
  779. await closeButton.click();
  780. } else {
  781. // 方式2: 点击取消按钮
  782. const cancelButton = this.page.locator('[role="dialog"]').getByRole('button', { name: '取消' }).first();
  783. const cancelButtonCount = await cancelButton.count();
  784. if (cancelButtonCount > 0) {
  785. await cancelButton.click();
  786. } else {
  787. // 方式3: 按 Escape 键
  788. await this.page.keyboard.press('Escape');
  789. }
  790. }
  791. // 等待对话框关闭
  792. await this.waitForDialogClosed();
  793. }
  794. // ===== 人员关联管理 =====
  795. /**
  796. * 打开人员管理对话框
  797. *
  798. * **使用场景:**
  799. * - **从订单列表页打开**: 传入 `orderName` 参数,方法会先找到对应订单行,再点击人员管理按钮
  800. * - **从订单详情页打开**: 不传参数,方法会直接点击页面中的人员管理按钮
  801. *
  802. * @param orderName 订单名称(可选)。从列表页打开时需要传入,从详情页打开时不传
  803. *
  804. * @example
  805. * ```typescript
  806. * // 从订单列表页打开
  807. * await orderPage.openPersonManagementDialog('测试订单');
  808. *
  809. * // 从订单详情页打开
  810. * await orderPage.openDetailDialog('测试订单');
  811. * await orderPage.openPersonManagementDialog();
  812. * ```
  813. */
  814. async openPersonManagementDialog(orderName?: string) {
  815. // 人员管理功能直接集成在订单详情对话框中
  816. // 如果提供了订单名称,打开订单详情对话框
  817. if (orderName) {
  818. await this.openDetailDialog(orderName);
  819. }
  820. // 人员管理功能已在详情对话框中,无需额外操作
  821. }
  822. /**
  823. * 添加人员到订单
  824. * @param personData 人员数据
  825. */
  826. async addPersonToOrder(personData: OrderPersonData) {
  827. // 点击添加人员按钮
  828. const addButton = this.page.getByRole('button', { name: /添加人员|新增人员/ });
  829. await addButton.click();
  830. await this.page.waitForTimeout(TIMEOUTS.SHORT);
  831. // 选择残疾人(支持通过名称选择)
  832. if (personData.disabledPersonName) {
  833. await selectRadixOption(this.page, '残疾人|选择残疾人', personData.disabledPersonName);
  834. } else if (personData.disabledPersonId) {
  835. // 如果只提供了 ID,尝试在对话框中选择第一个残疾人
  836. const firstCheckbox = this.page.locator('[role="dialog"]').locator('table tbody tr').first().locator('input[type="checkbox"]').first();
  837. try {
  838. await firstCheckbox.waitFor({ state: 'visible', timeout: TIMEOUTS.ELEMENT_VISIBLE_SHORT });
  839. await firstCheckbox.check();
  840. } catch {
  841. console.debug('没有可用的残疾人数据');
  842. }
  843. }
  844. // 填写入职日期
  845. if (personData.hireDate) {
  846. const hireDateInput = this.page.getByLabel(/入职日期/);
  847. await hireDateInput.fill(personData.hireDate);
  848. }
  849. // 填写薪资
  850. if (personData.salary !== undefined) {
  851. const salaryInput = this.page.getByLabel(/薪资|工资/);
  852. await salaryInput.fill(String(personData.salary));
  853. }
  854. // 选择工作状态
  855. if (personData.workStatus) {
  856. const workStatusLabel = WORK_STATUS_LABELS[personData.workStatus];
  857. await selectRadixOption(this.page, '工作状态', workStatusLabel);
  858. }
  859. // 提交
  860. const submitButton = this.page.getByRole('button', { name: /^(添加|确定|保存)$/ });
  861. await submitButton.click();
  862. await this.page.waitForLoadState('networkidle');
  863. await this.page.waitForTimeout(TIMEOUTS.LONG);
  864. }
  865. /**
  866. * 修改人员工作状态
  867. * @param personName 人员姓名
  868. * @param newStatus 新的工作状态
  869. */
  870. async updatePersonWorkStatus(personName: string, newStatus: WorkStatus) {
  871. const dialog = this.page.locator('[role="dialog"]');
  872. // 等待对话框完全加载
  873. await dialog.waitFor({ state: 'visible', timeout: TIMEOUTS.DIALOG });
  874. // 从 error-context.md 可知:
  875. // 1. 对话框中有"绑定人员列表"表格
  876. // 2. 表格列:ID 姓名 性别 残疾类型 联系电话 入职日期 离职日期 工作状态 薪资
  877. // 3. 工作状态列直接是 combobox,不需要点击编辑按钮
  878. // 查找所有表格
  879. const allTables = dialog.locator('table');
  880. const allTableCount = await allTables.count();
  881. console.debug(`对话框中总共有 ${allTableCount} 个表格`);
  882. let personTable = allTables.first();
  883. // 找到包含"绑定人员"或"工作状态"列的表格(第二个表格是绑定人员列表)
  884. for (let i = 0; i < allTableCount; i++) {
  885. const table = allTables.nth(i);
  886. const tableText = await table.textContent();
  887. if (tableText && (tableText.includes('绑定人员') || tableText.includes('工作状态'))) {
  888. personTable = table;
  889. console.debug(`找到人员表格(索引 ${i})`);
  890. break;
  891. }
  892. }
  893. // 在表格中查找包含指定人员名称的行
  894. const targetRow = personTable.locator('tbody tr').filter({ hasText: personName }).first();
  895. const rowCount = await targetRow.count();
  896. console.debug(`找到 ${rowCount} 个匹配的人员行`);
  897. if (rowCount === 0) {
  898. throw new Error(`未找到人员 ${personName}`);
  899. }
  900. // 等待行可见
  901. await targetRow.waitFor({ state: 'visible', timeout: TIMEOUTS.DIALOG });
  902. // 从 error-context.md 可知,工作状态在单元格中是一个 combobox
  903. // 表格列:ID 姓名 性别 残疾类型 联系电话 入职日期 离职日期 工作状态 薪资
  904. // 工作状态是倒数第二列(薪资是最后一列)
  905. const cells = targetRow.locator('td');
  906. const cellCount = await cells.count();
  907. console.debug(`人员行有 ${cellCount} 个单元格`);
  908. // 工作状态在倒数第二列
  909. const workStatusCell = cells.nth(cellCount - 2);
  910. const workStatusCombobox = workStatusCell.getByRole('combobox');
  911. const comboboxCount = await workStatusCombobox.count();
  912. console.debug(`工作状态 combobox 数量: ${comboboxCount}`);
  913. if (comboboxCount === 0) {
  914. throw new Error(`未找到人员 ${personName} 的工作状态选择器`);
  915. }
  916. await workStatusCombobox.click({ timeout: TIMEOUTS.DIALOG });
  917. console.debug('工作状态 combobox 已点击');
  918. // 等待下拉选项显示
  919. await this.page.waitForTimeout(TIMEOUTS.MEDIUM);
  920. // 使用中文标签选择选项
  921. // 注意:UI 中的工作状态选项与 WORK_STATUS_LABELS 不同
  922. // UI 选项:未入职、已入职、工作中、已离职
  923. // WORK_STATUS_LABELS:未就业、待就业、已就业、已离职
  924. const statusMapping: Record<WorkStatus, string> = {
  925. not_working: '未入职',
  926. pre_working: '已入职',
  927. working: '工作中',
  928. resigned: '已离职',
  929. };
  930. const newWorkStatusLabel = statusMapping[newStatus];
  931. console.debug(`尝试选择状态: ${newWorkStatusLabel}`);
  932. const optionLocator = this.page.getByRole('option', { name: newWorkStatusLabel });
  933. const optionCount = await optionLocator.count();
  934. console.debug(`找到 ${optionCount} 个选项`);
  935. if (optionCount === 0) {
  936. throw new Error(`未找到工作状态选项: ${newWorkStatusLabel}`);
  937. }
  938. await optionLocator.first().click({ timeout: TIMEOUTS.DIALOG });
  939. console.debug(`工作状态已更新为: ${newWorkStatusLabel}`);
  940. // 使用较短的超时时间等待网络空闲
  941. await this.page.waitForLoadState('domcontentloaded', { timeout: TIMEOUTS.DIALOG })
  942. .catch(() => console.debug('domcontentloaded 等待超时,继续'));
  943. await this.page.waitForTimeout(TIMEOUTS.MEDIUM);
  944. }
  945. // ===== 附件管理 =====
  946. /**
  947. * 打开资源上传对话框
  948. * "资源上传"按钮在订单详情对话框中
  949. */
  950. async openAddAttachmentDialog() {
  951. // 使用"资源上传"按钮
  952. const attachmentButton = this.page.getByRole('button', { name: /资源上传/ });
  953. await attachmentButton.click();
  954. // 等待第二个对话框(资源上传对话框)打开
  955. await this.page.waitForTimeout(TIMEOUTS.MEDIUM);
  956. }
  957. /**
  958. * 上传附件
  959. *
  960. * 实际的 UI 流程:
  961. * 1. 在资源上传对话框中,点击人员行中对应文件类型的"上传文件"按钮
  962. * 2. 打开上传弹窗(第三个对话框)- 选择文件类型
  963. * 3. 在上传弹窗中,点击 FileSelector 的触发按钮
  964. * 4. 打开 FileSelector 对话框(第四个对话框)
  965. * 5. 在 FileSelector 对话框中使用 uploadFileToField 上传文件
  966. * 6. 点击上传后的文件进行选择
  967. * 7. 点击"确认选择"按钮
  968. * 8. 在上传弹窗中点击"提交"按钮
  969. *
  970. * @param personIdentifier 人员标识(可以是 ID 或姓名,方法会自动匹配)
  971. * @param fileName 文件名(相对于 web/tests/fixtures 目录)
  972. * @param mimeType 文件类型(默认为 image/jpeg,未使用,保留用于未来扩展)
  973. * @param fileType 文件类型(税务文件、薪资单、工作成果、合同签署、残疾证明、其他),默认为"其他"
  974. */
  975. async uploadAttachment(
  976. personIdentifier: string,
  977. fileName: string,
  978. _mimeType: string = 'image/jpeg',
  979. fileType: string = '其他'
  980. ) {
  981. // 动态导入 uploadFileToField 工具
  982. const { uploadFileToField } = await import('@d8d/e2e-test-utils');
  983. // 找到资源上传对话框(第二个对话框)
  984. const dialogs = this.page.locator('[role="dialog"]');
  985. const uploadDialog = dialogs.nth(1);
  986. // 在对话框中找到对应残疾人的行
  987. // 使用 ID 或姓名匹配
  988. const personRow = uploadDialog.locator('tr').filter({ hasText: personIdentifier });
  989. const rowCount = await personRow.count();
  990. if (rowCount === 0) {
  991. console.debug(`未找到人员 ${personIdentifier} 的行`);
  992. // 尝试打印所有行内容用于调试
  993. const allRows = uploadDialog.locator('tbody tr');
  994. const allRowCount = await allRows.count();
  995. console.debug(`资源上传对话框共有 ${allRowCount} 行`);
  996. for (let i = 0; i < Math.min(allRowCount, 3); i++) {
  997. const rowText = await allRows.nth(i).textContent();
  998. console.debug(`行 ${i} 内容:`, rowText);
  999. }
  1000. return;
  1001. }
  1002. console.debug(`找到人员 ${personIdentifier} 的行`);
  1003. // 在该人员行中找到对应文件类型的"上传文件"按钮
  1004. // 文件类型列顺序:税务文件、薪资单、工作成果、合同签署、残疾证明、其他
  1005. const uploadButton = personRow.getByRole('button', { name: '上传文件' });
  1006. const buttonCount = await uploadButton.count();
  1007. if (buttonCount === 0) {
  1008. console.debug(`未找到"上传文件"按钮`);
  1009. return;
  1010. }
  1011. console.debug(`找到 ${buttonCount} 个"上传文件"按钮`);
  1012. // 根据文件类型选择对应的上传按钮
  1013. let buttonIndex = 5; // 默认为"其他"(最后一个)
  1014. switch (fileType) {
  1015. case '税务文件':
  1016. buttonIndex = 0;
  1017. break;
  1018. case '薪资单':
  1019. buttonIndex = 1;
  1020. break;
  1021. case '工作成果':
  1022. buttonIndex = 2;
  1023. break;
  1024. case '合同签署':
  1025. buttonIndex = 3;
  1026. break;
  1027. case '残疾证明':
  1028. buttonIndex = 4;
  1029. break;
  1030. case '其他':
  1031. default:
  1032. buttonIndex = 5;
  1033. break;
  1034. }
  1035. // 点击对应的上传文件按钮,这会打开上传弹窗(第三个对话框)
  1036. const targetButton = uploadButton.nth(buttonIndex);
  1037. // 调试信息:检查按钮是否可见
  1038. const isVisible = await targetButton.isVisible().catch(() => false);
  1039. console.debug(`目标上传文件按钮可见性: ${isVisible}`);
  1040. if (!isVisible) {
  1041. console.debug(`上传文件按钮不可见,尝试滚动到视图`);
  1042. await personRow.scrollIntoViewIfNeeded();
  1043. await this.page.waitForTimeout(TIMEOUTS.SHORT);
  1044. }
  1045. await targetButton.click();
  1046. console.debug(`已点击第 ${buttonIndex} 个上传文件按钮`);
  1047. // 等待上传弹窗打开(第三个对话框)
  1048. await this.page.waitForTimeout(TIMEOUTS.MEDIUM);
  1049. // 在上传弹窗中点击 FileSelector 的触发按钮
  1050. // FileSelector 组件的触发按钮文本是"选择或上传文件"
  1051. const fileSelectorTrigger = this.page.getByRole('button', { name: /选择或上传文件/ }).or(
  1052. this.page.getByText('选择或上传文件')
  1053. );
  1054. const triggerCount = await fileSelectorTrigger.count();
  1055. console.debug(`找到 ${triggerCount} 个 FileSelector 触发按钮`);
  1056. if (triggerCount === 0) {
  1057. console.debug('未找到 FileSelector 触发按钮');
  1058. return;
  1059. }
  1060. // 点击最新的 FileSelector 触发按钮(如果有多于一个的话)
  1061. await fileSelectorTrigger.nth(triggerCount - 1).click();
  1062. console.debug('已点击 FileSelector 触发按钮');
  1063. // FileSelector 对话框的 data-testid 是 "file-selector-dialog"
  1064. const fileSelectorDialog = this.page.getByTestId('file-selector-dialog');
  1065. // 等待 FileSelector 对话框打开(第四个对话框)
  1066. try {
  1067. await fileSelectorDialog.waitFor({ state: 'visible', timeout: TIMEOUTS.DIALOG });
  1068. console.debug('FileSelector 对话框已打开');
  1069. } catch (_error) {
  1070. console.debug('FileSelector 对话框未打开(超时)');
  1071. // 打印调试信息
  1072. const allDialogs = await this.page.locator('[role="dialog"]').count();
  1073. console.debug(`当前页面对话框数量: ${allDialogs}`);
  1074. return;
  1075. }
  1076. // 使用 uploadFileToField 上传文件
  1077. // MinioUploader 使用 data-testid="minio-uploader-input"(因为 testId 未被传递)
  1078. try {
  1079. await uploadFileToField(
  1080. this.page,
  1081. '[data-testid="minio-uploader-input"]',
  1082. fileName,
  1083. {
  1084. fixturesDir: 'tests/fixtures',
  1085. timeout: TIMEOUTS.DIALOG
  1086. }
  1087. );
  1088. console.debug(`文件 ${fileName} 上传操作已完成`);
  1089. } catch (uploadError) {
  1090. console.debug('文件上传失败:', uploadError);
  1091. // 即使上传失败,也尝试关闭对话框
  1092. await fileSelectorDialog.getByRole('button', { name: '取消' }).click().catch(() => {});
  1093. return;
  1094. }
  1095. // 等待上传处理完成,等待文件出现在对话框中
  1096. await this.page.waitForTimeout(TIMEOUTS.LONG);
  1097. // 点击上传后的文件进行选择(查找第一个可点击的文件)
  1098. // 上传成功后,文件会被添加到文件列表中并显示为选中状态(border-primary)
  1099. const uploadedFile = fileSelectorDialog.locator('.border-primary').or(
  1100. fileSelectorDialog.locator('img').first()
  1101. );
  1102. const fileExists = await uploadedFile.count() > 0;
  1103. if (fileExists) {
  1104. await uploadedFile.first().click();
  1105. console.debug('已点击上传后的文件');
  1106. } else {
  1107. // 如果没找到选中的文件,尝试查看对话框内容
  1108. const allImages = fileSelectorDialog.locator('img');
  1109. const imgCount = await allImages.count();
  1110. console.debug(`对话框中图片数量: ${imgCount}`);
  1111. // 尝试点击任何图片
  1112. if (imgCount > 0) {
  1113. await allImages.first().click();
  1114. console.debug('已点击第一张图片');
  1115. }
  1116. }
  1117. await this.page.waitForTimeout(TIMEOUTS.SHORT);
  1118. // 点击"确认选择"按钮
  1119. const confirmButton = fileSelectorDialog.getByRole('button', { name: '确认选择' });
  1120. const confirmButtonCount = await confirmButton.count();
  1121. if (confirmButtonCount > 0) {
  1122. await confirmButton.click();
  1123. console.debug('已点击确认选择按钮');
  1124. } else {
  1125. console.debug('未找到"确认选择"按钮');
  1126. }
  1127. // 等待 FileSelector 对话框关闭(回到上传弹窗)
  1128. await this.page.waitForTimeout(TIMEOUTS.MEDIUM);
  1129. // 在上传弹窗中点击"提交"按钮
  1130. const submitButton = this.page.getByRole('button', { name: /^提交$/ });
  1131. const submitButtonCount = await submitButton.count();
  1132. if (submitButtonCount > 0) {
  1133. await submitButton.click();
  1134. console.debug('已点击提交按钮');
  1135. // 等待提交完成(上传弹窗关闭)
  1136. await this.page.waitForTimeout(TIMEOUTS.LONG);
  1137. } else {
  1138. console.debug('未找到提交按钮');
  1139. }
  1140. console.debug(`附件上传流程完成: ${fileName}`);
  1141. }
  1142. /**
  1143. * 关闭资源上传对话框
  1144. */
  1145. async closeUploadDialog() {
  1146. // 资源上传对话框有"关闭"按钮
  1147. // 需要精确定位到第二个对话框(资源上传对话框)的关闭按钮
  1148. const dialogs = this.page.locator('[role="dialog"]');
  1149. const dialogCount = await dialogs.count();
  1150. if (dialogCount >= 2) {
  1151. // 资源上传对话框通常是第二个对话框
  1152. const uploadDialog = dialogs.nth(1);
  1153. const closeButton = uploadDialog.getByRole('button', { name: '关闭' });
  1154. const buttonCount = await closeButton.count();
  1155. if (buttonCount > 0) {
  1156. await closeButton.first().click();
  1157. console.debug('已关闭资源上传对话框');
  1158. } else {
  1159. console.debug('未找到资源上传对话框的关闭按钮,尝试按 Escape');
  1160. await this.page.keyboard.press('Escape');
  1161. }
  1162. } else {
  1163. // 如果只有一个对话框,尝试点击通用的关闭按钮
  1164. const closeButton = this.page.getByRole('button', { name: '关闭' });
  1165. const buttonCount = await closeButton.count();
  1166. if (buttonCount > 0) {
  1167. await closeButton.first().click();
  1168. console.debug('已关闭对话框(使用通用关闭按钮)');
  1169. }
  1170. }
  1171. await this.page.waitForTimeout(TIMEOUTS.MEDIUM);
  1172. }
  1173. // ===== 高级操作 =====
  1174. /**
  1175. * 创建订单(完整流程)
  1176. * @param data 订单数据
  1177. * @returns 表单提交结果
  1178. */
  1179. async createOrder(data: OrderData): Promise<FormSubmitResult> {
  1180. await this.openCreateDialog();
  1181. await this.fillOrderForm(data);
  1182. const result = await this.submitForm();
  1183. await this.waitForDialogClosed();
  1184. return result;
  1185. }
  1186. /**
  1187. * 编辑订单(完整流程)
  1188. * @param orderName 订单名称
  1189. * @param data 更新的订单数据
  1190. * @returns 表单提交结果
  1191. */
  1192. async editOrder(orderName: string, data: OrderData): Promise<FormSubmitResult> {
  1193. await this.openEditDialog(orderName);
  1194. await this.fillOrderForm(data);
  1195. const result = await this.submitForm();
  1196. await this.waitForDialogClosed();
  1197. return result;
  1198. }
  1199. /**
  1200. * 删除订单(完整流程)
  1201. * @param orderName 订单名称
  1202. * @returns 是否成功删除
  1203. */
  1204. async deleteOrder(orderName: string): Promise<boolean> {
  1205. await this.openDeleteDialog(orderName);
  1206. await this.confirmDelete();
  1207. // 等待并检查 Toast 消息
  1208. await this.page.waitForTimeout(TIMEOUTS.LONG);
  1209. const successToast = this.page.locator('[data-sonner-toast][data-type="success"]');
  1210. const hasSuccess = await successToast.count() > 0;
  1211. return hasSuccess;
  1212. }
  1213. // ===== 订单状态流转操作 =====
  1214. /**
  1215. * 打开激活订单确认对话框
  1216. * @param orderName 订单名称
  1217. */
  1218. async openActivateDialog(orderName: string): Promise<void> {
  1219. // 找到订单行并点击"打开菜单"按钮(与编辑/删除操作相同的模式)
  1220. const orderRow = this.orderTable.locator('tbody tr').filter({ hasText: orderName }).first();
  1221. const menuButton = orderRow.getByRole('button', { name: '打开菜单' });
  1222. await menuButton.click();
  1223. // 等待菜单出现并点击"激活"选项
  1224. const activateOption = this.page.getByRole('menuitem', { name: /激活|激活订单/ });
  1225. await activateOption.waitFor({ state: 'visible', timeout: TIMEOUTS.ELEMENT_VISIBLE_SHORT });
  1226. await activateOption.click();
  1227. // 等待确认对话框出现
  1228. await this.page.waitForSelector('[role="alertdialog"]', { state: 'visible', timeout: TIMEOUTS.DIALOG });
  1229. }
  1230. /**
  1231. * 确认激活订单
  1232. */
  1233. async confirmActivate(): Promise<void> {
  1234. // 尝试多种可能的按钮名称
  1235. const confirmButton = this.page.locator('[role="alertdialog"]').getByRole('button', {
  1236. name: /^(确认激活|激活|确定|确认)$/
  1237. });
  1238. await confirmButton.click();
  1239. // 等待确认对话框关闭和网络请求完成
  1240. await this.page.waitForSelector('[role="alertdialog"]', { state: 'hidden', timeout: TIMEOUTS.DIALOG })
  1241. .catch(() => console.debug('激活确认对话框关闭超时'));
  1242. // networkidle 可能因为持续的网络活动而失败,使用更宽松的超时
  1243. await this.page.waitForLoadState('networkidle', { timeout: TIMEOUTS.TABLE_LOAD })
  1244. .catch(() => console.debug('networkidle 超时,继续执行'));
  1245. await this.page.waitForTimeout(TIMEOUTS.LONG);
  1246. }
  1247. /**
  1248. * 激活订单(完整流程)
  1249. * @param orderName 订单名称
  1250. * @returns 是否成功激活
  1251. */
  1252. async activateOrder(orderName: string): Promise<boolean> {
  1253. await this.openActivateDialog(orderName);
  1254. await this.confirmActivate();
  1255. // 等待并检查 Toast 消息
  1256. await this.page.waitForTimeout(TIMEOUTS.LONG);
  1257. const successToast = this.page.locator('[data-sonner-toast][data-type="success"]');
  1258. const hasSuccess = await successToast.count() > 0;
  1259. return hasSuccess;
  1260. }
  1261. /**
  1262. * 打开关闭订单确认对话框
  1263. * @param orderName 订单名称
  1264. */
  1265. async openCloseDialog(orderName: string): Promise<void> {
  1266. // 找到订单行并点击"打开菜单"按钮
  1267. const orderRow = this.orderTable.locator('tbody tr').filter({ hasText: orderName }).first();
  1268. const menuButton = orderRow.getByRole('button', { name: '打开菜单' });
  1269. await menuButton.click();
  1270. // 等待菜单出现并点击"关闭"选项
  1271. const closeOption = this.page.getByRole('menuitem', { name: /关闭|关闭订单|完成/ });
  1272. await closeOption.waitFor({ state: 'visible', timeout: TIMEOUTS.ELEMENT_VISIBLE_SHORT });
  1273. await closeOption.click();
  1274. // 等待确认对话框出现
  1275. await this.page.waitForSelector('[role="alertdialog"]', { state: 'visible', timeout: TIMEOUTS.DIALOG });
  1276. }
  1277. /**
  1278. * 确认关闭订单
  1279. */
  1280. async confirmClose(): Promise<void> {
  1281. // 尝试多种可能的按钮名称
  1282. const confirmButton = this.page.locator('[role="alertdialog"]').getByRole('button', {
  1283. name: /^(确认关闭|关闭|确定|确认)$/
  1284. });
  1285. await confirmButton.click();
  1286. // 等待确认对话框关闭和网络请求完成
  1287. await this.page.waitForSelector('[role="alertdialog"]', { state: 'hidden', timeout: TIMEOUTS.DIALOG })
  1288. .catch(() => console.debug('关闭确认对话框关闭超时'));
  1289. await this.page.waitForLoadState('networkidle', { timeout: TIMEOUTS.TABLE_LOAD });
  1290. await this.page.waitForTimeout(TIMEOUTS.LONG);
  1291. }
  1292. /**
  1293. * 关闭订单(完整流程)
  1294. * @param orderName 订单名称
  1295. * @returns 是否成功关闭
  1296. */
  1297. async closeOrder(orderName: string): Promise<boolean> {
  1298. await this.openCloseDialog(orderName);
  1299. await this.confirmClose();
  1300. // 等待并检查 Toast 消息
  1301. await this.page.waitForTimeout(TIMEOUTS.LONG);
  1302. const successToast = this.page.locator('[data-sonner-toast][data-type="success"]');
  1303. const hasSuccess = await successToast.count() > 0;
  1304. return hasSuccess;
  1305. }
  1306. /**
  1307. * 获取订单的当前状态(从列表页面)
  1308. * @param orderName 订单名称
  1309. * @returns 订单状态值或 null
  1310. */
  1311. async getOrderStatus(orderName: string): Promise<OrderStatus | null> {
  1312. const orderRow = this.orderTable.locator('tbody tr').filter({ hasText: orderName }).first();
  1313. // 等待行可见
  1314. await orderRow.waitFor({ state: 'visible', timeout: TIMEOUTS.ELEMENT_VISIBLE_SHORT }).catch(() => {
  1315. console.debug(`订单 "${orderName}" 行不可见`);
  1316. });
  1317. const rowCount = await orderRow.count();
  1318. if (rowCount === 0) {
  1319. console.debug(`订单 "${orderName}" 不存在`);
  1320. return null;
  1321. }
  1322. // 尝试多种策略定位状态列
  1323. // 策略1: 查找包含状态文本的单元格(但排除订单名称列)
  1324. const allCells = orderRow.locator('td');
  1325. const cellCount = await allCells.count();
  1326. for (let i = 1; i < cellCount; i++) { // 跳过第一列(通常是订单名称)
  1327. const cell = allCells.nth(i);
  1328. const cellText = await cell.textContent();
  1329. if (cellText) {
  1330. // 检查是否包含完整的状态标签(避免部分匹配)
  1331. for (const [statusValue, statusLabel] of Object.entries(ORDER_STATUS_LABELS)) {
  1332. // 使用更严格的匹配:必须是状态标签本身或包含完整标签
  1333. const trimmedText = cellText.trim();
  1334. if (trimmedText === statusLabel || trimmedText.includes(`${statusLabel}`)) {
  1335. // 验证不是订单名称列(额外检查)
  1336. const firstCellText = await allCells.nth(0).textContent();
  1337. if (firstCellText && !firstCellText.includes(orderName.substring(0, 3))) {
  1338. // 第一列不包含订单名称开头,说明列结构可能不同
  1339. return statusValue as OrderStatus;
  1340. }
  1341. // 跳过第一列后找到的状态标签才返回
  1342. return statusValue as OrderStatus;
  1343. }
  1344. }
  1345. }
  1346. }
  1347. // 策略2: 如果上述方法失败,尝试查找状态徽章/标签元素
  1348. // 查找具有状态样式特征的元素
  1349. const statusBadge = orderRow.locator('[class*="status"], [class*="badge"], span').filter({
  1350. hasText: Object.values(ORDER_STATUS_LABELS)
  1351. });
  1352. if (await statusBadge.count() > 0) {
  1353. const badgeText = await statusBadge.first().textContent();
  1354. if (badgeText) {
  1355. for (const [statusValue, statusLabel] of Object.entries(ORDER_STATUS_LABELS)) {
  1356. if (badgeText.includes(statusLabel)) {
  1357. return statusValue as OrderStatus;
  1358. }
  1359. }
  1360. }
  1361. }
  1362. console.debug(`无法从订单 "${orderName}" 中解析状态`);
  1363. return null;
  1364. }
  1365. /**
  1366. * 验证订单状态
  1367. * @param orderName 订单名称
  1368. * @param expectedStatus 期望的状态
  1369. */
  1370. async expectOrderStatus(orderName: string, expectedStatus: OrderStatus): Promise<void> {
  1371. const actualStatus = await this.getOrderStatus(orderName);
  1372. if (actualStatus === null) {
  1373. throw new Error(`订单 "${orderName}" 未找到或状态列无法识别`);
  1374. }
  1375. if (actualStatus !== expectedStatus) {
  1376. throw new Error(
  1377. `订单 "${orderName}" 状态不匹配: 期望 "${ORDER_STATUS_LABELS[expectedStatus]}", 实际 "${ORDER_STATUS_LABELS[actualStatus]}"`
  1378. );
  1379. }
  1380. }
  1381. /**
  1382. * 检查激活按钮是否可用
  1383. *
  1384. * **注意**: 此方法会打开和关闭菜单,属于有副作用的操作
  1385. *
  1386. * @param orderName 订单名称
  1387. * @returns 按钮是否可用
  1388. */
  1389. async checkActivateButtonEnabled(orderName: string): Promise<boolean> {
  1390. // 找到订单行并打开菜单
  1391. const orderRow = this.orderTable.locator('tbody tr').filter({ hasText: orderName }).first();
  1392. // 检查订单是否存在
  1393. const orderCount = await orderRow.count();
  1394. if (orderCount === 0) {
  1395. console.debug(`订单 "${orderName}" 不存在`);
  1396. return false;
  1397. }
  1398. const menuButton = orderRow.getByRole('button', { name: '打开菜单' });
  1399. try {
  1400. await menuButton.click();
  1401. } catch (error) {
  1402. console.debug(`无法打开订单 "${orderName}" 的菜单:`, error);
  1403. return false;
  1404. }
  1405. // 检查激活菜单项是否可点击
  1406. const activateOption = this.page.getByRole('menuitem', { name: /激活|激活订单/ });
  1407. const isVisible = await activateOption.isVisible().catch(() => false);
  1408. let isEnabled = false;
  1409. if (isVisible) {
  1410. // 检查是否有禁用属性或样式
  1411. const isDisabled = await activateOption.isDisabled().catch(() => false);
  1412. isEnabled = !isDisabled;
  1413. }
  1414. // 关闭菜单以便后续操作
  1415. await this.page.keyboard.press('Escape');
  1416. await this.page.waitForTimeout(TIMEOUTS.SHORT);
  1417. return isEnabled;
  1418. }
  1419. /**
  1420. * 检查关闭按钮是否可用
  1421. *
  1422. * **注意**: 此方法会打开和关闭菜单,属于有副作用的操作
  1423. *
  1424. * @param orderName 订单名称
  1425. * @returns 按钮是否可用
  1426. */
  1427. async checkCloseButtonEnabled(orderName: string): Promise<boolean> {
  1428. // 找到订单行并打开菜单
  1429. const orderRow = this.orderTable.locator('tbody tr').filter({ hasText: orderName }).first();
  1430. // 检查订单是否存在
  1431. const orderCount = await orderRow.count();
  1432. if (orderCount === 0) {
  1433. console.debug(`订单 "${orderName}" 不存在`);
  1434. return false;
  1435. }
  1436. const menuButton = orderRow.getByRole('button', { name: '打开菜单' });
  1437. try {
  1438. await menuButton.click();
  1439. } catch (error) {
  1440. console.debug(`无法打开订单 "${orderName}" 的菜单:`, error);
  1441. return false;
  1442. }
  1443. // 检查关闭菜单项是否可点击
  1444. const closeOption = this.page.getByRole('menuitem', { name: /关闭|关闭订单|完成/ });
  1445. const isVisible = await closeOption.isVisible().catch(() => false);
  1446. let isEnabled = false;
  1447. if (isVisible) {
  1448. // 检查是否有禁用属性或样式
  1449. const isDisabled = await closeOption.isDisabled().catch(() => false);
  1450. isEnabled = !isDisabled;
  1451. }
  1452. // 关闭菜单以便后续操作
  1453. await this.page.keyboard.press('Escape');
  1454. await this.page.waitForTimeout(TIMEOUTS.SHORT);
  1455. return isEnabled;
  1456. }
  1457. }