99 lines
2.6 KiB
Dart
99 lines
2.6 KiB
Dart
import 'dart:async';
|
|
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
|
import 'package:dio/dio.dart';
|
|
import '../../../core/network/dio_client.dart';
|
|
import '../domain/invoice.dart';
|
|
|
|
class InvoicesNotifier extends AsyncNotifier<List<Invoice>> {
|
|
@override
|
|
FutureOr<List<Invoice>> build() async {
|
|
return _fetchInvoices();
|
|
}
|
|
|
|
Future<List<Invoice>> _fetchInvoices() async {
|
|
try {
|
|
final response = await DioClient().dio.get('/invoices');
|
|
if (response.statusCode == 200) {
|
|
final List<dynamic> data = response.data;
|
|
return data.map((e) => Invoice.fromJson(e)).toList();
|
|
}
|
|
return [];
|
|
} catch (e) {
|
|
print('Error fetching invoices: $e');
|
|
return [];
|
|
}
|
|
}
|
|
|
|
Future<void> refresh() async {
|
|
state = const AsyncValue.loading();
|
|
try {
|
|
final invoices = await _fetchInvoices();
|
|
state = AsyncValue.data(invoices);
|
|
} catch (e, stack) {
|
|
state = AsyncValue.error(e, stack);
|
|
}
|
|
}
|
|
|
|
Future<void> createInvoice(Invoice invoice) async {
|
|
try {
|
|
await DioClient().dio.post('/invoices', data: invoice.toJson());
|
|
await refresh();
|
|
} catch (e) {
|
|
if (e is DioException) {
|
|
throw Exception(
|
|
'Failed to create invoice: ${e.response?.statusCode} - ${e.response?.data}',
|
|
);
|
|
}
|
|
throw Exception('Failed to create invoice: $e');
|
|
}
|
|
}
|
|
|
|
Future<void> finalizeInvoice(int invoiceId) async {
|
|
try {
|
|
await DioClient().dio.put('/invoices/$invoiceId/finalize');
|
|
await refresh();
|
|
} catch (e) {
|
|
throw Exception('Failed to finalize invoice: $e');
|
|
}
|
|
}
|
|
|
|
Future<void> addPayment(int invoiceId, InvoicePayment payment) async {
|
|
try {
|
|
await DioClient().dio.post(
|
|
'/invoices/$invoiceId/payments',
|
|
data: payment.toJson(),
|
|
);
|
|
await refresh();
|
|
} catch (e) {
|
|
if (e is DioException) {
|
|
throw Exception(
|
|
'Failed to add payment: ${e.response?.statusCode} - ${e.response?.data}',
|
|
);
|
|
}
|
|
throw Exception('Failed to add payment: $e');
|
|
}
|
|
}
|
|
|
|
Future<List<InvoicePayment>> fetchPaymentsForInvoice(int invoiceId) async {
|
|
try {
|
|
final response = await DioClient().dio.get(
|
|
'/invoices/$invoiceId/payments',
|
|
);
|
|
if (response.statusCode == 200) {
|
|
final List<dynamic> data = response.data;
|
|
return data.map((e) => InvoicePayment.fromJson(e)).toList();
|
|
}
|
|
return [];
|
|
} catch (e) {
|
|
print('Error fetching payments for invoice $invoiceId: $e');
|
|
return [];
|
|
}
|
|
}
|
|
}
|
|
|
|
final invoicesProvider = AsyncNotifierProvider<InvoicesNotifier, List<Invoice>>(
|
|
() {
|
|
return InvoicesNotifier();
|
|
},
|
|
);
|