disability-person.page.ts 37 KB

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