expense_edit_page.dart 40 KB

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