expense_edit_page.dart 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245
  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. 'PAY_ID': expense.paymentMethod,
  301. 'USR': HostAppChannel.usr,
  302. 'REM': expense.remark,
  303. 'CUR_ID': expense.currencyCode,
  304. 'EXC_RTO': expense.excRto,
  305. 'REASON': expense.purpose,
  306. 'VOH_ID': expense.isGenerateVoucher ? 'T' : 'F',
  307. },
  308. 'BodyData1': expense.details.asMap().entries.map((e) {
  309. final d = e.value;
  310. final item = <String, dynamic>{
  311. 'BX_NO': _billNo,
  312. 'BX_DD': _today(),
  313. 'ACC_NO': d.acctSubjectId,
  314. 'AMT': d.totalAmount,
  315. 'AMTN': d.amount,
  316. 'AMTN_SH': d.approvedAmount,
  317. 'REM': d.remark,
  318. 'CUST': d.customerVendorId,
  319. 'IDX_NO': d.expenseCategory,
  320. 'OBJ_NO': d.projectId.isNotEmpty ? d.projectId : '',
  321. 'TAX': d.taxAmount,
  322. 'TAX_RTO': d.taxRate,
  323. 'DEP': d.costDeptId,
  324. 'AE_NO': d.aeNo,
  325. 'AE_DD': d.aeDd,
  326. 'BNK_NO': d.bankName,
  327. 'BNK_ID': d.bankAccount,
  328. 'ACCNAME': d.bankAccountName,
  329. 'SQ_MAN': d.sqMan.isNotEmpty ? d.sqMan : HostAppChannel.usr,
  330. 'EST_ITM': d.aeNo.isNotEmpty ? d.sortOrder : 0,
  331. };
  332. if (d.preItm != null) {
  333. item['PRE_ITM'] = d.preItm;
  334. }
  335. return item;
  336. }).toList(),
  337. };
  338. }
  339. // ═══ Build ═══
  340. @override
  341. Widget build(BuildContext context) {
  342. final r = ResponsiveHelper.of(context);
  343. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  344. final l10n = AppLocalizations.of(context);
  345. final bottomInset = MediaQuery.of(context).padding.bottom;
  346. if (_loadingError != null) {
  347. return Center(
  348. child: Column(
  349. mainAxisSize: MainAxisSize.min,
  350. children: [
  351. Icon(Icons.error_outline, size: 48, color: colors.danger),
  352. const SizedBox(height: 16),
  353. Padding(
  354. padding: const EdgeInsets.symmetric(horizontal: 32),
  355. child: Text(
  356. _loadingError!,
  357. textAlign: TextAlign.center,
  358. style: TextStyle(
  359. fontSize: AppFontSizes.body,
  360. color: colors.textSecondary,
  361. ),
  362. ),
  363. ),
  364. const SizedBox(height: 16),
  365. TDButton(
  366. text: l10n.get('retry'),
  367. size: TDButtonSize.medium,
  368. onTap: () {
  369. setState(() {
  370. _loadingError = null;
  371. _firstBuild = true;
  372. _refDataLoading = true;
  373. });
  374. _loadData();
  375. },
  376. ),
  377. ],
  378. ),
  379. );
  380. }
  381. if (_firstBuild || _expense == null) {
  382. return const SkeletonFormPage(showImportLink: false);
  383. }
  384. Future.microtask(
  385. () => ref.read(pageBackProvider.notifier).state = () => _doPop(l10n),
  386. );
  387. Widget pageContent = PopScope(
  388. canPop: false,
  389. onPopInvokedWithResult: (didPop, _) {
  390. if (didPop) return;
  391. _doPop(l10n);
  392. },
  393. child: Column(
  394. children: [
  395. Expanded(
  396. child: Align(
  397. alignment: Alignment.topCenter,
  398. child: ConstrainedBox(
  399. constraints: BoxConstraints(maxWidth: r.formMaxWidth),
  400. child: SingleChildScrollView(
  401. controller: _scrollCtrl,
  402. padding: const EdgeInsets.all(16),
  403. child: Column(
  404. crossAxisAlignment: CrossAxisAlignment.start,
  405. children: [
  406. _buildBasicInfoSection(l10n, colors),
  407. const SizedBox(height: 16),
  408. Container(
  409. key: _detailsSectionKey,
  410. child: _buildDetailSection(l10n, colors),
  411. ),
  412. const SizedBox(height: 24),
  413. _buildPageFooter(),
  414. ],
  415. ),
  416. ),
  417. ),
  418. ),
  419. ),
  420. ColoredBox(
  421. color: colors.bgCard,
  422. child: Column(
  423. mainAxisSize: MainAxisSize.min,
  424. children: [
  425. _buildBottomButtons(l10n),
  426. if (bottomInset > 0) SizedBox(height: bottomInset),
  427. ],
  428. ),
  429. ),
  430. ],
  431. ),
  432. );
  433. return pageContent;
  434. }
  435. Widget _buildBasicInfoSection(
  436. AppLocalizations l10n,
  437. AppColorsExtension colors,
  438. ) {
  439. final expense = _expense!;
  440. return FormSection(
  441. title: l10n.get('basicInfo'),
  442. leadingIcon: Icons.info_outline,
  443. children: [
  444. FormFieldRow(
  445. label: l10n.get('expenseNo'),
  446. value: _billNo,
  447. readOnly: true,
  448. showArrow: false,
  449. ),
  450. const SizedBox(height: 16),
  451. FormFieldRow(
  452. label: l10n.get('date'),
  453. value: _expenseDate,
  454. readOnly: true,
  455. showArrow: false,
  456. ),
  457. const SizedBox(height: 16),
  458. FormFieldRow(
  459. label: l10n.get('expensePersonnel'),
  460. value: _selEmployee != null
  461. ? '${_selEmployee!.salNo}/${_selEmployee!.name}'
  462. : '',
  463. hint: l10n.get('pleaseSelect'),
  464. onTap: _showEmployeePicker,
  465. ),
  466. const SizedBox(height: 16),
  467. FormFieldRow(
  468. label: l10n.get('expenseDept'),
  469. value: _selectedDeptName.isNotEmpty
  470. ? '$_selectedDeptId/$_selectedDeptName'
  471. : null,
  472. hint: l10n.get('pleaseSelect'),
  473. onTap: _refDataLoading ? null : () => _showDeptPicker(),
  474. ),
  475. const SizedBox(height: 16),
  476. _label(l10n.get('expenseReason'), required: true),
  477. const SizedBox(height: 8),
  478. TDTextarea(
  479. controller: _purposeController,
  480. focusNode: _purposeFocus,
  481. hintText: l10n.get('enterExpenseReason'),
  482. maxLines: 4,
  483. minLines: 1,
  484. maxLength: 500,
  485. indicator: true,
  486. padding: EdgeInsets.zero,
  487. bordered: true,
  488. backgroundColor: colors.bgPage,
  489. onChanged: (_) => _updatePurpose(_purposeController.text),
  490. ),
  491. const SizedBox(height: 16),
  492. FormFieldRow(
  493. label: l10n.get('paymentMethod'),
  494. value: expense.paymentMethod,
  495. hint: l10n.get('pleaseEnter'),
  496. onTap: () => _showTextInput(
  497. l10n.get('paymentMethod'),
  498. (v) => _updatePaymentMethod(v),
  499. initialText: expense.paymentMethod,
  500. ),
  501. onClear: () => _updatePaymentMethod(''),
  502. ),
  503. const SizedBox(height: 16),
  504. FormFieldRow(
  505. label: l10n.get('currency'),
  506. value: expense.currencyCode.isNotEmpty
  507. ? _currencyLabel(expense.currencyCode)
  508. : null,
  509. hint: l10n.get('selectCurrency'),
  510. onTap: () => _showCurrencyPicker(expense.currencyCode),
  511. onClear: () => _updateCurrencyCode(''),
  512. ),
  513. const SizedBox(height: 16),
  514. Row(
  515. mainAxisAlignment: MainAxisAlignment.spaceBetween,
  516. children: [
  517. Text(
  518. l10n.get('generateVoucher'),
  519. style: TextStyle(
  520. fontSize: AppFontSizes.subtitle,
  521. color: colors.textSecondary,
  522. ),
  523. ),
  524. TDSwitch(
  525. isOn: expense.isGenerateVoucher,
  526. onChanged: (v) {
  527. _setGenerateVoucher(v);
  528. return v;
  529. },
  530. ),
  531. ],
  532. ),
  533. const SizedBox(height: 16),
  534. _label(l10n.get('remark')),
  535. const SizedBox(height: 8),
  536. TDTextarea(
  537. controller: _remarkController,
  538. focusNode: _remarkFocus,
  539. hintText: l10n.get('enterRemark'),
  540. maxLines: 3,
  541. minLines: 1,
  542. maxLength: 500,
  543. indicator: true,
  544. padding: EdgeInsets.zero,
  545. bordered: true,
  546. backgroundColor: colors.bgPage,
  547. onChanged: (_) => _updateRemark(_remarkController.text),
  548. ),
  549. ],
  550. );
  551. }
  552. Widget _buildDetailSection(AppLocalizations l10n, AppColorsExtension colors) {
  553. final expense = _expense!;
  554. final totalAmount = expense.details.fold<double>(
  555. 0,
  556. (sum, d) => sum + d.totalAmount,
  557. );
  558. final totalApproved = expense.details.fold<double>(
  559. 0,
  560. (sum, d) => sum + d.approvedAmount,
  561. );
  562. return FormSection(
  563. title: l10n.get('expenseDetails'),
  564. leadingIcon: Icons.receipt_long_outlined,
  565. showAction: true,
  566. actionText: l10n.get('add'),
  567. onActionTap: () => _showAddDetailDialog(),
  568. children: [
  569. if (expense.details.isEmpty)
  570. Padding(
  571. padding: const EdgeInsets.symmetric(vertical: 8),
  572. child: Text(
  573. l10n.get('noDetailHint'),
  574. style: TextStyle(
  575. fontSize: AppFontSizes.subtitle,
  576. color: colors.textPlaceholder,
  577. ),
  578. ),
  579. )
  580. else
  581. ...expense.details.asMap().entries.map((entry) {
  582. final d = entry.value;
  583. return GestureDetector(
  584. onTap: () => _showAddDetailDialog(editIndex: entry.key),
  585. child: Container(
  586. margin: const EdgeInsets.symmetric(vertical: 6),
  587. padding: const EdgeInsets.all(12),
  588. decoration: BoxDecoration(
  589. color: colors.bgPage,
  590. borderRadius: BorderRadius.circular(8),
  591. ),
  592. child: Row(
  593. children: [
  594. Expanded(
  595. child: Column(
  596. crossAxisAlignment: CrossAxisAlignment.start,
  597. children: [
  598. Row(
  599. children: [
  600. Expanded(
  601. child: Text(
  602. d.categoryName.isNotEmpty
  603. ? '${d.expenseCategory}/${d.categoryName}'
  604. : d.expenseCategory,
  605. style: TextStyle(
  606. fontSize: AppFontSizes.body,
  607. fontWeight: FontWeight.w500,
  608. color: colors.textPrimary,
  609. ),
  610. ),
  611. ),
  612. Column(
  613. crossAxisAlignment: CrossAxisAlignment.end,
  614. children: [
  615. Text(
  616. formatAmount(d.totalAmount),
  617. style: TextStyle(
  618. fontSize: AppFontSizes.body,
  619. fontWeight: FontWeight.w600,
  620. color: colors.amountPrimary,
  621. ),
  622. ),
  623. if (d.approvedAmount > 0)
  624. Text(
  625. formatAmount(d.approvedAmount),
  626. style: TextStyle(
  627. fontSize: AppFontSizes.body,
  628. fontWeight: FontWeight.w600,
  629. color: colors.success,
  630. ),
  631. ),
  632. ],
  633. ),
  634. ],
  635. ),
  636. const SizedBox(height: 2),
  637. Text(
  638. '${l10n.get('amountExcludingTax')}: ${formatAmount(d.amount)}',
  639. style: TextStyle(
  640. fontSize: AppFontSizes.caption,
  641. color: colors.textSecondary,
  642. ),
  643. ),
  644. if (d.taxAmount > 0)
  645. Text(
  646. '${l10n.get('taxAmount')}: ${formatAmount(d.taxAmount)}',
  647. style: TextStyle(
  648. fontSize: AppFontSizes.caption,
  649. color: colors.textSecondary,
  650. ),
  651. ),
  652. if (d.taxRate > 0)
  653. Text(
  654. '${l10n.get('taxRate')}: ${d.taxRate.toStringAsFixed(0)}%',
  655. style: TextStyle(
  656. fontSize: AppFontSizes.caption,
  657. color: colors.textSecondary,
  658. ),
  659. ),
  660. if (d.acctSubjectId.isNotEmpty)
  661. Text(
  662. '${l10n.get('acctSubject')}: ${d.acctSubjectId}${d.acctSubjectName.isNotEmpty ? '/${d.acctSubjectName}' : ''}',
  663. maxLines: 1,
  664. overflow: TextOverflow.ellipsis,
  665. style: TextStyle(
  666. fontSize: AppFontSizes.caption,
  667. color: colors.textSecondary,
  668. ),
  669. ),
  670. if (d.aeNo.isNotEmpty)
  671. Text(
  672. '${l10n.get('expenseApplyNo')}: ${d.aeNo}',
  673. maxLines: 1,
  674. overflow: TextOverflow.ellipsis,
  675. style: TextStyle(
  676. fontSize: AppFontSizes.caption,
  677. color: colors.textSecondary,
  678. ),
  679. ),
  680. if (d.aeDd.isNotEmpty)
  681. Text(
  682. '${l10n.get('applyDate')}: ${d.aeDd.length >= 10 ? d.aeDd.substring(0, 10) : d.aeDd}',
  683. style: TextStyle(
  684. fontSize: AppFontSizes.caption,
  685. color: colors.textSecondary,
  686. ),
  687. ),
  688. if (d.projectId.isNotEmpty)
  689. Text(
  690. '${l10n.get('project')}: ${d.projectId}${d.projectName.isNotEmpty ? '/${d.projectName}' : ''}',
  691. maxLines: 1,
  692. overflow: TextOverflow.ellipsis,
  693. style: TextStyle(
  694. fontSize: AppFontSizes.caption,
  695. color: colors.textSecondary,
  696. ),
  697. ),
  698. if (d.costDeptId.isNotEmpty)
  699. Text(
  700. '${l10n.get('costDept')}: ${d.costDeptId}${d.costDeptName.isNotEmpty ? '/${d.costDeptName}' : ''}',
  701. maxLines: 1,
  702. overflow: TextOverflow.ellipsis,
  703. style: TextStyle(
  704. fontSize: AppFontSizes.caption,
  705. color: colors.textSecondary,
  706. ),
  707. ),
  708. if (d.customerVendorId.isNotEmpty)
  709. Text(
  710. '${l10n.get('customerVendor')}: ${d.customerVendorId}${d.customerVendorName.isNotEmpty ? '/${d.customerVendorName}' : ''}',
  711. maxLines: 1,
  712. overflow: TextOverflow.ellipsis,
  713. style: TextStyle(
  714. fontSize: AppFontSizes.caption,
  715. color: colors.textSecondary,
  716. ),
  717. ),
  718. if (d.sqMan.isNotEmpty)
  719. Text(
  720. '${l10n.get('applicant')}: ${d.sqMan}${d.sqManName.isNotEmpty ? '/${d.sqManName}' : ''}',
  721. style: TextStyle(
  722. fontSize: AppFontSizes.caption,
  723. color: colors.textSecondary,
  724. ),
  725. ),
  726. if (d.bankAccountName.isNotEmpty)
  727. Text(
  728. '${l10n.get('bankAccountName')}: ${d.bankAccountName}',
  729. maxLines: 1,
  730. overflow: TextOverflow.ellipsis,
  731. style: TextStyle(
  732. fontSize: AppFontSizes.caption,
  733. color: colors.textSecondary,
  734. ),
  735. ),
  736. if (d.bankName.isNotEmpty)
  737. Text(
  738. '${l10n.get('bankName')}: ${d.bankName}',
  739. maxLines: 1,
  740. overflow: TextOverflow.ellipsis,
  741. style: TextStyle(
  742. fontSize: AppFontSizes.caption,
  743. color: colors.textSecondary,
  744. ),
  745. ),
  746. if (d.bankAccount.isNotEmpty)
  747. Text(
  748. '${l10n.get('bankAccount')}: ${d.bankAccount}',
  749. maxLines: 1,
  750. overflow: TextOverflow.ellipsis,
  751. style: TextStyle(
  752. fontSize: AppFontSizes.caption,
  753. color: colors.textSecondary,
  754. ),
  755. ),
  756. if (d.remark.isNotEmpty)
  757. Text(
  758. '${l10n.get('remark')}: ${d.remark}',
  759. maxLines: 2,
  760. overflow: TextOverflow.ellipsis,
  761. style: TextStyle(
  762. fontSize: AppFontSizes.caption,
  763. color: colors.textSecondary,
  764. ),
  765. ),
  766. ],
  767. ),
  768. ),
  769. const SizedBox(width: 8),
  770. GestureDetector(
  771. onTap: () => _removeDetail(entry.key),
  772. child: Icon(
  773. Icons.close,
  774. size: 18,
  775. color: colors.textSecondary,
  776. ),
  777. ),
  778. ],
  779. ),
  780. ),
  781. );
  782. }),
  783. const SizedBox(height: 8),
  784. Row(
  785. mainAxisAlignment: MainAxisAlignment.spaceBetween,
  786. children: [
  787. Text(
  788. l10n.get('totalExpense'),
  789. style: TextStyle(
  790. fontSize: AppFontSizes.body,
  791. fontWeight: FontWeight.w600,
  792. color: colors.textPrimary,
  793. ),
  794. ),
  795. Text(
  796. formatAmount(totalAmount),
  797. style: TextStyle(
  798. fontSize: AppFontSizes.subtitle,
  799. fontWeight: FontWeight.w700,
  800. color: colors.amountPrimary,
  801. ),
  802. ),
  803. ],
  804. ),
  805. const SizedBox(height: 4),
  806. Row(
  807. mainAxisAlignment: MainAxisAlignment.spaceBetween,
  808. children: [
  809. Text(
  810. l10n.get('approvedTotal'),
  811. style: TextStyle(
  812. fontSize: AppFontSizes.body,
  813. fontWeight: FontWeight.w600,
  814. color: colors.textPrimary,
  815. ),
  816. ),
  817. Text(
  818. formatAmount(totalApproved),
  819. style: TextStyle(
  820. fontSize: AppFontSizes.subtitle,
  821. fontWeight: FontWeight.w700,
  822. color: totalApproved > 0 ? colors.success : colors.textPrimary,
  823. ),
  824. ),
  825. ],
  826. ),
  827. ],
  828. );
  829. }
  830. Future<void> _showAddDetailDialog({int? editIndex}) async {
  831. if (_addingDetail) return;
  832. _addingDetail = true;
  833. try {
  834. final l10n = AppLocalizations.of(context);
  835. final expense = _expense!;
  836. ExpenseDetailInputData? initialData;
  837. if (editIndex != null) {
  838. final d = expense.details[editIndex];
  839. initialData = ExpenseDetailInputData(
  840. category: d.expenseCategory,
  841. categoryName: d.categoryName,
  842. acctSubjectId: d.acctSubjectId,
  843. acctSubjectName: d.acctSubjectName,
  844. purpose: d.purpose,
  845. amount: d.totalAmount,
  846. taxRate: d.taxRate,
  847. projectId: d.projectId,
  848. projectName: d.projectName,
  849. costDeptId: d.costDeptId,
  850. costDeptName: d.costDeptName,
  851. customerVendorId: d.customerVendorId,
  852. customerVendorName: d.customerVendorName,
  853. approvedAmount: d.approvedAmount,
  854. bankName: d.bankName,
  855. bankAccountName: d.bankAccountName,
  856. bankAccount: d.bankAccount,
  857. remark: d.remark,
  858. attachmentPaths: d.attachments,
  859. sqMan: d.sqMan,
  860. sqManName: d.sqManName,
  861. aeNo: d.aeNo,
  862. aeDd: d.aeDd,
  863. );
  864. }
  865. FocusManager.instance.primaryFocus?.unfocus();
  866. final result = await ExpenseDetailDialog.show(
  867. context,
  868. api: ref.read(expenseApiProvider),
  869. l10n: l10n,
  870. initialData: initialData,
  871. checkAttachHealth: () =>
  872. ref.read(expenseApiProvider).checkAttachHealth(),
  873. showAttachments: false,
  874. canEditApprovedAmount: _canEditApprovedAmount,
  875. acctTree: _acctTree,
  876. defaultSqMan: _currentUserForDialog?.salNo,
  877. defaultSqManName: _currentUserForDialog?.name,
  878. );
  879. if (result != null && mounted) {
  880. final now = DateTime.now();
  881. final detail = ExpenseDetailModel(
  882. id: editIndex != null
  883. ? expense.details[editIndex].id
  884. : now.millisecondsSinceEpoch.toString(),
  885. expenseId: '',
  886. expenseCategory: result.category,
  887. categoryName: result.categoryName,
  888. purpose: result.purpose,
  889. amount: result.taxRate > 0
  890. ? result.amount / (1 + result.taxRate / 100)
  891. : result.amount,
  892. taxRate: result.taxRate,
  893. taxAmount: result.taxRate > 0
  894. ? result.amount - result.amount / (1 + result.taxRate / 100)
  895. : 0,
  896. totalAmount: result.amount,
  897. projectId: result.projectId,
  898. projectName: result.projectName,
  899. costDeptId: result.costDeptId,
  900. costDeptName: result.costDeptName,
  901. acctSubjectId: result.acctSubjectId,
  902. acctSubjectName: result.acctSubjectName,
  903. customerVendorId: result.customerVendorId,
  904. customerVendorName: result.customerVendorName,
  905. approvedAmount: result.approvedAmount,
  906. bankName: result.bankName,
  907. bankAccountName: result.bankAccountName,
  908. bankAccount: result.bankAccount,
  909. sqMan: result.sqMan,
  910. sqManName: result.sqManName,
  911. aeNo: result.aeNo,
  912. aeDd: result.aeDd,
  913. remark: result.remark,
  914. sortOrder: editIndex != null
  915. ? expense.details[editIndex].sortOrder
  916. : 1,
  917. preItm: editIndex != null ? expense.details[editIndex].preItm : null,
  918. attachments: result.attachmentPaths,
  919. createTime: now,
  920. updateTime: now,
  921. );
  922. if (editIndex != null) {
  923. _updateDetail(editIndex, detail);
  924. } else {
  925. _addDetail(detail);
  926. }
  927. }
  928. } finally {
  929. _addingDetail = false;
  930. }
  931. }
  932. void _showCurrencyPicker(String cur) {
  933. if (_currencies.isEmpty) {
  934. TDToast.showText(
  935. AppLocalizations.of(context).get('noData'),
  936. context: context,
  937. );
  938. return;
  939. }
  940. final l10n = AppLocalizations.of(context);
  941. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  942. final codes = _currencies.map((c) => c.curId).toList();
  943. final labels = _currencies.map((c) => '${c.curId}/${c.name}').toList();
  944. FocusManager.instance.primaryFocus?.unfocus();
  945. TDPicker.showMultiPicker(
  946. context,
  947. title: l10n.get('selectCurrency'),
  948. backgroundColor: colors.bgCard,
  949. data: [labels],
  950. onConfirm: (s) {
  951. if (s.isNotEmpty && s[0] is int) {
  952. final i = s[0] as int;
  953. if (i >= 0 && i < codes.length) {
  954. Navigator.of(context).pop();
  955. _updateCurrencyCode(codes[i], _currencies[i].excRto);
  956. }
  957. }
  958. },
  959. );
  960. }
  961. void _showTextInput(
  962. String title,
  963. Function(String) onConfirm, {
  964. String initialText = '',
  965. }) {
  966. FocusScope.of(context).unfocus();
  967. FocusManager.instance.primaryFocus?.unfocus();
  968. final l10n = AppLocalizations.of(context);
  969. final c = TextEditingController(text: initialText);
  970. showGeneralDialog(
  971. context: context,
  972. pageBuilder: (ctx, animation, secondaryAnimation) => TDInputDialog(
  973. textEditingController: c,
  974. title: title,
  975. hintText: l10n.get('pleaseEnter'),
  976. leftBtn: TDDialogButtonOptions(
  977. title: l10n.get('cancel'),
  978. action: () => Navigator.pop(ctx),
  979. ),
  980. rightBtn: TDDialogButtonOptions(
  981. title: l10n.get('confirm'),
  982. action: () {
  983. onConfirm(c.text);
  984. Navigator.pop(ctx);
  985. },
  986. ),
  987. ),
  988. );
  989. }
  990. Widget _label(String t, {bool required = false}) {
  991. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  992. return Text.rich(
  993. TextSpan(
  994. children: [
  995. TextSpan(
  996. text: t,
  997. style: TextStyle(
  998. fontSize: AppFontSizes.subtitle,
  999. color: colors.textSecondary,
  1000. ),
  1001. ),
  1002. if (required)
  1003. TextSpan(
  1004. text: ' *',
  1005. style: TextStyle(
  1006. fontSize: AppFontSizes.subtitle,
  1007. color: colors.danger,
  1008. ),
  1009. ),
  1010. ],
  1011. ),
  1012. );
  1013. }
  1014. Widget _buildBottomButtons(AppLocalizations l10n) {
  1015. return ActionBar(
  1016. showLeft: false,
  1017. showCenter: false,
  1018. rightLabel: l10n.get('submit'),
  1019. onRightTap: () async {
  1020. if (_isSubmitting) return;
  1021. final err = _validate(l10n);
  1022. if (err.isNotEmpty) {
  1023. TDToast.showText(err.first, context: context);
  1024. return;
  1025. }
  1026. FocusScope.of(context).unfocus();
  1027. _isSubmitting = true;
  1028. LoadingDialog.show(context, text: l10n.get('submitting'));
  1029. try {
  1030. final data = _buildSubmitData();
  1031. final api = ref.read(expenseApiProvider);
  1032. final billNo = await api.submit(data);
  1033. if (!mounted) return;
  1034. LoadingDialog.hide(context);
  1035. if (billNo != null) {
  1036. try {
  1037. final config = await api.getBillAuditConfig('BX');
  1038. if (!mounted) return;
  1039. final hasFlow = config['hasAuditFlow'] == true;
  1040. final autoSubmit = config['autoSubmit'] == true;
  1041. if (hasFlow && !autoSubmit) {
  1042. final dd = data['HeadData']['BX_DD']?.toString() ?? '';
  1043. await AuditFlowHelper.handle(
  1044. context: context,
  1045. l10n: l10n,
  1046. getConfig: () async => config,
  1047. onShSubmit: () => api.shSubmit(bilNo: billNo, bilDd: dd),
  1048. );
  1049. }
  1050. } catch (_) {}
  1051. }
  1052. if (mounted) {
  1053. TDToast.showSuccess(l10n.get('billModified'), context: context);
  1054. GoRouter.of(context).go('/expense/list');
  1055. }
  1056. } catch (e) {
  1057. if (mounted) LoadingDialog.hide(context);
  1058. } finally {
  1059. _isSubmitting = false;
  1060. }
  1061. },
  1062. );
  1063. }
  1064. List<String> _validate(AppLocalizations l10n) {
  1065. final e = <String>[];
  1066. if (_purposeController.text.trim().isEmpty) {
  1067. e.add(l10n.get('enterExpenseReason'));
  1068. }
  1069. if (_expense!.details.isEmpty) {
  1070. e.add(l10n.get('addAtLeastOneDetail'));
  1071. }
  1072. return e;
  1073. }
  1074. bool _hasUnsaved() {
  1075. if (_expense == null || _originalExpense == null) return false;
  1076. final e = _expense!;
  1077. final o = _originalExpense!;
  1078. if (e.purpose != o.purpose) return true;
  1079. if (e.remark != o.remark) return true;
  1080. if (e.paymentMethod != o.paymentMethod) return true;
  1081. if (e.currencyCode != o.currencyCode) return true;
  1082. if (e.details.length != o.details.length) return true;
  1083. for (var i = 0; i < e.details.length; i++) {
  1084. if (i >= o.details.length) return true;
  1085. final d = e.details[i];
  1086. final od = o.details[i];
  1087. if (d.expenseCategory != od.expenseCategory ||
  1088. d.acctSubjectId != od.acctSubjectId ||
  1089. d.amount != od.amount ||
  1090. d.taxRate != od.taxRate ||
  1091. d.totalAmount != od.totalAmount ||
  1092. d.approvedAmount != od.approvedAmount ||
  1093. d.projectId != od.projectId ||
  1094. d.costDeptId != od.costDeptId ||
  1095. d.customerVendorId != od.customerVendorId ||
  1096. d.remark != od.remark ||
  1097. d.bankName != od.bankName ||
  1098. d.bankAccount != od.bankAccount ||
  1099. d.bankAccountName != od.bankAccountName ||
  1100. d.sqMan != od.sqMan ||
  1101. d.aeNo != od.aeNo ||
  1102. d.aeDd != od.aeDd) {
  1103. return true;
  1104. }
  1105. }
  1106. return false;
  1107. }
  1108. void _doPop(AppLocalizations l10n) {
  1109. if (_hasUnsaved()) {
  1110. _showConfirmDialog(
  1111. l10n.get('confirmExit'),
  1112. l10n.get('unsavedContentWarning'),
  1113. l10n.get('continueEditing'),
  1114. l10n.get('discardAndExit'),
  1115. () {
  1116. if (!mounted) return;
  1117. _forcePop();
  1118. },
  1119. );
  1120. } else {
  1121. _forcePop();
  1122. }
  1123. }
  1124. void _forcePop() {
  1125. FocusManager.instance.primaryFocus?.unfocus();
  1126. final router = GoRouter.of(context);
  1127. if (router.canPop()) {
  1128. router.pop();
  1129. } else {
  1130. SystemNavigator.pop();
  1131. }
  1132. }
  1133. void _showConfirmDialog(
  1134. String title,
  1135. String content,
  1136. String leftText,
  1137. String rightText,
  1138. VoidCallback onConfirm,
  1139. ) {
  1140. FocusScope.of(context).unfocus();
  1141. FocusManager.instance.primaryFocus?.unfocus();
  1142. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  1143. showDialog(
  1144. context: context,
  1145. useRootNavigator: true,
  1146. builder: (ctx) => TDAlertDialog(
  1147. title: title,
  1148. content: content,
  1149. buttonStyle: TDDialogButtonStyle.text,
  1150. leftBtn: TDDialogButtonOptions(
  1151. title: leftText,
  1152. titleColor: colors.primary,
  1153. action: () => Navigator.pop(ctx),
  1154. ),
  1155. rightBtn: TDDialogButtonOptions(
  1156. title: rightText,
  1157. titleColor: colors.danger,
  1158. action: () {
  1159. Navigator.pop(ctx);
  1160. onConfirm();
  1161. },
  1162. ),
  1163. ),
  1164. );
  1165. }
  1166. Widget _buildPageFooter() {
  1167. final l10n = AppLocalizations.of(context);
  1168. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  1169. return Center(
  1170. child: Padding(
  1171. padding: const EdgeInsets.only(bottom: 16),
  1172. child: Row(
  1173. mainAxisSize: MainAxisSize.min,
  1174. children: [
  1175. Icon(
  1176. Icons.rocket_launch_outlined,
  1177. size: 16,
  1178. color: colors.textPlaceholder,
  1179. ),
  1180. const SizedBox(width: 6),
  1181. Text(
  1182. l10n.get('pageFooter'),
  1183. style: TextStyle(
  1184. fontSize: AppFontSizes.caption,
  1185. color: colors.textPlaceholder,
  1186. ),
  1187. ),
  1188. ],
  1189. ),
  1190. ),
  1191. );
  1192. }
  1193. String _today() {
  1194. final n = DateTime.now();
  1195. return '${n.year}-${n.month.toString().padLeft(2, '0')}-${n.day.toString().padLeft(2, '0')}';
  1196. }
  1197. }