Files
kmobile/lib/api/services/beneficiary_service.dart

132 lines
3.2 KiB
Dart

import 'package:dio/dio.dart';
import 'package:kmobile/data/models/ifsc.dart';
import 'package:kmobile/data/models/beneficiary.dart';
class BeneficiaryService {
final Dio _dio;
BeneficiaryService(this._dio);
Future<String> validateBeneficiaryWithinBank(String accountNumber) async {
try {
final response = await _dio.get('/api/beneficiary/validate/within-bank', queryParameters: {
'accountNumber': accountNumber,
});
if (response.statusCode == 200) {
return response.data['name'];
} else {
throw Exception(response.data['error'] ?? 'Failed to validate beneficiary');
}
} on DioException catch (e) {
throw Exception('Network error: ${e.message}');
} catch (e) {
throw Exception('Unexpected error: ${e.toString()}');
}
}
Future<ifsc?> validateIFSC(String ifscCode) async {
try {
final response = await _dio.get('/api/beneficiary/ifsc-details', queryParameters: {
"ifscCode": ifscCode
}
);
if (response.statusCode == 200) {
return ifsc.fromJson(response.data);
}
} on DioException catch (e) {
if (e.response?.statusCode == 404) {
print('Invalid IFSC code.');
} else {
print('API error: ${e.message}');
}
} catch (e) {
print('Unexpected error: $e');
}
return null;
}
// Send Data for Validation
Future<void> sendForValidation(Beneficiary beneficiary) async {
try {
print(beneficiary.toJson());
final response = await _dio.post(
'/api/beneficiary/add',
data: beneficiary.toJson(),
);
if (response.statusCode == 200) {
print("SENT FOR VALIDATION");
} else {
print("VALIDATION REQUEST FAILED: ${response.statusCode}");
}
} catch (e) {
print("ERROR IN SENDING REQUEST: $e");
rethrow;
}
}
// Poll to check if beneficiary is found
Future<bool> checkIfFound(String accountNo) async {
const int timeoutInSeconds = 30;
const int intervalInSeconds = 2;
const int maxTries = timeoutInSeconds ~/ intervalInSeconds;
int attempts = 0;
while (attempts < maxTries) {
try {
final response = await _dio.get(
'/api/beneficiary/check?',
queryParameters: {
'accountNo': accountNo
}
);
if (response.statusCode == 200) {
print("FOUND");
return true;
} else if (response.statusCode == 404) {
print("NOT FOUND");
}
} catch (e) {
print("ERROR DURING STATUS: $e");
}
attempts++;
}
print("Beneficiary not found within timeout.");
return false;
}
Future<List<dynamic>> fetchBeneficiaryList() async {
try {
final response = await _dio.get(
"/api/beneficiaries/get", // replace with actual path
options: Options(
headers: {
"Content-Type": "application/json",
},
),
);
if (response.statusCode == 200) {
// Assuming API returns JSON array of beneficiaries
return response.data as List<dynamic>;
} else {
throw Exception("Failed to fetch beneficiaries");
}
} catch (e) {
print("Error fetching beneficiaries: $e");
return [];
}
}
}