expense_edit_page.dart 42 KB

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