expense_edit_page.dart 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240
  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. final dd = data['HeadData']['BX_DD']?.toString() ?? '';
  1039. await AuditFlowHelper.handle(
  1040. context: context,
  1041. l10n: l10n,
  1042. getConfig: () => api.getBillAuditConfig('BX'),
  1043. onShSubmit: () => api.shSubmit(bilNo: billNo, bilDd: dd),
  1044. skipOnAutoSubmit: true,
  1045. );
  1046. }
  1047. if (mounted) {
  1048. TDToast.showSuccess(l10n.get('billModified'), context: context);
  1049. GoRouter.of(context).go('/expense/list');
  1050. }
  1051. } catch (e) {
  1052. if (mounted) LoadingDialog.hide(context);
  1053. } finally {
  1054. _isSubmitting = false;
  1055. }
  1056. },
  1057. );
  1058. }
  1059. List<String> _validate(AppLocalizations l10n) {
  1060. final e = <String>[];
  1061. if (_purposeController.text.trim().isEmpty) {
  1062. e.add(l10n.get('enterExpenseReason'));
  1063. }
  1064. if (_expense!.details.isEmpty) {
  1065. e.add(l10n.get('addAtLeastOneDetail'));
  1066. }
  1067. return e;
  1068. }
  1069. bool _hasUnsaved() {
  1070. if (_expense == null || _originalExpense == null) return false;
  1071. final e = _expense!;
  1072. final o = _originalExpense!;
  1073. if (e.purpose != o.purpose) return true;
  1074. if (e.remark != o.remark) return true;
  1075. if (e.paymentMethod != o.paymentMethod) return true;
  1076. if (e.currencyCode != o.currencyCode) return true;
  1077. if (e.details.length != o.details.length) return true;
  1078. for (var i = 0; i < e.details.length; i++) {
  1079. if (i >= o.details.length) return true;
  1080. final d = e.details[i];
  1081. final od = o.details[i];
  1082. if (d.expenseCategory != od.expenseCategory ||
  1083. d.acctSubjectId != od.acctSubjectId ||
  1084. d.amount != od.amount ||
  1085. d.taxRate != od.taxRate ||
  1086. d.totalAmount != od.totalAmount ||
  1087. d.approvedAmount != od.approvedAmount ||
  1088. d.projectId != od.projectId ||
  1089. d.costDeptId != od.costDeptId ||
  1090. d.customerVendorId != od.customerVendorId ||
  1091. d.remark != od.remark ||
  1092. d.bankName != od.bankName ||
  1093. d.bankAccount != od.bankAccount ||
  1094. d.bankAccountName != od.bankAccountName ||
  1095. d.sqMan != od.sqMan ||
  1096. d.aeNo != od.aeNo ||
  1097. d.aeDd != od.aeDd) {
  1098. return true;
  1099. }
  1100. }
  1101. return false;
  1102. }
  1103. void _doPop(AppLocalizations l10n) {
  1104. if (_hasUnsaved()) {
  1105. _showConfirmDialog(
  1106. l10n.get('confirmExit'),
  1107. l10n.get('unsavedContentWarning'),
  1108. l10n.get('continueEditing'),
  1109. l10n.get('discardAndExit'),
  1110. () {
  1111. if (!mounted) return;
  1112. _forcePop();
  1113. },
  1114. );
  1115. } else {
  1116. _forcePop();
  1117. }
  1118. }
  1119. void _forcePop() {
  1120. FocusManager.instance.primaryFocus?.unfocus();
  1121. final router = GoRouter.of(context);
  1122. if (router.canPop()) {
  1123. router.pop();
  1124. } else {
  1125. SystemNavigator.pop();
  1126. }
  1127. }
  1128. void _showConfirmDialog(
  1129. String title,
  1130. String content,
  1131. String leftText,
  1132. String rightText,
  1133. VoidCallback onConfirm,
  1134. ) {
  1135. FocusScope.of(context).unfocus();
  1136. FocusManager.instance.primaryFocus?.unfocus();
  1137. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  1138. showDialog(
  1139. context: context,
  1140. useRootNavigator: true,
  1141. builder: (ctx) => TDAlertDialog(
  1142. title: title,
  1143. content: content,
  1144. buttonStyle: TDDialogButtonStyle.text,
  1145. leftBtn: TDDialogButtonOptions(
  1146. title: leftText,
  1147. titleColor: colors.primary,
  1148. action: () => Navigator.pop(ctx),
  1149. ),
  1150. rightBtn: TDDialogButtonOptions(
  1151. title: rightText,
  1152. titleColor: colors.danger,
  1153. action: () {
  1154. Navigator.pop(ctx);
  1155. onConfirm();
  1156. },
  1157. ),
  1158. ),
  1159. );
  1160. }
  1161. Widget _buildPageFooter() {
  1162. final l10n = AppLocalizations.of(context);
  1163. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  1164. return Center(
  1165. child: Padding(
  1166. padding: const EdgeInsets.only(bottom: 16),
  1167. child: Row(
  1168. mainAxisSize: MainAxisSize.min,
  1169. children: [
  1170. Icon(
  1171. Icons.rocket_launch_outlined,
  1172. size: 16,
  1173. color: colors.textPlaceholder,
  1174. ),
  1175. const SizedBox(width: 6),
  1176. Text(
  1177. l10n.get('pageFooter'),
  1178. style: TextStyle(
  1179. fontSize: AppFontSizes.caption,
  1180. color: colors.textPlaceholder,
  1181. ),
  1182. ),
  1183. ],
  1184. ),
  1185. ),
  1186. );
  1187. }
  1188. String _today() {
  1189. final n = DateTime.now();
  1190. return '${n.year}-${n.month.toString().padLeft(2, '0')}-${n.day.toString().padLeft(2, '0')}';
  1191. }
  1192. }