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> { @override FutureOr> build() async { return _fetchInvoices(); } Future> _fetchInvoices() async { try { final response = await DioClient().dio.get('/invoices'); if (response.statusCode == 200) { final List data = response.data; return data.map((e) => Invoice.fromJson(e)).toList(); } return []; } catch (e) { print('Error fetching invoices: $e'); return []; } } Future refresh() async { state = const AsyncValue.loading(); try { final invoices = await _fetchInvoices(); state = AsyncValue.data(invoices); } catch (e, stack) { state = AsyncValue.error(e, stack); } } Future 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 finalizeInvoice(int invoiceId) async { try { await DioClient().dio.put('/invoices/$invoiceId/finalize'); await refresh(); } catch (e) { throw Exception('Failed to finalize invoice: $e'); } } Future 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> fetchPaymentsForInvoice(int invoiceId) async { try { final response = await DioClient().dio.get('/invoices/$invoiceId/payments'); if (response.statusCode == 200) { final List 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>(() { return InvoicesNotifier(); });