expense_edit_page.dart 40 KB

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