Files
rental_income_tracker/lib/services/open_exchange_service.dart
T

221 lines
6.8 KiB
Dart

import 'dart:async';
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;
import 'package:intl/intl.dart';
class ForexConversionResult {
ForexConversionResult({required this.quote, required this.result});
final double quote;
final double result;
}
class ForexRateApiService {
ForexRateApiService({required this.httpClient, required this.apiKey});
final http.Client httpClient;
final String apiKey;
void _log(String message) {
if (kDebugMode) {
debugPrint('[ForexRateApiService] $message');
}
}
String _redactedUri(Uri uri) {
final redactedQuery = <String, String>{...uri.queryParameters};
if (redactedQuery.containsKey('api_key')) {
redactedQuery['api_key'] = '***REDACTED***';
}
return uri.replace(queryParameters: redactedQuery).toString();
}
bool _isRateLimitedResponse(http.Response response) {
if (response.statusCode == 429) {
return true;
}
try {
final parsed = jsonDecode(response.body) as Map<String, dynamic>;
final error = parsed['error'] as Map<String, dynamic>?;
final code = error?['code']?.toString().toLowerCase();
return code == '104' || code == 'rate_limit_reached';
} catch (_) {
return false;
}
}
DateTime _asUtcDate(DateTime value) {
return DateTime.utc(value.year, value.month, value.day);
}
DateTime _latestHistoricalDateUtc() {
final nowUtc = DateTime.now().toUtc();
final todayUtcDate = DateTime.utc(nowUtc.year, nowUtc.month, nowUtc.day);
return todayUtcDate.subtract(const Duration(days: 1));
}
DateTime _normalizeHistoricalDate(DateTime requestedDate) {
final requestedUtcDate = _asUtcDate(requestedDate);
final latestAllowed = _latestHistoricalDateUtc();
if (requestedUtcDate.isAfter(latestAllowed)) {
_log(
'Historical date ${DateFormat('yyyy-MM-dd').format(requestedUtcDate)} is not available yet; clamping to ${DateFormat('yyyy-MM-dd').format(latestAllowed)}.',
);
return latestAllowed;
}
return requestedUtcDate;
}
Future<http.Response> _getWithRateLimitRetry(
Uri uri, {
required String operation,
}) async {
const maxAttempts = 3;
for (var attempt = 1; attempt <= maxAttempts; attempt++) {
final response = await httpClient.get(uri);
_log('$operation HTTP status: ${response.statusCode}');
_log('$operation raw response: ${response.body}');
final shouldRetry = _isRateLimitedResponse(response);
if (!shouldRetry || attempt == maxAttempts) {
return response;
}
final delayMs = 1200 * attempt;
_log(
'$operation rate limited; retrying in ${delayMs}ms (attempt ${attempt + 1}/$maxAttempts)',
);
await Future.delayed(Duration(milliseconds: delayMs));
}
throw StateError('Unexpected rate-limit retry flow for $operation.');
}
Future<double> fetchUsdToSekRate({required DateTime estDate}) async {
if (apiKey == 'REPLACE_WITH_YOUR_FOREXRATE_API_KEY') {
throw StateError('ForexRateAPI key is not configured.');
}
final effectiveDate = _normalizeHistoricalDate(estDate);
final date = DateFormat('yyyy-MM-dd').format(effectiveDate);
final uri = Uri.https('api.forexrateapi.com', '/v1/$date', <String, String>{
'api_key': apiKey,
'base': 'USD',
'currencies': 'SEK',
});
_log('Daily rate request: ${_redactedUri(uri)}');
final response = await _getWithRateLimitRetry(uri, operation: 'Daily rate');
if (response.statusCode != 200) {
throw StateError('ForexRateAPI request failed (${response.statusCode}).');
}
final json = jsonDecode(response.body) as Map<String, dynamic>;
final success = json['success'] as bool? ?? false;
if (!success) {
final error = json['error'];
_log('Daily rate success=false. error=$error');
throw StateError('ForexRateAPI returned success=false. error=$error');
}
final rates = json['rates'] as Map<String, dynamic>?;
final sek = rates?['SEK'];
if (sek == null) {
throw StateError('SEK rate was missing in API response.');
}
_log('Daily rate parsed SEK quote: $sek');
return (sek as num).toDouble();
}
Future<ForexConversionResult> convertUsdToSek({
required DateTime estDate,
required double amount,
}) async {
if (apiKey == 'REPLACE_WITH_YOUR_FOREXRATE_API_KEY') {
throw StateError('ForexRateAPI key is not configured.');
}
final quote = await fetchUsdToSekRate(estDate: estDate);
final result = quote * amount;
_log(
'Computed conversion from daily rate quote=$quote result=$result amount=$amount date=${DateFormat('yyyy-MM-dd').format(estDate)}',
);
return ForexConversionResult(quote: quote, result: result);
}
/// Fetches USD->SEK cross-rates for every day of [year] in a single timeseries
/// API call. Returns a map of 'yyyy-MM-dd' -> rate, or null if the timeseries
/// endpoint is not available on the current subscription plan.
Future<Map<String, double>?> tryFetchYearRates(int year) async {
if (apiKey == 'REPLACE_WITH_YOUR_FOREXRATE_API_KEY') {
throw StateError('ForexRateAPI key is not configured.');
}
final start = DateTime(year, 1, 1);
final end = DateTime(year, 12, 31);
final uri =
Uri.https('api.forexrateapi.com', '/v1/timeframe', <String, String>{
'api_key': apiKey,
'base': 'USD',
'currencies': 'SEK',
'start_date': DateFormat('yyyy-MM-dd').format(start),
'end_date': DateFormat('yyyy-MM-dd').format(end),
});
_log('Timeframe request: ${_redactedUri(uri)}');
final response = await _getWithRateLimitRetry(uri, operation: 'Timeframe');
if (response.statusCode != 200) {
_log(
'Timeframe endpoint unavailable for this account or request; falling back to per-day requests. status=${response.statusCode}',
);
return null;
}
final json = jsonDecode(response.body) as Map<String, dynamic>;
final success = json['success'] as bool? ?? false;
if (!success) {
_log(
'Timeframe success=false; falling back to per-day requests. error=${json['error']}',
);
return null;
}
final rates = json['rates'] as Map<String, dynamic>?;
if (rates == null) {
_log(
'Timeframe response missing rates; falling back to per-day requests.',
);
return null;
}
final results = <String, double>{};
for (final entry in rates.entries) {
final dayRates = entry.value as Map<String, dynamic>?;
final sek = dayRates?['SEK'];
if (sek is num) {
results[entry.key] = sek.toDouble();
}
}
if (results.isEmpty) {
_log(
'Timeframe parsed no SEK entries; falling back to per-day requests.',
);
return null;
}
_log('Timeframe parsed ${results.length} daily SEK quotes.');
return results;
}
}