| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394 |
- import 'package:flutter_riverpod/flutter_riverpod.dart';
- import 'expense_model.dart';
- import 'expense_api.dart';
- class ExpenseApplyState {
- final ExpenseModel expense;
- final bool isSubmitting;
- const ExpenseApplyState({required this.expense, this.isSubmitting = false});
- ExpenseApplyState copyWith({ExpenseModel? expense, bool? isSubmitting}) {
- return ExpenseApplyState(
- expense: expense ?? this.expense,
- isSubmitting: isSubmitting ?? this.isSubmitting,
- );
- }
- }
- class ExpenseApplyController extends StateNotifier<ExpenseApplyState> {
- final ExpenseApi _api;
- ExpenseApplyController(this._api, {ExpenseModel? initial})
- : super(
- ExpenseApplyState(
- expense:
- initial ??
- ExpenseModel(
- id: '',
- reportNo: '',
- applicantId: '',
- applicantName: '',
- deptId: '',
- deptName: '',
- expenseType: '',
- totalAmount: 0.0,
- purpose: '',
- createTime: DateTime.now(),
- updateTime: DateTime.now(),
- ),
- ),
- );
- void updatePurpose(String purpose) {
- state = state.copyWith(expense: state.expense.copyWith(purpose: purpose));
- }
- void addDetail(ExpenseDetailModel detail) {
- final details = [...state.expense.details, detail];
- state = state.copyWith(expense: state.expense.copyWith(details: details));
- }
- void removeDetail(int index) {
- final details = [...state.expense.details]..removeAt(index);
- state = state.copyWith(expense: state.expense.copyWith(details: details));
- }
- void recalculateAmount() {
- final total = state.expense.details.fold<double>(
- 0,
- (sum, d) => sum + d.totalAmount,
- );
- state = state.copyWith(expense: state.expense.copyWith(totalAmount: total));
- }
- Future<bool> submit() async {
- state = state.copyWith(isSubmitting: true);
- try {
- await _api.submit(state.expense.copyWith(status: 'pending'));
- return true;
- } catch (_) {
- return false;
- } finally {
- state = state.copyWith(isSubmitting: false);
- }
- }
- Future<bool> saveDraft() async {
- state = state.copyWith(isSubmitting: true);
- try {
- await _api.saveDraft(state.expense);
- return true;
- } catch (_) {
- return false;
- } finally {
- state = state.copyWith(isSubmitting: false);
- }
- }
- }
- final expenseApplyProvider = StateNotifierProvider.autoDispose
- .family<ExpenseApplyController, ExpenseApplyState, String?>((ref, editId) {
- final api = ref.watch(expenseApiProvider);
- return ExpenseApplyController(api);
- });
|