expense_edit_page.dart 42 KB

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