disability-person.page.ts 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090
  1. import { Page, Locator } from '@playwright/test';
  2. // import { selectRadixOption, selectProvinceCity } from '@d8d/e2e-test-utils';
  3. import { TIMEOUTS } from '../../utils/timeouts';
  4. // 注意:@d8d/e2e-test-utils 包已安装,将在后续 story (2.2, 2.3) 中实际使用
  5. export class DisabilityPersonManagementPage {
  6. readonly page: Page;
  7. readonly pageTitle: Locator;
  8. readonly addPersonButton: Locator;
  9. readonly keywordSearchInput: Locator;
  10. readonly searchButton: Locator;
  11. readonly personTable: Locator;
  12. constructor(page: Page) {
  13. this.page = page;
  14. this.pageTitle = page.getByText('残疾人个人管理');
  15. this.addPersonButton = page.getByRole('button', { name: '新增残疾人' });
  16. this.keywordSearchInput = page.getByPlaceholder('搜索姓名或身份证号');
  17. this.searchButton = page.getByRole('button', { name: '搜索' });
  18. this.personTable = page.locator('table');
  19. }
  20. async goto() {
  21. await this.page.goto('/admin/disabilities');
  22. await this.page.waitForLoadState('domcontentloaded');
  23. // 等待页面标题出现
  24. await this.pageTitle.waitFor({ state: 'visible', timeout: TIMEOUTS.PAGE_LOAD });
  25. // 等待表格数据加载
  26. await this.page.waitForSelector('table tbody tr', { state: 'visible', timeout: TIMEOUTS.PAGE_LOAD_LONG });
  27. await this.expectToBeVisible();
  28. }
  29. async expectToBeVisible() {
  30. await this.pageTitle.waitFor({ state: 'visible', timeout: TIMEOUTS.PAGE_LOAD });
  31. await this.addPersonButton.waitFor({ state: 'visible', timeout: TIMEOUTS.TABLE_LOAD });
  32. }
  33. async openCreateDialog() {
  34. // 监听网络请求
  35. const responses: any[] = [];
  36. this.page.on('response', async (response) => {
  37. if (response.url().includes('disabled-person') || response.url().includes('aggregated')) {
  38. try {
  39. const responseData = await response.json().catch(() => ({ status: response.status() }));
  40. responses.push({
  41. url: response.url(),
  42. status: response.status(),
  43. data: responseData
  44. });
  45. } catch (e) {
  46. responses.push({
  47. url: response.url(),
  48. status: response.status(),
  49. error: e
  50. });
  51. }
  52. }
  53. });
  54. await this.addPersonButton.click();
  55. await this.page.waitForSelector('[data-testid="create-disabled-person-dialog-title"]', { state: 'visible', timeout: TIMEOUTS.DIALOG });
  56. return responses;
  57. }
  58. async fillBasicForm(data: {
  59. name: string;
  60. gender: string;
  61. idCard: string;
  62. disabilityId: string;
  63. disabilityType: string;
  64. disabilityLevel: string;
  65. phone: string;
  66. idAddress: string;
  67. province: string;
  68. city: string;
  69. }) {
  70. // 等待表单出现
  71. const form = this.page.locator('form#create-form');
  72. await form.waitFor({ state: 'visible', timeout: TIMEOUTS.DIALOG });
  73. console.debug('开始填写表单...');
  74. // 填写基本信息 - 使用 form locator 确保只在对话框内查找
  75. await form.getByLabel('姓名 *').fill(data.name);
  76. console.debug('✓ 姓名已填写:', data.name);
  77. // 性别 - 使用 data-testid
  78. const genderTrigger = this.page.locator('[data-testid="gender-select"]');
  79. await genderTrigger.click();
  80. await this.page.getByRole('option', { name: data.gender }).click();
  81. console.debug('✓ 性别已选择:', data.gender);
  82. await form.getByLabel('身份证号 *').fill(data.idCard);
  83. console.debug('✓ 身份证号已填写');
  84. await form.getByLabel('残疾证号 *').fill(data.disabilityId);
  85. console.debug('✓ 残疾证号已填写');
  86. // 残疾类型 - 使用 data-testid
  87. const disabilityTypeTrigger = this.page.locator('[data-testid="disability-type-select"]');
  88. await disabilityTypeTrigger.scrollIntoViewIfNeeded();
  89. await this.page.waitForTimeout(TIMEOUTS.VERY_SHORT);
  90. await disabilityTypeTrigger.click();
  91. await this.page.getByRole('option', { name: data.disabilityType }).click();
  92. console.debug('✓ 残疾类型已选择:', data.disabilityType);
  93. // 残疾等级 - 使用 data-testid
  94. const disabilityLevelTrigger = this.page.locator('[data-testid="disability-level-select"]');
  95. await disabilityLevelTrigger.scrollIntoViewIfNeeded();
  96. await this.page.waitForTimeout(TIMEOUTS.VERY_SHORT);
  97. await disabilityLevelTrigger.click();
  98. await this.page.getByRole('option', { name: data.disabilityLevel }).click();
  99. console.debug('✓ 残疾等级已选择:', data.disabilityLevel);
  100. await form.getByLabel('联系电话 *').fill(data.phone);
  101. console.debug('✓ 联系电话已填写');
  102. await form.getByLabel('身份证地址 *').fill(data.idAddress);
  103. console.debug('✓ 身份证地址已填写');
  104. // 居住地址 - 省市区级联选择
  105. // AreaSelectForm 使用 data-testid="area-select-province" 等属性
  106. const provinceTrigger = this.page.locator('[data-testid="area-select-province"]');
  107. await provinceTrigger.scrollIntoViewIfNeeded();
  108. await provinceTrigger.click();
  109. await this.page.getByRole('option', { name: data.province }).click();
  110. console.debug('✓ 省份已选择:', data.province);
  111. const cityTrigger = this.page.locator('[data-testid="area-select-city"]');
  112. await cityTrigger.click();
  113. await this.page.getByRole('option', { name: data.city }).click();
  114. console.debug('✓ 城市已选择:', data.city);
  115. console.debug('表单填写完成');
  116. }
  117. async submitForm() {
  118. // 收集网络响应
  119. const responses: any[] = [];
  120. // 监听所有网络请求
  121. this.page.on('response', async (response) => {
  122. const url = response.url();
  123. if (url.includes('disabled-person') || url.includes('aggregated')) {
  124. const requestBody = response.request()?.postData();
  125. const responseBody = await response.text().catch(() => '');
  126. let jsonBody = null;
  127. try {
  128. jsonBody = JSON.parse(responseBody);
  129. } catch {
  130. // 不是 JSON
  131. }
  132. responses.push({
  133. url,
  134. method: response.request()?.method(),
  135. status: response.status(),
  136. ok: response.ok(),
  137. requestHeaders: await response.allHeaders().catch(() => ({})),
  138. responseHeaders: await response.allHeaders().catch(() => ({})),
  139. requestBody: requestBody ? JSON.parse(requestBody) : null,
  140. responseBody: jsonBody || responseBody,
  141. statusText: response.statusText()
  142. });
  143. }
  144. });
  145. // 点击创建按钮
  146. const submitButton = this.page.getByRole('button', { name: '创建' });
  147. await submitButton.click();
  148. // 等待网络请求完成(增加超时并添加容错处理)
  149. try {
  150. await this.page.waitForLoadState('networkidle', { timeout: TIMEOUTS.UPLOAD_LONG });
  151. } catch {
  152. // networkidle 可能因为长轮询或后台请求而失败,使用 domcontentloaded 作为降级方案
  153. console.debug(' ⚠ networkidle 超时,使用 domcontentloaded 作为降级方案');
  154. await this.page.waitForLoadState('domcontentloaded', { timeout: TIMEOUTS.TABLE_LOAD });
  155. }
  156. // 等待一段时间让 Toast 消息显示
  157. await this.page.waitForTimeout(TIMEOUTS.VERY_LONG);
  158. // 检查是否有错误提示
  159. const errorToast = this.page.locator('[data-sonner-toast][data-type="error"]');
  160. const successToast = this.page.locator('[data-sonner-toast][data-type="success"]');
  161. const hasError = await errorToast.count() > 0;
  162. const hasSuccess = await successToast.count() > 0;
  163. let errorMessage = null;
  164. let successMessage = null;
  165. if (hasError) {
  166. errorMessage = await errorToast.first().textContent();
  167. }
  168. if (hasSuccess) {
  169. successMessage = await successToast.first().textContent();
  170. }
  171. return {
  172. responses,
  173. hasError,
  174. hasSuccess,
  175. errorMessage,
  176. successMessage
  177. };
  178. }
  179. async searchByName(name: string) {
  180. await this.keywordSearchInput.fill(name);
  181. await this.searchButton.click();
  182. await this.page.waitForLoadState('networkidle');
  183. await this.page.waitForTimeout(TIMEOUTS.LONG);
  184. }
  185. async personExists(name: string): Promise<boolean> {
  186. const personRow = this.personTable.locator('tbody tr').filter({ hasText: name }).first();
  187. return (await personRow.count()) > 0;
  188. }
  189. /**
  190. * 等待人员记录出现(带重试机制,用于修复数据持久化稳定性问题)
  191. * @param name 残疾人姓名
  192. * @param options 选项
  193. * @returns 是否找到记录
  194. */
  195. async waitForPersonExists(name: string, options?: { timeout?: number; retries?: number }): Promise<boolean> {
  196. const timeout = options?.timeout ?? TIMEOUTS.TABLE_LOAD; // 默认 10 秒
  197. const startTime = Date.now();
  198. while (Date.now() - startTime < timeout) {
  199. // 重新搜索
  200. await this.searchByName(name);
  201. await this.page.waitForTimeout(TIMEOUTS.LONG); // 等待后检查
  202. const exists = await this.personExists(name);
  203. if (exists) {
  204. console.debug(` ✓ 记录已出现: ${name}`);
  205. return true;
  206. }
  207. console.debug(` ⏳ 等待记录出现: ${name} (${Math.floor((Date.now() - startTime) / 1000)}s)`);
  208. }
  209. console.debug(` ✗ 记录未出现: ${name} (超时 ${timeout}ms)`);
  210. return false;
  211. }
  212. /**
  213. * 等待人员记录消失(带重试机制)
  214. * @param name 残疾人姓名
  215. * @param options 选项
  216. * @returns 记录是否已消失
  217. */
  218. async waitForPersonNotExists(name: string, options?: { timeout?: number }): Promise<boolean> {
  219. const timeout = options?.timeout ?? TIMEOUTS.TABLE_LOAD; // 默认 10 秒
  220. const startTime = Date.now();
  221. while (Date.now() - startTime < timeout) {
  222. await this.searchByName(name);
  223. await this.page.waitForTimeout(TIMEOUTS.LONG);
  224. const exists = await this.personExists(name);
  225. if (!exists) {
  226. console.debug(` ✓ 记录已消失: ${name}`);
  227. return true;
  228. }
  229. console.debug(` ⏳ 等待记录消失: ${name} (${Math.floor((Date.now() - startTime) / 1000)}s)`);
  230. }
  231. console.debug(` ✗ 记录仍存在: ${name} (超时 ${timeout}ms)`);
  232. return false;
  233. }
  234. /**
  235. * 上传照片
  236. * @param photoType 照片类型(身份证照片、残疾证照片、个人照片、其他照片)
  237. * @param fileName 文件名
  238. */
  239. async uploadPhoto(photoType: string, fileName: string) {
  240. // 找到对应照片类型的上传按钮区域
  241. const photoSection = this.page.locator('text=' + photoType).first();
  242. await photoSection.scrollIntoViewIfNeeded();
  243. // 查找该类型照片区域的"上传"按钮
  244. const uploadButton = photoSection.locator('xpath=ancestor::div[contains(@class, "space-y-")]').first()
  245. .getByRole('button', { name: /上传/ }).first();
  246. // 创建测试文件
  247. const fileInput = await uploadButton.evaluateHandle((el: any) => {
  248. const input = el.querySelector('input[type="file"]');
  249. return input;
  250. });
  251. // 使用临时文件上传(类型转换以修复 TypeScript 错误)
  252. const file = {
  253. name: fileName,
  254. mimeType: 'image/jpeg',
  255. buffer: Buffer.from('fake image content')
  256. };
  257. // ElementHandle.uploadFile 在 Playwright 中可用,需要类型断言
  258. await (fileInput as any).uploadFile(file as any);
  259. await this.page.waitForTimeout(TIMEOUTS.MEDIUM); // 等待上传处理
  260. console.debug(` ✓ 上传照片: ${photoType} - ${fileName}`);
  261. }
  262. /**
  263. * 添加银行卡(内联表单模式)
  264. * @param bankCard 银行卡信息
  265. */
  266. async addBankCard(bankCard: {
  267. bankName: string;
  268. subBankName: string;
  269. cardNumber: string;
  270. cardholderName: string;
  271. cardType?: string;
  272. isDefault?: boolean;
  273. }) {
  274. // 滚动到银行卡管理区域
  275. const bankCardLabel = this.page.getByText('银行卡管理');
  276. await bankCardLabel.scrollIntoViewIfNeeded();
  277. await this.page.waitForTimeout(TIMEOUTS.SHORT);
  278. // 获取当前银行卡数量
  279. const currentCardCount = await this.page.locator('[data-testid^="remove-bank-card-"]').count();
  280. // 点击"添加银行卡"按钮
  281. const addButton = this.page.locator('[data-testid="add-bank-card-button"]');
  282. await addButton.click();
  283. await this.page.waitForTimeout(TIMEOUTS.MEDIUM);
  284. // 等待新的银行卡卡片出现
  285. const newCardCount = await this.page.locator('[data-testid^="remove-bank-card-"]').count();
  286. if (newCardCount !== currentCardCount + 1) {
  287. throw new Error(`添加银行卡失败:预期 ${currentCardCount + 1} 张,实际 ${newCardCount} 张`);
  288. }
  289. // 新添加的银行卡索引
  290. const cardIndex = currentCardCount;
  291. // 1. 选择银行名称
  292. const bankSelectTrigger = this.page.locator(`[data-testid="bank-select-${cardIndex}"]`);
  293. await bankSelectTrigger.click();
  294. await this.page.waitForTimeout(TIMEOUTS.SHORT);
  295. await this.page.getByRole('option', { name: bankCard.bankName }).click();
  296. // 2. 填写发卡支行
  297. const subBankInput = this.page.locator(`[data-testid="sub-bank-name-input-${cardIndex}"]`);
  298. await subBankInput.fill(bankCard.subBankName);
  299. // 3. 填写银行卡号
  300. const cardNumberInput = this.page.locator(`[data-testid="card-number-input-${cardIndex}"]`);
  301. await cardNumberInput.fill(bankCard.cardNumber);
  302. // 4. 填写持卡人姓名
  303. const cardholderInput = this.page.locator(`[data-testid="cardholder-name-input-${cardIndex}"]`);
  304. await cardholderInput.fill(bankCard.cardholderName);
  305. // 5. 选择银行卡类型(可选)
  306. if (bankCard.cardType) {
  307. const cardTypeTrigger = this.page.locator(`[data-testid="card-type-select-${cardIndex}"]`);
  308. await cardTypeTrigger.click();
  309. await this.page.waitForTimeout(TIMEOUTS.SHORT);
  310. // 修复稳定性问题:等待选项出现后再点击(异步加载场景)
  311. await this.page.getByRole('option', { name: bankCard.cardType }).waitFor({ state: 'visible', timeout: TIMEOUTS.DIALOG });
  312. await this.page.getByRole('option', { name: bankCard.cardType }).click();
  313. }
  314. // 6. 设置默认银行卡(可选)
  315. if (bankCard.isDefault) {
  316. const defaultSwitch = this.page.locator(`[data-testid="default-card-switch-${cardIndex}"]`);
  317. const isChecked = await defaultSwitch.isChecked();
  318. if (!isChecked) {
  319. await defaultSwitch.click();
  320. }
  321. }
  322. console.debug(` ✓ 添加银行卡: ${bankCard.bankName} - ${bankCard.cardNumber}`);
  323. return cardIndex;
  324. }
  325. /**
  326. * 编辑指定索引的银行卡
  327. * @param cardIndex 银行卡索引(从0开始)
  328. * @param updatedData 更新的银行卡数据
  329. */
  330. async editBankCard(cardIndex: number, updatedData: {
  331. bankName?: string;
  332. subBankName?: string;
  333. cardNumber?: string;
  334. cardholderName?: string;
  335. cardType?: string;
  336. isDefault?: boolean;
  337. }) {
  338. console.debug(` 编辑银行卡 ${cardIndex}`);
  339. // 编辑银行名称
  340. if (updatedData.bankName !== undefined) {
  341. const bankSelectTrigger = this.page.locator(`[data-testid="bank-select-${cardIndex}"]`);
  342. await bankSelectTrigger.click();
  343. await this.page.waitForTimeout(TIMEOUTS.SHORT);
  344. await this.page.getByRole('option', { name: updatedData.bankName }).click();
  345. console.debug(` ✓ 更新银行名称: ${updatedData.bankName}`);
  346. }
  347. // 编辑发卡支行
  348. if (updatedData.subBankName !== undefined) {
  349. const subBankInput = this.page.locator(`[data-testid="sub-bank-name-input-${cardIndex}"]`);
  350. await subBankInput.clear();
  351. await subBankInput.fill(updatedData.subBankName);
  352. console.debug(` ✓ 更新发卡支行: ${updatedData.subBankName}`);
  353. }
  354. // 编辑银行卡号
  355. if (updatedData.cardNumber !== undefined) {
  356. const cardNumberInput = this.page.locator(`[data-testid="card-number-input-${cardIndex}"]`);
  357. await cardNumberInput.clear();
  358. await cardNumberInput.fill(updatedData.cardNumber);
  359. console.debug(` ✓ 更新银行卡号: ${updatedData.cardNumber}`);
  360. }
  361. // 编辑持卡人姓名
  362. if (updatedData.cardholderName !== undefined) {
  363. const cardholderInput = this.page.locator(`[data-testid="cardholder-name-input-${cardIndex}"]`);
  364. await cardholderInput.clear();
  365. await cardholderInput.fill(updatedData.cardholderName);
  366. console.debug(` ✓ 更新持卡人姓名: ${updatedData.cardholderName}`);
  367. }
  368. // 编辑银行卡类型
  369. if (updatedData.cardType !== undefined) {
  370. const cardTypeTrigger = this.page.locator(`[data-testid="card-type-select-${cardIndex}"]`);
  371. await cardTypeTrigger.click();
  372. await this.page.waitForTimeout(TIMEOUTS.SHORT);
  373. // 修复稳定性问题:等待选项出现后再点击(异步加载场景)
  374. await this.page.getByRole('option', { name: updatedData.cardType }).waitFor({ state: 'visible', timeout: TIMEOUTS.DIALOG });
  375. await this.page.getByRole('option', { name: updatedData.cardType }).click();
  376. console.debug(` ✓ 更新银行卡类型: ${updatedData.cardType}`);
  377. }
  378. // 设置默认银行卡
  379. if (updatedData.isDefault !== undefined) {
  380. const defaultSwitch = this.page.locator(`[data-testid="default-card-switch-${cardIndex}"]`);
  381. const isChecked = await defaultSwitch.isChecked();
  382. if (isChecked !== updatedData.isDefault) {
  383. await defaultSwitch.click();
  384. console.debug(` ✓ 设置默认银行卡: ${updatedData.isDefault}`);
  385. }
  386. }
  387. console.debug(` ✓ 银行卡 ${cardIndex} 编辑完成`);
  388. }
  389. /**
  390. * 删除指定索引的银行卡
  391. * @param cardIndex 银行卡索引(从0开始)
  392. */
  393. async deleteBankCard(cardIndex: number) {
  394. console.debug(` 删除银行卡 ${cardIndex}`);
  395. const removeButton = this.page.locator(`[data-testid="remove-bank-card-${cardIndex}"]`);
  396. await removeButton.click();
  397. await this.page.waitForTimeout(TIMEOUTS.MEDIUM);
  398. console.debug(` ✓ 银行卡 ${cardIndex} 已删除`);
  399. }
  400. /**
  401. * 获取银行卡列表
  402. * @returns 银行卡号数组
  403. */
  404. async getBankCardList(): Promise<string[]> {
  405. const cards: string[] = [];
  406. const cardCount = await this.page.locator('[data-testid^="remove-bank-card-"]').count();
  407. for (let i = 0; i < cardCount; i++) {
  408. const cardNumberInput = this.page.locator(`[data-testid="card-number-input-${i}"]`);
  409. const cardNumber = await cardNumberInput.inputValue();
  410. cards.push(cardNumber);
  411. }
  412. return cards;
  413. }
  414. /**
  415. * 获取默认银行卡的索引
  416. * @returns 默认银行卡的索引,如果没有则返回 null
  417. */
  418. async getDefaultBankCardIndex(): Promise<number | null> {
  419. const cardCount = await this.page.locator('[data-testid^="remove-bank-card-"]').count();
  420. for (let i = 0; i < cardCount; i++) {
  421. const defaultSwitch = this.page.locator(`[data-testid="default-card-switch-${i}"]`);
  422. const isChecked = await defaultSwitch.isChecked();
  423. if (isChecked) {
  424. return i;
  425. }
  426. }
  427. return null;
  428. }
  429. /**
  430. * 获取当前银行卡数量
  431. * @returns 银行卡数量
  432. */
  433. async getBankCardCount(): Promise<number> {
  434. return await this.page.locator('[data-testid^="remove-bank-card-"]').count();
  435. }
  436. /**
  437. * 检查添加银行卡按钮是否被禁用
  438. * @returns 是否禁用
  439. */
  440. async isAddBankCardButtonDisabled(): Promise<boolean> {
  441. const addButton = this.page.locator('[data-testid="add-bank-card-button"]');
  442. return await addButton.isDisabled();
  443. }
  444. /**
  445. * 添加回访记录(内联表单模式)
  446. * @param visit 回访信息
  447. * @returns 添加的回访记录索引
  448. */
  449. async addVisit(visit: {
  450. visitDate: string;
  451. visitType: string;
  452. visitContent: string;
  453. visitResult?: string;
  454. nextVisitDate?: string;
  455. }): Promise<number> {
  456. // 获取当前回访数量
  457. const currentVisitCount = await this.getVisitCount();
  458. // 点击"添加回访"按钮
  459. const addButton = this.page.locator('[data-testid="add-visit-button"]');
  460. await addButton.click();
  461. await this.page.waitForTimeout(TIMEOUTS.SHORT);
  462. // 等待新的回访卡片出现
  463. const newVisitCount = await this.getVisitCount();
  464. if (newVisitCount !== currentVisitCount + 1) {
  465. throw new Error(`添加回访失败:预期 ${currentVisitCount + 1} 条,实际 ${newVisitCount} 条`);
  466. }
  467. // 新添加的回访索引
  468. const visitIndex = currentVisitCount;
  469. // 1. 填写回访日期
  470. const dateInput = this.page.locator(`[data-testid="visit-date-input-${visitIndex}"]`);
  471. await dateInput.fill(visit.visitDate);
  472. // 2. 选择回访类型
  473. const typeSelectTrigger = this.page.locator(`[data-testid="visit-type-select-${visitIndex}"]`);
  474. await typeSelectTrigger.click();
  475. await this.page.waitForTimeout(TIMEOUTS.VERY_SHORT);
  476. await this.page.getByRole('option', { name: visit.visitType }).click();
  477. // 3. 填写回访内容
  478. const contentTextarea = this.page.locator(`[data-testid="visit-content-textarea-${visitIndex}"]`);
  479. await contentTextarea.fill(visit.visitContent);
  480. // 4. 填写回访结果(可选)
  481. if (visit.visitResult !== undefined) {
  482. const resultInput = this.page.locator(`[data-testid="visit-result-input-${visitIndex}"]`);
  483. await resultInput.fill(visit.visitResult);
  484. }
  485. // 5. 填写下一次回访日期(可选)
  486. if (visit.nextVisitDate !== undefined) {
  487. const nextDateInput = this.page.locator(`[data-testid="next-visit-date-input-${visitIndex}"]`);
  488. await nextDateInput.fill(visit.nextVisitDate);
  489. }
  490. console.debug(` ✓ 添加回访: ${visit.visitType} - ${visit.visitDate}`);
  491. return visitIndex;
  492. }
  493. /**
  494. * 编辑指定索引的回访记录
  495. * @param index 回访索引(从0开始)
  496. * @param updatedData 更新的回访数据
  497. */
  498. async editVisit(index: number, updatedData: {
  499. visitDate?: string;
  500. visitType?: string;
  501. visitContent?: string;
  502. visitResult?: string;
  503. nextVisitDate?: string;
  504. }): Promise<void> {
  505. console.debug(` 编辑回访 ${index}`);
  506. // 编辑回访日期
  507. if (updatedData.visitDate !== undefined) {
  508. const dateInput = this.page.locator(`[data-testid="visit-date-input-${index}"]`);
  509. await dateInput.clear();
  510. await dateInput.fill(updatedData.visitDate);
  511. console.debug(` ✓ 更新回访日期: ${updatedData.visitDate}`);
  512. }
  513. // 编辑回访类型
  514. if (updatedData.visitType !== undefined) {
  515. const typeSelectTrigger = this.page.locator(`[data-testid="visit-type-select-${index}"]`);
  516. await typeSelectTrigger.click();
  517. await this.page.waitForTimeout(TIMEOUTS.VERY_SHORT);
  518. await this.page.getByRole('option', { name: updatedData.visitType }).click();
  519. console.debug(` ✓ 更新回访类型: ${updatedData.visitType}`);
  520. }
  521. // 编辑回访内容
  522. if (updatedData.visitContent !== undefined) {
  523. const contentTextarea = this.page.locator(`[data-testid="visit-content-textarea-${index}"]`);
  524. await contentTextarea.clear();
  525. await contentTextarea.fill(updatedData.visitContent);
  526. console.debug(` ✓ 更新回访内容`);
  527. }
  528. // 编辑回访结果
  529. if (updatedData.visitResult !== undefined) {
  530. const resultInput = this.page.locator(`[data-testid="visit-result-input-${index}"]`);
  531. await resultInput.clear();
  532. await resultInput.fill(updatedData.visitResult);
  533. console.debug(` ✓ 更新回访结果`);
  534. }
  535. // 编辑下次回访日期
  536. if (updatedData.nextVisitDate !== undefined) {
  537. const nextDateInput = this.page.locator(`[data-testid="next-visit-date-input-${index}"]`);
  538. await nextDateInput.clear();
  539. await nextDateInput.fill(updatedData.nextVisitDate);
  540. console.debug(` ✓ 更新下次回访日期`);
  541. }
  542. console.debug(` ✓ 回访 ${index} 编辑完成`);
  543. }
  544. /**
  545. * 删除指定索引的回访记录
  546. * @param index 回访索引(从0开始)
  547. */
  548. async deleteVisit(index: number): Promise<void> {
  549. console.debug(` 删除回访 ${index}`);
  550. const removeButton = this.page.locator(`[data-testid="remove-visit-${index}"]`);
  551. await removeButton.click();
  552. await this.page.waitForTimeout(TIMEOUTS.SHORT);
  553. console.debug(` ✓ 回访 ${index} 已删除`);
  554. }
  555. /**
  556. * 获取回访记录列表
  557. * @returns 回访信息数组
  558. */
  559. async getVisitList(): Promise<Array<{
  560. visitDate: string;
  561. visitType: string;
  562. visitContent: string;
  563. visitResult?: string;
  564. nextVisitDate?: string;
  565. }>> {
  566. const visits: Array<{
  567. visitDate: string;
  568. visitType: string;
  569. visitContent: string;
  570. visitResult?: string;
  571. nextVisitDate?: string;
  572. }> = [];
  573. const visitCount = await this.getVisitCount();
  574. for (let i = 0; i < visitCount; i++) {
  575. // 获取回访日期
  576. const dateInput = this.page.locator(`[data-testid="visit-date-input-${i}"]`);
  577. const visitDate = await dateInput.inputValue();
  578. // 获取回访类型
  579. const typeSelectTrigger = this.page.locator(`[data-testid="visit-type-select-${i}"]`);
  580. const visitType = await typeSelectTrigger.textContent() || '';
  581. // 获取回访内容
  582. const contentTextarea = this.page.locator(`[data-testid="visit-content-textarea-${i}"]`);
  583. const visitContent = await contentTextarea.inputValue();
  584. // 获取回访结果
  585. const resultInput = this.page.locator(`[data-testid="visit-result-input-${i}"]`);
  586. const visitResult = await resultInput.inputValue().catch(() => '');
  587. // 获取下次回访日期
  588. const nextDateInput = this.page.locator(`[data-testid="next-visit-date-input-${i}"]`);
  589. const nextVisitDate = await nextDateInput.inputValue().catch(() => '');
  590. visits.push({
  591. visitDate,
  592. visitType: visitType.trim(),
  593. visitContent,
  594. visitResult: visitResult || undefined,
  595. nextVisitDate: nextVisitDate || undefined,
  596. });
  597. }
  598. return visits;
  599. }
  600. /**
  601. * 获取当前回访记录数量
  602. * @returns 回访数量
  603. */
  604. async getVisitCount(): Promise<number> {
  605. return await this.page.locator('[data-testid^="remove-visit-"]').count();
  606. }
  607. /**
  608. * 检查添加回访按钮是否被禁用
  609. * @returns 是否禁用
  610. */
  611. async isAddVisitButtonDisabled(): Promise<boolean> {
  612. const addButton = this.page.locator('[data-testid="add-visit-button"]');
  613. return await addButton.isDisabled();
  614. }
  615. /**
  616. * 滚动表单到指定区域
  617. * @param sectionName 区域名称
  618. */
  619. async scrollToSection(sectionName: string) {
  620. const section = this.page.locator(`text=${sectionName}`).first();
  621. await section.scrollIntoViewIfNeeded();
  622. await this.page.waitForTimeout(TIMEOUTS.SHORT);
  623. }
  624. /**
  625. * 等待对话框关闭
  626. */
  627. async waitForDialogClosed() {
  628. const dialog = this.page.locator('[role="dialog"]');
  629. await dialog.waitFor({ state: 'hidden', timeout: TIMEOUTS.DIALOG }).catch(() => {});
  630. await this.page.waitForTimeout(TIMEOUTS.MEDIUM);
  631. }
  632. /**
  633. * 取消对话框
  634. */
  635. async cancelDialog() {
  636. const cancelButton = this.page.getByRole('button', { name: '取消' });
  637. await cancelButton.click();
  638. await this.waitForDialogClosed();
  639. }
  640. /**
  641. * 添加备注(内联表单模式)
  642. * @param content 备注内容
  643. * @param options 选项
  644. */
  645. async addNote(content: string, options?: { isSpecialNeeds?: boolean }): Promise<number> {
  646. // 点击"添加备注"按钮
  647. const addButton = this.page.locator('[data-testid="add-remark-button"]');
  648. await addButton.click();
  649. await this.page.waitForTimeout(TIMEOUTS.SHORT);
  650. // 获取当前备注数量
  651. const noteCount = await this.getNoteCount();
  652. const noteIndex = noteCount > 0 ? noteCount - 1 : 0;
  653. // 填写备注内容
  654. const textarea = this.page.locator(`[data-testid="remark-content-textarea-${noteIndex}"]`);
  655. await textarea.fill(content);
  656. // 标记特殊需求(如果需要)
  657. if (options?.isSpecialNeeds) {
  658. const switchControl = this.page.locator(`[data-testid="special-needs-switch-${noteIndex}"]`);
  659. const isChecked = await switchControl.isChecked();
  660. if (!isChecked) {
  661. await switchControl.click();
  662. }
  663. }
  664. console.debug(` ✓ 添加备注: ${content.substring(0, 30)}...`);
  665. return noteIndex;
  666. }
  667. /**
  668. * 编辑指定索引的备注
  669. * @param index 备注索引(从0开始)
  670. * @param content 更新的备注内容
  671. */
  672. async editNote(index: number, content: string): Promise<void> {
  673. console.debug(` 编辑备注 ${index}`);
  674. const textarea = this.page.locator(`[data-testid="remark-content-textarea-${index}"]`);
  675. await textarea.clear();
  676. await textarea.fill(content);
  677. console.debug(` ✓ 备注 ${index} 编辑完成`);
  678. }
  679. /**
  680. * 删除指定索引的备注
  681. * @param index 备注索引(从0开始)
  682. */
  683. async deleteNote(index: number): Promise<void> {
  684. console.debug(` 删除备注 ${index}`);
  685. const removeButton = this.page.locator(`[data-testid="remove-remark-${index}"]`);
  686. await removeButton.click();
  687. await this.page.waitForTimeout(TIMEOUTS.SHORT);
  688. console.debug(` ✓ 备注 ${index} 已删除`);
  689. }
  690. /**
  691. * 获取备注列表
  692. * @returns 备注内容数组
  693. */
  694. async getNoteList(): Promise<string[]> {
  695. const notes: string[] = [];
  696. const noteCount = await this.page.locator('[data-testid^="remark-content-textarea-"]').count();
  697. for (let i = 0; i < noteCount; i++) {
  698. const textarea = this.page.locator(`[data-testid="remark-content-textarea-${i}"]`);
  699. const content = await textarea.inputValue();
  700. notes.push(content);
  701. }
  702. return notes;
  703. }
  704. /**
  705. * 获取备注数量
  706. * @returns 备注数量
  707. */
  708. async getNoteCount(): Promise<number> {
  709. return await this.page.locator('[data-testid^="remark-content-textarea-"]').count();
  710. }
  711. /**
  712. * 获取指定备注的特殊需求状态
  713. * @param index 备注索引(从0开始)
  714. * @returns 是否标记为特殊需求
  715. */
  716. async getNoteSpecialNeedsStatus(index: number): Promise<boolean> {
  717. const switchControl = this.page.locator(`[data-testid="special-needs-switch-${index}"]`);
  718. return await switchControl.isChecked();
  719. }
  720. /**
  721. * 检查添加备注按钮是否被禁用
  722. * @returns 是否禁用
  723. */
  724. async isAddNoteButtonDisabled(): Promise<boolean> {
  725. const addButton = this.page.locator('[data-testid="add-remark-button"]');
  726. return await addButton.isDisabled();
  727. }
  728. /**
  729. * 打开编辑对话框(通过姓名查找残疾人记录并点击编辑按钮)
  730. * @param name 残疾人姓名
  731. */
  732. async openEditDialog(name: string): Promise<void> {
  733. // 在列表中找到包含该姓名的行
  734. const row = this.personTable.locator('tbody tr').filter({ hasText: name }).first();
  735. // 等待行可见
  736. await row.waitFor({ state: 'visible', timeout: TIMEOUTS.DIALOG });
  737. // 点击该行的编辑按钮(使用 data-testid)
  738. // 需要先获取该行的 ID,因为 edit-person-{id} 按钮使用 ID
  739. const editButton = row.locator('[data-testid^="edit-person-"]').first();
  740. await editButton.click();
  741. // 等待编辑对话框出现
  742. await this.page.waitForSelector('[data-testid="edit-disabled-person-dialog-title"]', { state: 'visible', timeout: TIMEOUTS.DIALOG });
  743. console.debug(`✓ 打开编辑对话框: ${name}`);
  744. }
  745. /**
  746. * 打开详情对话框(通过姓名查找残疾人记录并点击查看按钮)
  747. * @param name 残疾人姓名
  748. */
  749. async openDetailDialog(name: string): Promise<void> {
  750. // 在列表中找到包含该姓名的行
  751. const row = this.personTable.locator('tbody tr').filter({ hasText: name }).first();
  752. // 等待行可见
  753. await row.waitFor({ state: 'visible', timeout: TIMEOUTS.DIALOG });
  754. // 点击该行的查看按钮(使用 data-testid)
  755. const viewButton = row.locator('[data-testid^="view-person-"]').first();
  756. await viewButton.click();
  757. // 等待详情对话框出现
  758. await this.page.waitForSelector('text=残疾人详情', { state: 'visible', timeout: TIMEOUTS.DIALOG });
  759. console.debug(`✓ 打开详情对话框: ${name}`);
  760. }
  761. /**
  762. * 删除残疾人记录(通过姓名查找并删除)
  763. * @param name 残疾人姓名
  764. */
  765. async deleteDisabilityPerson(name: string): Promise<void> {
  766. // 在列表中找到包含该姓名的行
  767. const row = this.personTable.locator('tbody tr').filter({ hasText: name }).first();
  768. // 等待行可见
  769. await row.waitFor({ state: 'visible', timeout: TIMEOUTS.DIALOG });
  770. // 点击该行的删除按钮
  771. const deleteButton = row.locator('[data-testid^="delete-person-"]').first();
  772. await deleteButton.click();
  773. // 等待删除确认对话框出现
  774. await this.page.waitForSelector('[data-testid="delete-confirmation-dialog-title"]', { state: 'visible', timeout: TIMEOUTS.ELEMENT_VISIBLE_SHORT });
  775. // 点击确认删除按钮
  776. const confirmButton = this.page.getByRole('button', { name: '确认删除' });
  777. await confirmButton.click();
  778. // 等待网络请求完成
  779. await this.page.waitForLoadState('networkidle', { timeout: TIMEOUTS.TABLE_LOAD });
  780. // 等待 Toast 提示
  781. await this.page.waitForTimeout(TIMEOUTS.VERY_LONG);
  782. console.debug(`✓ 删除残疾人记录: ${name}`);
  783. }
  784. /**
  785. * 获取列表中所有残疾人记录的数据
  786. * @returns 残疾人信息数组
  787. */
  788. async getListData(): Promise<Array<{
  789. name: string;
  790. idCard: string;
  791. disabilityType: string;
  792. disabilityLevel: string;
  793. phone: string;
  794. address: string;
  795. }>> {
  796. const rows = await this.personTable.locator('tbody tr').all();
  797. const data: Array<{
  798. name: string;
  799. idCard: string;
  800. disabilityType: string;
  801. disabilityLevel: string;
  802. phone: string;
  803. address: string;
  804. }> = [];
  805. for (const row of rows) {
  806. const cells = await row.locator('td').all();
  807. if (cells.length >= 6) {
  808. data.push({
  809. name: await cells[0].textContent() || '',
  810. idCard: await cells[2].textContent() || '',
  811. disabilityType: await cells[4].textContent() || '',
  812. disabilityLevel: await cells[5].textContent() || '',
  813. phone: await cells[6].textContent() || '',
  814. address: '',
  815. });
  816. }
  817. }
  818. return data;
  819. }
  820. /**
  821. * 获取当前列表记录数量
  822. * @returns 记录数量
  823. */
  824. async getListCount(): Promise<number> {
  825. return await this.personTable.locator('tbody tr').count();
  826. }
  827. /**
  828. * 按残疾类型筛选
  829. * @param disabilityType 残疾类型
  830. */
  831. async filterByDisabilityType(disabilityType: string): Promise<void> {
  832. const filterSelect = this.page.locator('[data-testid="disability-type-filter"]');
  833. await filterSelect.click();
  834. await this.page.getByRole('option', { name: disabilityType }).click();
  835. await this.page.waitForLoadState('networkidle');
  836. await this.page.waitForTimeout(TIMEOUTS.LONG);
  837. console.debug(`✓ 按残疾类型筛选: ${disabilityType}`);
  838. }
  839. /**
  840. * 重置筛选条件
  841. */
  842. async resetFilters(): Promise<void> {
  843. const resetButton = this.page.getByRole('button', { name: '重置筛选' });
  844. await resetButton.click();
  845. await this.page.waitForLoadState('networkidle');
  846. await this.page.waitForTimeout(TIMEOUTS.LONG);
  847. console.debug('✓ 已重置筛选条件');
  848. }
  849. /**
  850. * 等待详情对话框关闭
  851. */
  852. async waitForDetailDialogClosed(): Promise<void> {
  853. const dialog = this.page.locator('[role="dialog"]').filter({ hasText: '残疾人详情' });
  854. await dialog.waitFor({ state: 'hidden', timeout: TIMEOUTS.DIALOG }).catch(() => {});
  855. await this.page.waitForTimeout(TIMEOUTS.MEDIUM);
  856. }
  857. /**
  858. * 提交表单并保存(编辑模式通用方法)
  859. * @returns 提交结果
  860. */
  861. async submitAndSave(): Promise<{
  862. hasSuccess: boolean;
  863. hasError: boolean;
  864. errorMessage?: string;
  865. successMessage?: string;
  866. }> {
  867. // 点击更新按钮(编辑模式)
  868. const submitButton = this.page.getByRole('button', { name: '更新' });
  869. await submitButton.click();
  870. // 等待网络请求完成
  871. await this.page.waitForLoadState('networkidle', { timeout: TIMEOUTS.TABLE_LOAD }).catch(() => {});
  872. await this.page.waitForTimeout(TIMEOUTS.VERY_LONG);
  873. // 检查 Toast 消息
  874. const errorToast = this.page.locator('[data-sonner-toast][data-type="error"]');
  875. const successToast = this.page.locator('[data-sonner-toast][data-type="success"]');
  876. const hasError = await errorToast.count() > 0;
  877. const hasSuccess = await successToast.count() > 0;
  878. let errorMessage: string | null = null;
  879. let successMessage: string | null = null;
  880. if (hasError) {
  881. errorMessage = await errorToast.first().textContent();
  882. }
  883. if (hasSuccess) {
  884. successMessage = await successToast.first().textContent();
  885. }
  886. return {
  887. hasSuccess: hasSuccess || (!hasError && !hasSuccess),
  888. hasError,
  889. errorMessage: errorMessage ?? undefined,
  890. successMessage: successMessage ?? undefined,
  891. };
  892. }
  893. /**
  894. * 导出残疾人列表数据
  895. * @returns 下载事件(可用于验证下载)
  896. */
  897. async exportData(): Promise<{
  898. success: boolean;
  899. fileName?: string;
  900. }> {
  901. // 监听下载事件
  902. const downloadPromise = this.page.waitForEvent('download', { timeout: TIMEOUTS.TABLE_LOAD }).catch(() => null);
  903. // 点击导出按钮
  904. const exportButton = this.page.getByRole('button', { name: /导出|下载|Export/i }).first();
  905. const buttonExists = await exportButton.count() > 0;
  906. if (!buttonExists) {
  907. console.debug('⚠️ exportData: 未找到导出按钮');
  908. return { success: false };
  909. }
  910. await exportButton.click();
  911. // 等待下载开始
  912. const download = await downloadPromise;
  913. if (download) {
  914. const fileName = download.suggestedFilename();
  915. console.debug(`✓ exportData: 文件下载开始: ${fileName}`);
  916. return { success: true, fileName };
  917. }
  918. return { success: false };
  919. }
  920. }