| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495 |
- 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,
- remark: '',
- createTime: DateTime.now(),
- updateTime: DateTime.now(),
- ),
- ));
- void updateType(String type) {
- state = state.copyWith(expense: state.expense.copyWith(expenseType: type));
- }
- void updateRemark(String remark) {
- state = state.copyWith(expense: state.expense.copyWith(remark: remark));
- }
- 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);
- });
|