expense_edit_page.dart 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208
  1. import 'dart:async';
  2. import 'package:flutter/material.dart';
  3. import 'package:flutter/services.dart';
  4. import 'package:flutter_riverpod/flutter_riverpod.dart';
  5. import 'package:tdesign_flutter/tdesign_flutter.dart';
  6. import 'package:dio/dio.dart';
  7. import 'package:go_router/go_router.dart';
  8. import '../../core/network/api_exception.dart';
  9. import '../../core/utils/responsive.dart';
  10. import '../../core/utils/date_utils.dart' as du;
  11. import '../../shared/widgets/form_section.dart';
  12. import '../../shared/widgets/form_field_row.dart';
  13. import '../../shared/widgets/app_skeletons.dart';
  14. import '../../shared/widgets/nav_bar_config.dart';
  15. import 'widgets/expense_detail_dialog.dart';
  16. import '../../shared/widgets/searchable_picker_sheet.dart';
  17. import '../../shared/widgets/loading_dialog.dart';
  18. import '../../shared/widgets/action_bar.dart';
  19. import 'expense_api.dart';
  20. import '../../core/i18n/app_localizations.dart';
  21. import 'expense_model.dart';
  22. import '../../core/theme/app_colors.dart';
  23. import '../../core/theme/app_colors_extension.dart';
  24. import '../../core/navigation/host_app_channel.dart';
  25. import '../../core/utils/amount_utils.dart';
  26. /// 费用报销修改页
  27. ///
  28. /// 完全参考 [ExpenseCreatePage] 创建页,但:
  29. /// - 无草稿功能
  30. /// - 无附件上传区
  31. /// - 无从申请单导入链接
  32. /// - initState 中加载原单数据并回填
  33. /// - 基本信息区顶部加单号、日期只读行
  34. /// - ActionBar 仅含提交按钮
  35. /// - 提交时 HeadData 加 BX_NO,成功 pop(true) 返回详情页
  36. class ExpenseEditPage extends ConsumerStatefulWidget {
  37. final String billNo;
  38. const ExpenseEditPage({super.key, required this.billNo});
  39. @override
  40. ConsumerState<ExpenseEditPage> createState() => _ExpenseEditPageState();
  41. }
  42. class _ExpenseEditPageState extends ConsumerState<ExpenseEditPage> {
  43. final _purposeController = TextEditingController();
  44. final _purposeFocus = FocusNode();
  45. final _remarkController = TextEditingController();
  46. final _remarkFocus = FocusNode();
  47. final _scrollCtrl = ScrollController();
  48. final _detailsSectionKey = GlobalKey();
  49. // ── 参考数据(从 API 加载) ──
  50. List<CurrencyItem> _currencies = [];
  51. EmployeeItem? _selEmployee;
  52. dynamic _acctTree;
  53. bool _firstBuild = true;
  54. bool _refDataLoading = true;
  55. bool _addingDetail = false;
  56. bool _isSubmitting = false;
  57. bool _canEditApprovedAmount = false;
  58. String? _loadingError;
  59. // ── 原单数据 ──
  60. ExpenseModel? _expense;
  61. String _billNo = '';
  62. String _expenseDate = '';
  63. // ── 报销部门 ──
  64. String _selectedDeptId = '';
  65. String _selectedDeptName = '';
  66. @override
  67. void initState() {
  68. super.initState();
  69. SystemChrome.setSystemUIOverlayStyle(
  70. const SystemUiOverlayStyle(
  71. statusBarColor: Colors.transparent,
  72. statusBarIconBrightness: Brightness.dark,
  73. ),
  74. );
  75. _purposeFocus.addListener(() => _ensureVisible(_purposeFocus));
  76. _remarkFocus.addListener(() => _ensureVisible(_remarkFocus));
  77. _billNo = widget.billNo;
  78. _loadData();
  79. _checkApprovedAmountRight();
  80. }
  81. Future<void> _checkApprovedAmountRight() async {
  82. try {
  83. final api = ref.read(expenseApiProvider);
  84. final ok = await api.checkSpcRight('MONCJ_AMTN_SH');
  85. if (mounted) setState(() => _canEditApprovedAmount = ok);
  86. } catch (_) {
  87. if (mounted) setState(() => _canEditApprovedAmount = false);
  88. }
  89. }
  90. Future<void> _loadData() async {
  91. try {
  92. final api = ref.read(expenseApiProvider);
  93. final results = await Future.wait([
  94. api.getCurrencies(),
  95. api.fetchDetail(widget.billNo),
  96. api.getAcctSubjects(),
  97. ]);
  98. if (!mounted) return;
  99. final expense = results[1] as ExpenseModel;
  100. setState(() {
  101. _currencies = results[0] as List<CurrencyItem>;
  102. _acctTree = _convertAcctTree(results[2]);
  103. _expense = expense;
  104. _expenseDate = expense.expenseDate != null
  105. ? du.DateUtils.formatDate(expense.expenseDate!)
  106. : _today();
  107. _selectedDeptId = expense.deptId;
  108. _selectedDeptName = expense.deptName;
  109. _selEmployee = expense.applicantId.isNotEmpty
  110. ? EmployeeItem(salNo: expense.applicantId, name: expense.applicantName)
  111. : null;
  112. _purposeController.text = expense.purpose;
  113. _remarkController.text = expense.remark;
  114. _refDataLoading = false;
  115. _firstBuild = false;
  116. _recalculateAmount();
  117. });
  118. } catch (e) {
  119. if (!mounted) return;
  120. setState(() {
  121. _refDataLoading = false;
  122. _firstBuild = false;
  123. _loadingError = e.toString();
  124. });
  125. }
  126. }
  127. Future<void> _showEmployeePicker() async {
  128. FocusManager.instance.primaryFocus?.unfocus();
  129. final l10n = AppLocalizations.of(context);
  130. final api = ref.read(expenseApiProvider);
  131. final result = await showSearchablePicker<EmployeeItem>(
  132. context,
  133. title: '${l10n.get('select')}${l10n.get('expensePersonnel')}',
  134. searchHint: l10n.get('search'),
  135. loader: (keyword, page) =>
  136. api.getEmployees(keyword: keyword, page: page, size: 20),
  137. labelBuilder: (e) => e.name.isEmpty ? e.salNo : '${e.salNo} ${e.name}',
  138. onRefresh: () => api.clearRefCache(),
  139. );
  140. if (result != null && mounted) {
  141. setState(() => _selEmployee = result);
  142. }
  143. }
  144. void _ensureVisible(FocusNode node) {
  145. if (!node.hasFocus) return;
  146. WidgetsBinding.instance.addPostFrameCallback((_) {
  147. if (node.hasFocus && _scrollCtrl.hasClients) {
  148. final ctx = node.context;
  149. if (ctx != null) {
  150. Scrollable.ensureVisible(
  151. ctx,
  152. alignment: 0.3,
  153. duration: const Duration(milliseconds: 300),
  154. );
  155. }
  156. }
  157. });
  158. }
  159. @override
  160. void dispose() {
  161. _purposeController.dispose();
  162. _purposeFocus.dispose();
  163. _remarkController.dispose();
  164. _remarkFocus.dispose();
  165. _scrollCtrl.dispose();
  166. super.dispose();
  167. }
  168. // ═══ 状态更新助手(替代 Riverpod controller) ═══
  169. void _updatePurpose(String purpose) {
  170. if (_expense == null) return;
  171. setState(() {
  172. _expense = _expense!.copyWith(purpose: purpose);
  173. });
  174. }
  175. void _updateRemark(String remark) {
  176. if (_expense == null) return;
  177. setState(() {
  178. _expense = _expense!.copyWith(remark: remark);
  179. });
  180. }
  181. void _updatePaymentMethod(String method) {
  182. if (_expense == null) return;
  183. setState(() {
  184. _expense = _expense!.copyWith(paymentMethod: method);
  185. });
  186. }
  187. void _updateCurrencyCode(String code) {
  188. if (_expense == null) return;
  189. setState(() {
  190. _expense = _expense!.copyWith(currencyCode: code);
  191. });
  192. }
  193. void _setGenerateVoucher(bool value) {
  194. if (_expense == null) return;
  195. setState(() {
  196. _expense = _expense!.copyWith(isGenerateVoucher: value);
  197. });
  198. }
  199. void _addDetail(ExpenseDetailModel detail) {
  200. if (_expense == null) return;
  201. setState(() {
  202. _expense = _expense!.copyWith(details: [..._expense!.details, detail]);
  203. });
  204. _recalculateAmount();
  205. }
  206. void _updateDetail(int index, ExpenseDetailModel detail) {
  207. if (_expense == null) return;
  208. final details = [..._expense!.details];
  209. details[index] = detail;
  210. setState(() {
  211. _expense = _expense!.copyWith(details: details);
  212. });
  213. _recalculateAmount();
  214. }
  215. void _removeDetail(int index) {
  216. if (_expense == null) return;
  217. final details = [..._expense!.details]..removeAt(index);
  218. setState(() {
  219. _expense = _expense!.copyWith(details: details);
  220. });
  221. _recalculateAmount();
  222. }
  223. List<Map<String, dynamic>> _convertAcctTree(dynamic tree) {
  224. if (tree is! List) return [];
  225. return (tree as List).map<Map<String, dynamic>>((item) {
  226. final map = Map<String, dynamic>.from(item is Map ? item : {});
  227. if (map.containsKey('children') && map['children'] != null) {
  228. map['children'] = _convertAcctTree(map['children']);
  229. }
  230. return map;
  231. }).toList();
  232. }
  233. void _recalculateAmount() {
  234. if (_expense == null) return;
  235. var totalAmount = 0.0;
  236. var approvedAmount = 0.0;
  237. for (final d in _expense!.details) {
  238. totalAmount += d.totalAmount;
  239. approvedAmount += d.approvedAmount;
  240. }
  241. setState(() {
  242. _expense = _expense!.copyWith(
  243. totalAmount: totalAmount,
  244. approvedAmount: approvedAmount,
  245. );
  246. });
  247. }
  248. String _currencyLabel(String code) {
  249. final match = _currencies.where((c) => c.curId == code);
  250. return match.isNotEmpty ? '${match.first.curId}/${match.first.name}' : code;
  251. }
  252. Future<void> _showDeptPicker() async {
  253. FocusManager.instance.primaryFocus?.unfocus();
  254. final l10n = AppLocalizations.of(context);
  255. final api = ref.read(expenseApiProvider);
  256. final result = await showSearchablePicker<DepartmentItem>(
  257. context,
  258. title: '${l10n.get('select')}${l10n.get('expenseDept')}',
  259. searchHint: l10n.get('search'),
  260. loader: (keyword, page) =>
  261. api.getDepartments(keyword: keyword, page: page, size: 20),
  262. labelBuilder: (d) => d.name.isEmpty ? d.dep : '${d.dep} ${d.name}',
  263. onRefresh: () => api.clearRefCache(),
  264. );
  265. if (result != null && mounted) {
  266. setState(() {
  267. _selectedDeptId = result.dep;
  268. _selectedDeptName = result.name;
  269. });
  270. }
  271. }
  272. Map<String, dynamic> _buildSubmitData() {
  273. final expense = _expense!;
  274. return {
  275. 'HeadData': {
  276. 'BX_NO': _billNo,
  277. 'BX_DD': _today(),
  278. 'DEP': _selectedDeptId,
  279. 'USR_NO': _selEmployee?.salNo ?? '',
  280. 'PAY_ID': expense.paymentMethod,
  281. 'USR': HostAppChannel.usr,
  282. 'REM': expense.remark,
  283. 'CUR_ID': expense.currencyCode,
  284. 'EXC_RTO': 1,
  285. 'REASON': expense.purpose,
  286. 'VOH_ID': expense.isGenerateVoucher ? 'T' : 'F',
  287. },
  288. 'BodyData1': expense.details.asMap().entries.map((e) {
  289. final d = e.value;
  290. final item = <String, dynamic>{
  291. 'BX_NO': _billNo,
  292. 'BX_DD': _today(),
  293. 'ACC_NO': d.acctSubjectId,
  294. 'AMT': d.totalAmount,
  295. 'AMTN': d.amount,
  296. 'AMTN_SH': d.approvedAmount,
  297. 'REM': d.remark,
  298. 'CUST': d.customerVendorId,
  299. 'IDX_NO': d.expenseCategory,
  300. 'OBJ_NO': d.projectId.isNotEmpty ? d.projectId : '',
  301. 'TAX': d.taxAmount,
  302. 'TAX_RTO': d.taxRate,
  303. 'DEP': d.costDeptId,
  304. 'AE_NO': d.aeNo,
  305. 'AE_DD': d.aeDd,
  306. 'BNK_NO': d.bankName,
  307. 'BNK_ID': d.bankAccount,
  308. 'ACCNAME': d.bankAccountName,
  309. 'SQ_MAN': d.sqMan.isNotEmpty ? d.sqMan : HostAppChannel.usr,
  310. 'EST_ITM': d.aeNo.isNotEmpty ? d.sortOrder : 0,
  311. };
  312. if (d.preItm != null) {
  313. item['PRE_ITM'] = d.preItm;
  314. }
  315. return item;
  316. }).toList(),
  317. };
  318. }
  319. // ═══ Build ═══
  320. @override
  321. Widget build(BuildContext context) {
  322. final r = ResponsiveHelper.of(context);
  323. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  324. final l10n = AppLocalizations.of(context);
  325. final bottomInset = MediaQuery.of(context).padding.bottom;
  326. if (_loadingError != null) {
  327. return Center(
  328. child: Column(
  329. mainAxisSize: MainAxisSize.min,
  330. children: [
  331. Icon(Icons.error_outline, size: 48, color: colors.danger),
  332. const SizedBox(height: 16),
  333. Padding(
  334. padding: const EdgeInsets.symmetric(horizontal: 32),
  335. child: Text(
  336. _loadingError!,
  337. textAlign: TextAlign.center,
  338. style: TextStyle(
  339. fontSize: AppFontSizes.body,
  340. color: colors.textSecondary,
  341. ),
  342. ),
  343. ),
  344. const SizedBox(height: 16),
  345. TDButton(
  346. text: l10n.get('retry'),
  347. size: TDButtonSize.medium,
  348. onTap: () {
  349. setState(() {
  350. _loadingError = null;
  351. _firstBuild = true;
  352. _refDataLoading = true;
  353. });
  354. _loadData();
  355. },
  356. ),
  357. ],
  358. ),
  359. );
  360. }
  361. if (_firstBuild || _expense == null) {
  362. return const SkeletonFormPage(showImportLink: false);
  363. }
  364. Future.microtask(
  365. () => ref.read(pageBackProvider.notifier).state = () => _doPop(l10n),
  366. );
  367. Widget pageContent = PopScope(
  368. canPop: false,
  369. onPopInvokedWithResult: (didPop, _) {
  370. if (didPop) return;
  371. _doPop(l10n);
  372. },
  373. child: Column(
  374. children: [
  375. Expanded(
  376. child: Align(
  377. alignment: Alignment.topCenter,
  378. child: ConstrainedBox(
  379. constraints: BoxConstraints(maxWidth: r.formMaxWidth),
  380. child: SingleChildScrollView(
  381. controller: _scrollCtrl,
  382. padding: const EdgeInsets.all(16),
  383. child: Column(
  384. crossAxisAlignment: CrossAxisAlignment.start,
  385. children: [
  386. _buildBasicInfoSection(l10n, colors),
  387. const SizedBox(height: 16),
  388. Container(
  389. key: _detailsSectionKey,
  390. child: _buildDetailSection(l10n, colors),
  391. ),
  392. const SizedBox(height: 24),
  393. _buildPageFooter(),
  394. ],
  395. ),
  396. ),
  397. ),
  398. ),
  399. ),
  400. ColoredBox(
  401. color: colors.bgCard,
  402. child: Column(
  403. mainAxisSize: MainAxisSize.min,
  404. children: [
  405. _buildBottomButtons(l10n),
  406. if (bottomInset > 0) SizedBox(height: bottomInset),
  407. ],
  408. ),
  409. ),
  410. ],
  411. ),
  412. );
  413. return pageContent;
  414. }
  415. Widget _buildBasicInfoSection(
  416. AppLocalizations l10n,
  417. AppColorsExtension colors,
  418. ) {
  419. final expense = _expense!;
  420. return FormSection(
  421. title: l10n.get('basicInfo'),
  422. leadingIcon: Icons.info_outline,
  423. children: [
  424. FormFieldRow(
  425. label: l10n.get('expenseNo'),
  426. value: _billNo,
  427. readOnly: true,
  428. showArrow: false,
  429. ),
  430. const SizedBox(height: 16),
  431. FormFieldRow(
  432. label: l10n.get('date'),
  433. value: _expenseDate,
  434. readOnly: true,
  435. showArrow: false,
  436. ),
  437. const SizedBox(height: 16),
  438. FormFieldRow(
  439. label: l10n.get('expensePersonnel'),
  440. value: _selEmployee != null
  441. ? '${_selEmployee!.salNo}/${_selEmployee!.name}'
  442. : '',
  443. hint: l10n.get('pleaseSelect'),
  444. onTap: _showEmployeePicker,
  445. ),
  446. const SizedBox(height: 16),
  447. FormFieldRow(
  448. label: l10n.get('expenseDept'),
  449. value: _selectedDeptName.isNotEmpty
  450. ? '$_selectedDeptId/$_selectedDeptName'
  451. : null,
  452. hint: l10n.get('pleaseSelect'),
  453. onTap: _refDataLoading ? null : () => _showDeptPicker(),
  454. ),
  455. const SizedBox(height: 16),
  456. _label(l10n.get('expenseReason'), required: true),
  457. const SizedBox(height: 8),
  458. TDTextarea(
  459. controller: _purposeController,
  460. focusNode: _purposeFocus,
  461. hintText: l10n.get('enterExpenseReason'),
  462. maxLines: 4,
  463. minLines: 1,
  464. maxLength: 500,
  465. indicator: true,
  466. padding: EdgeInsets.zero,
  467. bordered: true,
  468. backgroundColor: colors.bgPage,
  469. onChanged: (_) => _updatePurpose(_purposeController.text),
  470. ),
  471. const SizedBox(height: 16),
  472. FormFieldRow(
  473. label: l10n.get('paymentMethod'),
  474. value: expense.paymentMethod,
  475. hint: l10n.get('pleaseEnter'),
  476. onTap: () => _showTextInput(
  477. l10n.get('paymentMethod'),
  478. (v) => _updatePaymentMethod(v),
  479. initialText: expense.paymentMethod,
  480. ),
  481. onClear: () => _updatePaymentMethod(''),
  482. ),
  483. const SizedBox(height: 16),
  484. FormFieldRow(
  485. label: l10n.get('currency'),
  486. value: expense.currencyCode.isNotEmpty
  487. ? _currencyLabel(expense.currencyCode)
  488. : null,
  489. hint: l10n.get('selectCurrency'),
  490. onTap: () => _showCurrencyPicker(expense.currencyCode),
  491. onClear: () => _updateCurrencyCode(''),
  492. ),
  493. const SizedBox(height: 16),
  494. Row(
  495. mainAxisAlignment: MainAxisAlignment.spaceBetween,
  496. children: [
  497. Text(
  498. l10n.get('generateVoucher'),
  499. style: TextStyle(
  500. fontSize: AppFontSizes.subtitle,
  501. color: colors.textSecondary,
  502. ),
  503. ),
  504. TDSwitch(
  505. isOn: expense.isGenerateVoucher,
  506. onChanged: (v) {
  507. _setGenerateVoucher(v);
  508. return v;
  509. },
  510. ),
  511. ],
  512. ),
  513. const SizedBox(height: 16),
  514. _label(l10n.get('remark')),
  515. const SizedBox(height: 8),
  516. TDTextarea(
  517. controller: _remarkController,
  518. focusNode: _remarkFocus,
  519. hintText: l10n.get('enterRemark'),
  520. maxLines: 3,
  521. minLines: 1,
  522. maxLength: 500,
  523. indicator: true,
  524. padding: EdgeInsets.zero,
  525. bordered: true,
  526. backgroundColor: colors.bgPage,
  527. onChanged: (_) => _updateRemark(_remarkController.text),
  528. ),
  529. ],
  530. );
  531. }
  532. Widget _buildDetailSection(AppLocalizations l10n, AppColorsExtension colors) {
  533. final expense = _expense!;
  534. final totalAmount = expense.details.fold<double>(
  535. 0,
  536. (sum, d) => sum + d.totalAmount,
  537. );
  538. final totalApproved = expense.details.fold<double>(
  539. 0,
  540. (sum, d) => sum + d.approvedAmount,
  541. );
  542. return FormSection(
  543. title: l10n.get('expenseDetails'),
  544. leadingIcon: Icons.receipt_long_outlined,
  545. showAction: true,
  546. actionText: l10n.get('add'),
  547. onActionTap: () => _showAddDetailDialog(),
  548. children: [
  549. if (expense.details.isEmpty)
  550. Padding(
  551. padding: const EdgeInsets.symmetric(vertical: 8),
  552. child: Text(
  553. l10n.get('noDetailHint'),
  554. style: TextStyle(
  555. fontSize: AppFontSizes.subtitle,
  556. color: colors.textPlaceholder,
  557. ),
  558. ),
  559. )
  560. else
  561. ...expense.details.asMap().entries.map((entry) {
  562. final d = entry.value;
  563. return GestureDetector(
  564. onTap: () => _showAddDetailDialog(editIndex: entry.key),
  565. child: Container(
  566. margin: const EdgeInsets.symmetric(vertical: 6),
  567. padding: const EdgeInsets.all(12),
  568. decoration: BoxDecoration(
  569. color: colors.bgPage,
  570. borderRadius: BorderRadius.circular(8),
  571. ),
  572. child: Row(
  573. children: [
  574. Expanded(
  575. child: Column(
  576. crossAxisAlignment: CrossAxisAlignment.start,
  577. children: [
  578. Row(
  579. children: [
  580. Expanded(
  581. child: Text(
  582. d.categoryName.isNotEmpty
  583. ? '${d.expenseCategory}/${d.categoryName}'
  584. : d.expenseCategory,
  585. style: TextStyle(
  586. fontSize: AppFontSizes.body,
  587. fontWeight: FontWeight.w500,
  588. color: colors.textPrimary,
  589. ),
  590. ),
  591. ),
  592. Column(
  593. crossAxisAlignment: CrossAxisAlignment.end,
  594. children: [
  595. Text(
  596. formatAmount(d.totalAmount),
  597. style: TextStyle(
  598. fontSize: AppFontSizes.body,
  599. fontWeight: FontWeight.w600,
  600. color: colors.amountPrimary,
  601. ),
  602. ),
  603. if (d.approvedAmount > 0)
  604. Text(
  605. formatAmount(d.approvedAmount),
  606. style: TextStyle(
  607. fontSize: AppFontSizes.body,
  608. fontWeight: FontWeight.w600,
  609. color: colors.success,
  610. ),
  611. ),
  612. ],
  613. ),
  614. ],
  615. ),
  616. const SizedBox(height: 2),
  617. Text(
  618. '${l10n.get('amountExcludingTax')}: ${formatAmount(d.amount)}',
  619. style: TextStyle(
  620. fontSize: AppFontSizes.caption,
  621. color: colors.textSecondary,
  622. ),
  623. ),
  624. if (d.taxAmount > 0)
  625. Text(
  626. '${l10n.get('taxAmount')}: ${formatAmount(d.taxAmount)}',
  627. style: TextStyle(
  628. fontSize: AppFontSizes.caption,
  629. color: colors.textSecondary,
  630. ),
  631. ),
  632. if (d.taxRate > 0)
  633. Text(
  634. '${l10n.get('taxRate')}: ${d.taxRate.toStringAsFixed(0)}%',
  635. style: TextStyle(
  636. fontSize: AppFontSizes.caption,
  637. color: colors.textSecondary,
  638. ),
  639. ),
  640. if (d.acctSubjectId.isNotEmpty)
  641. Text(
  642. '${l10n.get('acctSubject')}: ${d.acctSubjectId}${d.acctSubjectName.isNotEmpty ? '/${d.acctSubjectName}' : ''}',
  643. maxLines: 1,
  644. overflow: TextOverflow.ellipsis,
  645. style: TextStyle(
  646. fontSize: AppFontSizes.caption,
  647. color: colors.textSecondary,
  648. ),
  649. ),
  650. if (d.aeNo.isNotEmpty)
  651. Text(
  652. '${l10n.get('expenseApplyNo')}: ${d.aeNo}',
  653. maxLines: 1,
  654. overflow: TextOverflow.ellipsis,
  655. style: TextStyle(
  656. fontSize: AppFontSizes.caption,
  657. color: colors.textSecondary,
  658. ),
  659. ),
  660. if (d.aeDd.isNotEmpty)
  661. Text(
  662. '${l10n.get('applyDate')}: ${d.aeDd.length >= 10 ? d.aeDd.substring(0, 10) : d.aeDd}',
  663. style: TextStyle(
  664. fontSize: AppFontSizes.caption,
  665. color: colors.textSecondary,
  666. ),
  667. ),
  668. if (d.projectId.isNotEmpty)
  669. Text(
  670. '${l10n.get('project')}: ${d.projectId}${d.projectName.isNotEmpty ? '/${d.projectName}' : ''}',
  671. maxLines: 1,
  672. overflow: TextOverflow.ellipsis,
  673. style: TextStyle(
  674. fontSize: AppFontSizes.caption,
  675. color: colors.textSecondary,
  676. ),
  677. ),
  678. if (d.costDeptId.isNotEmpty)
  679. Text(
  680. '${l10n.get('costDept')}: ${d.costDeptId}${d.costDeptName.isNotEmpty ? '/${d.costDeptName}' : ''}',
  681. maxLines: 1,
  682. overflow: TextOverflow.ellipsis,
  683. style: TextStyle(
  684. fontSize: AppFontSizes.caption,
  685. color: colors.textSecondary,
  686. ),
  687. ),
  688. if (d.customerVendorId.isNotEmpty)
  689. Text(
  690. '${l10n.get('customerVendor')}: ${d.customerVendorId}${d.customerVendorName.isNotEmpty ? '/${d.customerVendorName}' : ''}',
  691. maxLines: 1,
  692. overflow: TextOverflow.ellipsis,
  693. style: TextStyle(
  694. fontSize: AppFontSizes.caption,
  695. color: colors.textSecondary,
  696. ),
  697. ),
  698. if (d.sqMan.isNotEmpty)
  699. Text(
  700. '${l10n.get('applicant')}: ${d.sqMan}${d.sqManName.isNotEmpty ? '/${d.sqManName}' : ''}',
  701. style: TextStyle(
  702. fontSize: AppFontSizes.caption,
  703. color: colors.textSecondary,
  704. ),
  705. ),
  706. if (d.bankAccountName.isNotEmpty)
  707. Text(
  708. '${l10n.get('bankAccountName')}: ${d.bankAccountName}',
  709. maxLines: 1,
  710. overflow: TextOverflow.ellipsis,
  711. style: TextStyle(
  712. fontSize: AppFontSizes.caption,
  713. color: colors.textSecondary,
  714. ),
  715. ),
  716. if (d.bankName.isNotEmpty)
  717. Text(
  718. '${l10n.get('bankName')}: ${d.bankName}',
  719. maxLines: 1,
  720. overflow: TextOverflow.ellipsis,
  721. style: TextStyle(
  722. fontSize: AppFontSizes.caption,
  723. color: colors.textSecondary,
  724. ),
  725. ),
  726. if (d.bankAccount.isNotEmpty)
  727. Text(
  728. '${l10n.get('bankAccount')}: ${d.bankAccount}',
  729. maxLines: 1,
  730. overflow: TextOverflow.ellipsis,
  731. style: TextStyle(
  732. fontSize: AppFontSizes.caption,
  733. color: colors.textSecondary,
  734. ),
  735. ),
  736. if (d.remark.isNotEmpty)
  737. Text(
  738. '${l10n.get('remark')}: ${d.remark}',
  739. maxLines: 2,
  740. overflow: TextOverflow.ellipsis,
  741. style: TextStyle(
  742. fontSize: AppFontSizes.caption,
  743. color: colors.textSecondary,
  744. ),
  745. ),
  746. ],
  747. ),
  748. ),
  749. const SizedBox(width: 8),
  750. GestureDetector(
  751. onTap: () => _removeDetail(entry.key),
  752. child: Icon(
  753. Icons.close,
  754. size: 18,
  755. color: colors.textSecondary,
  756. ),
  757. ),
  758. ],
  759. ),
  760. ),
  761. );
  762. }),
  763. const SizedBox(height: 8),
  764. Row(
  765. mainAxisAlignment: MainAxisAlignment.spaceBetween,
  766. children: [
  767. Text(
  768. l10n.get('totalExpense'),
  769. style: TextStyle(
  770. fontSize: AppFontSizes.body,
  771. fontWeight: FontWeight.w600,
  772. color: colors.textPrimary,
  773. ),
  774. ),
  775. Text(
  776. formatAmount(totalAmount),
  777. style: TextStyle(
  778. fontSize: AppFontSizes.subtitle,
  779. fontWeight: FontWeight.w700,
  780. color: colors.amountPrimary,
  781. ),
  782. ),
  783. ],
  784. ),
  785. const SizedBox(height: 4),
  786. Row(
  787. mainAxisAlignment: MainAxisAlignment.spaceBetween,
  788. children: [
  789. Text(
  790. l10n.get('approvedTotal'),
  791. style: TextStyle(
  792. fontSize: AppFontSizes.body,
  793. fontWeight: FontWeight.w600,
  794. color: colors.textPrimary,
  795. ),
  796. ),
  797. Text(
  798. formatAmount(totalApproved),
  799. style: TextStyle(
  800. fontSize: AppFontSizes.subtitle,
  801. fontWeight: FontWeight.w700,
  802. color: totalApproved > 0 ? colors.success : colors.textPrimary,
  803. ),
  804. ),
  805. ],
  806. ),
  807. ],
  808. );
  809. }
  810. Future<void> _showAddDetailDialog({int? editIndex}) async {
  811. if (_addingDetail) return;
  812. _addingDetail = true;
  813. try {
  814. final l10n = AppLocalizations.of(context);
  815. final expense = _expense!;
  816. ExpenseDetailInputData? initialData;
  817. if (editIndex != null) {
  818. final d = expense.details[editIndex];
  819. initialData = ExpenseDetailInputData(
  820. category: d.expenseCategory,
  821. categoryName: d.categoryName,
  822. acctSubjectId: d.acctSubjectId,
  823. acctSubjectName: d.acctSubjectName,
  824. purpose: d.purpose,
  825. amount: d.totalAmount,
  826. taxRate: d.taxRate,
  827. projectId: d.projectId,
  828. projectName: d.projectName,
  829. costDeptId: d.costDeptId,
  830. costDeptName: d.costDeptName,
  831. customerVendorId: d.customerVendorId,
  832. customerVendorName: d.customerVendorName,
  833. approvedAmount: d.approvedAmount,
  834. bankName: d.bankName,
  835. bankAccountName: d.bankAccountName,
  836. bankAccount: d.bankAccount,
  837. remark: d.remark,
  838. attachmentPaths: d.attachments,
  839. sqMan: d.sqMan,
  840. sqManName: d.sqManName,
  841. aeNo: d.aeNo,
  842. aeDd: d.aeDd,
  843. );
  844. }
  845. FocusManager.instance.primaryFocus?.unfocus();
  846. final result = await ExpenseDetailDialog.show(
  847. context,
  848. api: ref.read(expenseApiProvider),
  849. l10n: l10n,
  850. initialData: initialData,
  851. checkAttachHealth: () =>
  852. ref.read(expenseApiProvider).checkAttachHealth(),
  853. showAttachments: false,
  854. canEditApprovedAmount: _canEditApprovedAmount,
  855. acctTree: _acctTree,
  856. );
  857. if (result != null && mounted) {
  858. final now = DateTime.now();
  859. final detail = ExpenseDetailModel(
  860. id: editIndex != null
  861. ? expense.details[editIndex].id
  862. : now.millisecondsSinceEpoch.toString(),
  863. expenseId: '',
  864. expenseCategory: result.category,
  865. categoryName: result.categoryName,
  866. purpose: result.purpose,
  867. amount: result.taxRate > 0
  868. ? result.amount / (1 + result.taxRate / 100)
  869. : result.amount,
  870. taxRate: result.taxRate,
  871. taxAmount: result.taxRate > 0
  872. ? result.amount - result.amount / (1 + result.taxRate / 100)
  873. : 0,
  874. totalAmount: result.amount,
  875. projectId: result.projectId,
  876. projectName: result.projectName,
  877. costDeptId: result.costDeptId,
  878. costDeptName: result.costDeptName,
  879. acctSubjectId: result.acctSubjectId,
  880. acctSubjectName: result.acctSubjectName,
  881. customerVendorId: result.customerVendorId,
  882. customerVendorName: result.customerVendorName,
  883. approvedAmount: result.approvedAmount,
  884. bankName: result.bankName,
  885. bankAccountName: result.bankAccountName,
  886. bankAccount: result.bankAccount,
  887. sqMan: result.sqMan,
  888. sqManName: result.sqManName,
  889. aeNo: result.aeNo,
  890. aeDd: result.aeDd,
  891. remark: result.remark,
  892. sortOrder: editIndex != null
  893. ? expense.details[editIndex].sortOrder
  894. : 1,
  895. preItm: editIndex != null ? expense.details[editIndex].preItm : null,
  896. attachments: result.attachmentPaths,
  897. createTime: now,
  898. updateTime: now,
  899. );
  900. if (editIndex != null) {
  901. _updateDetail(editIndex, detail);
  902. } else {
  903. _addDetail(detail);
  904. }
  905. }
  906. } finally {
  907. _addingDetail = false;
  908. }
  909. }
  910. void _showCurrencyPicker(String cur) {
  911. if (_currencies.isEmpty) {
  912. TDToast.showText(
  913. AppLocalizations.of(context).get('noData'),
  914. context: context,
  915. );
  916. return;
  917. }
  918. final l10n = AppLocalizations.of(context);
  919. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  920. final codes = _currencies.map((c) => c.curId).toList();
  921. final labels = _currencies.map((c) => '${c.curId}/${c.name}').toList();
  922. FocusManager.instance.primaryFocus?.unfocus();
  923. TDPicker.showMultiPicker(
  924. context,
  925. title: l10n.get('selectCurrency'),
  926. backgroundColor: colors.bgCard,
  927. data: [labels],
  928. onConfirm: (s) {
  929. if (s.isNotEmpty && s[0] is int) {
  930. final i = s[0] as int;
  931. if (i >= 0 && i < codes.length) {
  932. Navigator.of(context).pop();
  933. _updateCurrencyCode(codes[i]);
  934. }
  935. }
  936. },
  937. );
  938. }
  939. void _showTextInput(
  940. String title,
  941. Function(String) onConfirm, {
  942. String initialText = '',
  943. }) {
  944. FocusScope.of(context).unfocus();
  945. FocusManager.instance.primaryFocus?.unfocus();
  946. final l10n = AppLocalizations.of(context);
  947. final c = TextEditingController(text: initialText);
  948. showGeneralDialog(
  949. context: context,
  950. pageBuilder: (ctx, animation, secondaryAnimation) => TDInputDialog(
  951. textEditingController: c,
  952. title: title,
  953. hintText: l10n.get('pleaseEnter'),
  954. leftBtn: TDDialogButtonOptions(
  955. title: l10n.get('cancel'),
  956. action: () => Navigator.pop(ctx),
  957. ),
  958. rightBtn: TDDialogButtonOptions(
  959. title: l10n.get('confirm'),
  960. action: () {
  961. onConfirm(c.text);
  962. Navigator.pop(ctx);
  963. },
  964. ),
  965. ),
  966. );
  967. }
  968. Widget _label(String t, {bool required = false}) {
  969. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  970. return Text.rich(
  971. TextSpan(
  972. children: [
  973. TextSpan(
  974. text: t,
  975. style: TextStyle(
  976. fontSize: AppFontSizes.subtitle,
  977. color: colors.textSecondary,
  978. ),
  979. ),
  980. if (required)
  981. TextSpan(
  982. text: ' *',
  983. style: TextStyle(
  984. fontSize: AppFontSizes.subtitle,
  985. color: colors.danger,
  986. ),
  987. ),
  988. ],
  989. ),
  990. );
  991. }
  992. Widget _buildBottomButtons(AppLocalizations l10n) {
  993. return ActionBar(
  994. showLeft: false,
  995. showCenter: false,
  996. rightLabel: l10n.get('submit'),
  997. onRightTap: () async {
  998. if (_isSubmitting) return;
  999. final err = _validate(l10n);
  1000. if (err.isNotEmpty) {
  1001. TDToast.showText(err.first, context: context);
  1002. return;
  1003. }
  1004. FocusScope.of(context).unfocus();
  1005. _isSubmitting = true;
  1006. LoadingDialog.show(context, text: l10n.get('submitting'));
  1007. try {
  1008. final data = _buildSubmitData();
  1009. final api = ref.read(expenseApiProvider);
  1010. await api.submit(data);
  1011. if (mounted) {
  1012. LoadingDialog.hide(context);
  1013. TDToast.showSuccess(
  1014. l10n.get('submitSuccess'),
  1015. context: context,
  1016. );
  1017. WidgetsBinding.instance.addPostFrameCallback((_) {
  1018. if (mounted) GoRouter.of(context).pop(true);
  1019. });
  1020. }
  1021. } catch (e) {
  1022. if (mounted) {
  1023. LoadingDialog.hide(context);
  1024. WidgetsBinding.instance.addPostFrameCallback((_) {
  1025. if (mounted) _showSubmitError(e, l10n);
  1026. });
  1027. }
  1028. } finally {
  1029. _isSubmitting = false;
  1030. }
  1031. },
  1032. );
  1033. }
  1034. void _showSubmitError(Object e, AppLocalizations l10n) {
  1035. final message = _extractErrorMessage(e) ?? l10n.get('submitFailedRetry');
  1036. showGeneralDialog(
  1037. context: context,
  1038. pageBuilder: (ctx, animation, secondaryAnimation) => TDConfirmDialog(
  1039. title: l10n.get('submitFailed'),
  1040. content: message,
  1041. buttonStyle: TDDialogButtonStyle.text,
  1042. ),
  1043. );
  1044. }
  1045. String? _extractErrorMessage(Object e) {
  1046. if (e is DioException) {
  1047. if (e.error is ApiException) return (e.error as ApiException).message;
  1048. if (e.error is NetworkException) {
  1049. return (e.error as NetworkException).message;
  1050. }
  1051. }
  1052. return null;
  1053. }
  1054. List<String> _validate(AppLocalizations l10n) {
  1055. final e = <String>[];
  1056. if (_purposeController.text.trim().isEmpty) {
  1057. e.add(l10n.get('enterExpenseReason'));
  1058. }
  1059. if (_expense!.details.isEmpty) {
  1060. e.add(l10n.get('addAtLeastOneDetail'));
  1061. }
  1062. return e;
  1063. }
  1064. bool _hasUnsaved() =>
  1065. _purposeController.text.isNotEmpty ||
  1066. (_expense?.paymentMethod.isNotEmpty ?? false) ||
  1067. (_expense?.currencyCode.isNotEmpty ?? false) ||
  1068. _remarkController.text.isNotEmpty ||
  1069. (_expense?.details.isNotEmpty ?? false);
  1070. void _doPop(AppLocalizations l10n) {
  1071. if (_hasUnsaved()) {
  1072. _showConfirmDialog(
  1073. l10n.get('confirmExit'),
  1074. l10n.get('unsavedContentWarning'),
  1075. l10n.get('continueEditing'),
  1076. l10n.get('discardAndExit'),
  1077. () {
  1078. if (!mounted) return;
  1079. _forcePop();
  1080. },
  1081. );
  1082. } else {
  1083. _forcePop();
  1084. }
  1085. }
  1086. void _forcePop() {
  1087. FocusManager.instance.primaryFocus?.unfocus();
  1088. final router = GoRouter.of(context);
  1089. if (router.canPop()) {
  1090. router.pop();
  1091. } else {
  1092. SystemNavigator.pop();
  1093. }
  1094. }
  1095. void _showConfirmDialog(
  1096. String title,
  1097. String content,
  1098. String leftText,
  1099. String rightText,
  1100. VoidCallback onConfirm,
  1101. ) {
  1102. FocusScope.of(context).unfocus();
  1103. FocusManager.instance.primaryFocus?.unfocus();
  1104. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  1105. showDialog(
  1106. context: context,
  1107. useRootNavigator: true,
  1108. builder: (ctx) => TDAlertDialog(
  1109. title: title,
  1110. content: content,
  1111. buttonStyle: TDDialogButtonStyle.text,
  1112. leftBtn: TDDialogButtonOptions(
  1113. title: leftText,
  1114. titleColor: colors.primary,
  1115. action: () => Navigator.pop(ctx),
  1116. ),
  1117. rightBtn: TDDialogButtonOptions(
  1118. title: rightText,
  1119. titleColor: colors.danger,
  1120. action: () {
  1121. Navigator.pop(ctx);
  1122. onConfirm();
  1123. },
  1124. ),
  1125. ),
  1126. );
  1127. }
  1128. Widget _buildPageFooter() {
  1129. final l10n = AppLocalizations.of(context);
  1130. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  1131. return Center(
  1132. child: Padding(
  1133. padding: const EdgeInsets.only(bottom: 16),
  1134. child: Row(
  1135. mainAxisSize: MainAxisSize.min,
  1136. children: [
  1137. Icon(
  1138. Icons.rocket_launch_outlined,
  1139. size: 16,
  1140. color: colors.textPlaceholder,
  1141. ),
  1142. const SizedBox(width: 6),
  1143. Text(
  1144. l10n.get('pageFooter'),
  1145. style: TextStyle(
  1146. fontSize: AppFontSizes.caption,
  1147. color: colors.textPlaceholder,
  1148. ),
  1149. ),
  1150. ],
  1151. ),
  1152. ),
  1153. );
  1154. }
  1155. String _today() {
  1156. final n = DateTime.now();
  1157. return '${n.year}-${n.month.toString().padLeft(2, '0')}-${n.day.toString().padLeft(2, '0')}';
  1158. }
  1159. }