chore: normalize line endings (CRLF -> LF)
No content changes: git diff --ignore-all-space over these files is empty. The churn came from editing on Windows against a repo checked out with LF.
This commit is contained in:
1 parent
15566a6951
commit
caf8e98378
315 files changed
+86950
-86950
No files matched your search
@@ -1,75 +1,75 @@
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import '../../config/app_config.dart';
|
||||
import 'api_exception.dart';
|
||||
|
||||
class ApiClient {
|
||||
late final Dio _dio;
|
||||
|
||||
ApiClient() {
|
||||
_dio = Dio(
|
||||
BaseOptions(
|
||||
baseUrl: AppConfig.apiBaseUrl,
|
||||
connectTimeout: const Duration(seconds: 10),
|
||||
// Upload triggers a synchronous OCR pass server-side that can take up to
|
||||
// 210s worst case (see v1/documents/upload/route.ts's AbortSignal.timeout).
|
||||
// Keep a safety margin above that so a legitimately slow-but-successful
|
||||
// parse isn't killed client-side as a false "connection timeout".
|
||||
receiveTimeout: const Duration(seconds: 240),
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Accept': 'application/json',
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
_setupInterceptors();
|
||||
}
|
||||
|
||||
void _setupInterceptors() {
|
||||
// Request interceptor to append JWT token
|
||||
_dio.interceptors.add(InterceptorsWrapper(
|
||||
onRequest: (options, handler) async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final token = prefs.getString('auth_token');
|
||||
if (token != null) {
|
||||
options.headers['Authorization'] = 'Bearer $token';
|
||||
}
|
||||
return handler.next(options);
|
||||
},
|
||||
));
|
||||
|
||||
// Logging interceptor for debugging
|
||||
_dio.interceptors.add(LogInterceptor(
|
||||
requestBody: true,
|
||||
responseBody: true,
|
||||
));
|
||||
|
||||
// Standardized Error Interceptor: wraps every failure into an ApiException
|
||||
// (attached as DioException.error) so call sites read one consistent shape
|
||||
// instead of reverse-engineering DioException.toString().
|
||||
_dio.interceptors.add(InterceptorsWrapper(
|
||||
onError: (DioException e, handler) {
|
||||
final apiException = ApiException.fromDioException(e);
|
||||
final customError = DioException(
|
||||
requestOptions: e.requestOptions,
|
||||
response: e.response,
|
||||
type: e.type,
|
||||
error: apiException,
|
||||
);
|
||||
return handler.next(customError);
|
||||
},
|
||||
));
|
||||
|
||||
// Dummy Response Interceptor for Development
|
||||
// TODO: Remove this interceptor before production release
|
||||
// _dio.interceptors.add(DummyResponseInterceptor());
|
||||
}
|
||||
|
||||
Dio get client => _dio;
|
||||
}
|
||||
|
||||
// Single shared instance so every screen/notifier reuses the same Dio HTTP client
|
||||
// (connection keep-alive) instead of paying a fresh TCP/TLS handshake per call site.
|
||||
final apiClientProvider = Provider<ApiClient>((ref) => ApiClient());
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import '../../config/app_config.dart';
|
||||
import 'api_exception.dart';
|
||||
|
||||
class ApiClient {
|
||||
late final Dio _dio;
|
||||
|
||||
ApiClient() {
|
||||
_dio = Dio(
|
||||
BaseOptions(
|
||||
baseUrl: AppConfig.apiBaseUrl,
|
||||
connectTimeout: const Duration(seconds: 10),
|
||||
// Upload triggers a synchronous OCR pass server-side that can take up to
|
||||
// 210s worst case (see v1/documents/upload/route.ts's AbortSignal.timeout).
|
||||
// Keep a safety margin above that so a legitimately slow-but-successful
|
||||
// parse isn't killed client-side as a false "connection timeout".
|
||||
receiveTimeout: const Duration(seconds: 240),
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Accept': 'application/json',
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
_setupInterceptors();
|
||||
}
|
||||
|
||||
void _setupInterceptors() {
|
||||
// Request interceptor to append JWT token
|
||||
_dio.interceptors.add(InterceptorsWrapper(
|
||||
onRequest: (options, handler) async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final token = prefs.getString('auth_token');
|
||||
if (token != null) {
|
||||
options.headers['Authorization'] = 'Bearer $token';
|
||||
}
|
||||
return handler.next(options);
|
||||
},
|
||||
));
|
||||
|
||||
// Logging interceptor for debugging
|
||||
_dio.interceptors.add(LogInterceptor(
|
||||
requestBody: true,
|
||||
responseBody: true,
|
||||
));
|
||||
|
||||
// Standardized Error Interceptor: wraps every failure into an ApiException
|
||||
// (attached as DioException.error) so call sites read one consistent shape
|
||||
// instead of reverse-engineering DioException.toString().
|
||||
_dio.interceptors.add(InterceptorsWrapper(
|
||||
onError: (DioException e, handler) {
|
||||
final apiException = ApiException.fromDioException(e);
|
||||
final customError = DioException(
|
||||
requestOptions: e.requestOptions,
|
||||
response: e.response,
|
||||
type: e.type,
|
||||
error: apiException,
|
||||
);
|
||||
return handler.next(customError);
|
||||
},
|
||||
));
|
||||
|
||||
// Dummy Response Interceptor for Development
|
||||
// TODO: Remove this interceptor before production release
|
||||
// _dio.interceptors.add(DummyResponseInterceptor());
|
||||
}
|
||||
|
||||
Dio get client => _dio;
|
||||
}
|
||||
|
||||
// Single shared instance so every screen/notifier reuses the same Dio HTTP client
|
||||
// (connection keep-alive) instead of paying a fresh TCP/TLS handshake per call site.
|
||||
final apiClientProvider = Provider<ApiClient>((ref) => ApiClient());
|
||||
@@ -1,97 +1,97 @@
|
||||
import 'package:dio/dio.dart';
|
||||
|
||||
/// Mirrors backend/pfm-web-app/src/lib/http-status.ts - keep the two in sync.
|
||||
const Map<int, String> _httpReasonPhrases = {
|
||||
400: 'Bad Request',
|
||||
401: 'Unauthorized',
|
||||
403: 'Forbidden',
|
||||
404: 'Not Found',
|
||||
405: 'Method Not Allowed',
|
||||
409: 'Conflict',
|
||||
413: 'Payload Too Large',
|
||||
422: 'Unprocessable Entity',
|
||||
429: 'Too Many Requests',
|
||||
500: 'Internal Server Error',
|
||||
502: 'Bad Gateway',
|
||||
503: 'Service Unavailable',
|
||||
504: 'Gateway Timeout',
|
||||
};
|
||||
|
||||
/// Structured representation of an API/network failure, built from the
|
||||
/// backend's `{ status: "error", error: { statusCode, code, message } }`
|
||||
/// envelope or synthesized for network-level failures (timeout, no
|
||||
/// connection). This is the single object every catch block should read
|
||||
/// instead of scraping `DioException.toString()`.
|
||||
class ApiException implements Exception {
|
||||
final int? statusCode;
|
||||
final String code;
|
||||
final String message;
|
||||
|
||||
const ApiException({this.statusCode, required this.code, required this.message});
|
||||
|
||||
String get reasonPhrase {
|
||||
if (statusCode == null) return code;
|
||||
return _httpReasonPhrases[statusCode] ?? 'Error';
|
||||
}
|
||||
|
||||
/// Formatted like an HTTP status line, e.g. "404 Not Found: Document not found".
|
||||
String get displayMessage {
|
||||
if (statusCode == null) return message;
|
||||
return '$statusCode $reasonPhrase: $message';
|
||||
}
|
||||
|
||||
/// Unwraps any thrown object into an [ApiException]. This is the one call
|
||||
/// every catch block should use to get a consistent, displayable error.
|
||||
static ApiException from(Object error) {
|
||||
if (error is ApiException) return error;
|
||||
if (error is DioException) {
|
||||
if (error.error is ApiException) return error.error as ApiException;
|
||||
return fromDioException(error);
|
||||
}
|
||||
// Strip Dart's default `Exception: `/`Error: ` toString() prefix so plain
|
||||
// `throw Exception("...")` call sites still display just the message.
|
||||
final raw = error.toString();
|
||||
final message = raw.replaceFirst(RegExp(r'^(Exception|Error): '), '');
|
||||
return ApiException(code: 'UNKNOWN', message: message);
|
||||
}
|
||||
|
||||
static ApiException fromDioException(DioException e) {
|
||||
if (e.type == DioExceptionType.connectionTimeout ||
|
||||
e.type == DioExceptionType.sendTimeout ||
|
||||
e.type == DioExceptionType.receiveTimeout) {
|
||||
return const ApiException(code: 'TIMEOUT', message: 'Koneksi timeout. Silakan coba lagi.');
|
||||
}
|
||||
|
||||
if (e.type == DioExceptionType.connectionError) {
|
||||
return const ApiException(code: 'NETWORK_ERROR', message: 'Tidak ada koneksi internet.');
|
||||
}
|
||||
|
||||
final response = e.response;
|
||||
if (response != null) {
|
||||
final data = response.data;
|
||||
if (data is Map && data['error'] is Map) {
|
||||
final errorBody = data['error'] as Map;
|
||||
return ApiException(
|
||||
statusCode: (errorBody['statusCode'] as num?)?.toInt() ?? response.statusCode,
|
||||
code: errorBody['code']?.toString() ?? 'UNKNOWN',
|
||||
message: errorBody['message']?.toString() ?? 'Tidak diketahui',
|
||||
);
|
||||
}
|
||||
|
||||
// Fallback for responses that don't (yet) use the standardized envelope.
|
||||
String fallbackMessage = 'Tidak diketahui';
|
||||
if (data is Map && data['message'] != null) {
|
||||
fallbackMessage = data['message'].toString();
|
||||
} else if (data is String && data.isNotEmpty) {
|
||||
fallbackMessage = data.length > 100 ? '${data.substring(0, 100)}...' : data;
|
||||
}
|
||||
return ApiException(
|
||||
statusCode: response.statusCode,
|
||||
code: 'UNKNOWN',
|
||||
message: fallbackMessage,
|
||||
);
|
||||
}
|
||||
|
||||
return const ApiException(code: 'UNKNOWN', message: 'Terjadi kesalahan yang tidak terduga');
|
||||
}
|
||||
}
|
||||
import 'package:dio/dio.dart';
|
||||
|
||||
/// Mirrors backend/pfm-web-app/src/lib/http-status.ts - keep the two in sync.
|
||||
const Map<int, String> _httpReasonPhrases = {
|
||||
400: 'Bad Request',
|
||||
401: 'Unauthorized',
|
||||
403: 'Forbidden',
|
||||
404: 'Not Found',
|
||||
405: 'Method Not Allowed',
|
||||
409: 'Conflict',
|
||||
413: 'Payload Too Large',
|
||||
422: 'Unprocessable Entity',
|
||||
429: 'Too Many Requests',
|
||||
500: 'Internal Server Error',
|
||||
502: 'Bad Gateway',
|
||||
503: 'Service Unavailable',
|
||||
504: 'Gateway Timeout',
|
||||
};
|
||||
|
||||
/// Structured representation of an API/network failure, built from the
|
||||
/// backend's `{ status: "error", error: { statusCode, code, message } }`
|
||||
/// envelope or synthesized for network-level failures (timeout, no
|
||||
/// connection). This is the single object every catch block should read
|
||||
/// instead of scraping `DioException.toString()`.
|
||||
class ApiException implements Exception {
|
||||
final int? statusCode;
|
||||
final String code;
|
||||
final String message;
|
||||
|
||||
const ApiException({this.statusCode, required this.code, required this.message});
|
||||
|
||||
String get reasonPhrase {
|
||||
if (statusCode == null) return code;
|
||||
return _httpReasonPhrases[statusCode] ?? 'Error';
|
||||
}
|
||||
|
||||
/// Formatted like an HTTP status line, e.g. "404 Not Found: Document not found".
|
||||
String get displayMessage {
|
||||
if (statusCode == null) return message;
|
||||
return '$statusCode $reasonPhrase: $message';
|
||||
}
|
||||
|
||||
/// Unwraps any thrown object into an [ApiException]. This is the one call
|
||||
/// every catch block should use to get a consistent, displayable error.
|
||||
static ApiException from(Object error) {
|
||||
if (error is ApiException) return error;
|
||||
if (error is DioException) {
|
||||
if (error.error is ApiException) return error.error as ApiException;
|
||||
return fromDioException(error);
|
||||
}
|
||||
// Strip Dart's default `Exception: `/`Error: ` toString() prefix so plain
|
||||
// `throw Exception("...")` call sites still display just the message.
|
||||
final raw = error.toString();
|
||||
final message = raw.replaceFirst(RegExp(r'^(Exception|Error): '), '');
|
||||
return ApiException(code: 'UNKNOWN', message: message);
|
||||
}
|
||||
|
||||
static ApiException fromDioException(DioException e) {
|
||||
if (e.type == DioExceptionType.connectionTimeout ||
|
||||
e.type == DioExceptionType.sendTimeout ||
|
||||
e.type == DioExceptionType.receiveTimeout) {
|
||||
return const ApiException(code: 'TIMEOUT', message: 'Koneksi timeout. Silakan coba lagi.');
|
||||
}
|
||||
|
||||
if (e.type == DioExceptionType.connectionError) {
|
||||
return const ApiException(code: 'NETWORK_ERROR', message: 'Tidak ada koneksi internet.');
|
||||
}
|
||||
|
||||
final response = e.response;
|
||||
if (response != null) {
|
||||
final data = response.data;
|
||||
if (data is Map && data['error'] is Map) {
|
||||
final errorBody = data['error'] as Map;
|
||||
return ApiException(
|
||||
statusCode: (errorBody['statusCode'] as num?)?.toInt() ?? response.statusCode,
|
||||
code: errorBody['code']?.toString() ?? 'UNKNOWN',
|
||||
message: errorBody['message']?.toString() ?? 'Tidak diketahui',
|
||||
);
|
||||
}
|
||||
|
||||
// Fallback for responses that don't (yet) use the standardized envelope.
|
||||
String fallbackMessage = 'Tidak diketahui';
|
||||
if (data is Map && data['message'] != null) {
|
||||
fallbackMessage = data['message'].toString();
|
||||
} else if (data is String && data.isNotEmpty) {
|
||||
fallbackMessage = data.length > 100 ? '${data.substring(0, 100)}...' : data;
|
||||
}
|
||||
return ApiException(
|
||||
statusCode: response.statusCode,
|
||||
code: 'UNKNOWN',
|
||||
message: fallbackMessage,
|
||||
);
|
||||
}
|
||||
|
||||
return const ApiException(code: 'UNKNOWN', message: 'Terjadi kesalahan yang tidak terduga');
|
||||
}
|
||||
}
|
||||
@@ -1,70 +1,70 @@
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
/// Interceptor to simulate a 5-second delayed OCR processing response.
|
||||
/// This will only intercept POST requests to the upload document endpoint.
|
||||
class DummyResponseInterceptor extends Interceptor {
|
||||
@override
|
||||
Future<void> onRequest(RequestOptions options, RequestInterceptorHandler handler) async {
|
||||
// Check if it's the upload document endpoint
|
||||
if (options.path.contains('/documents/upload')) {
|
||||
debugPrint('Simulating 5-second processing delay for OCR...');
|
||||
|
||||
// Simulate 5 seconds delay
|
||||
await Future.delayed(const Duration(seconds: 5));
|
||||
|
||||
// Create a dummy successful response based on user schema requirements
|
||||
final dummyData = {
|
||||
'status': 'success',
|
||||
'message': 'Document processed successfully',
|
||||
'data': {
|
||||
'header': {
|
||||
'tanggal': '16 April 2026',
|
||||
'no_po': 'PO/26/0000140731',
|
||||
'no_so': '1691869400',
|
||||
'no_do': '1659896184'
|
||||
},
|
||||
'shipment': {
|
||||
'kepada_yth': 'PT.PRIMAFOOD INTERNATIONAL DKI AREA',
|
||||
'order_untuk': '',
|
||||
'alamat': 'JL. ANCOL BARAT VIII/1, ANCOL, PADEMANGAN, JAKARTA UTARA, 14430',
|
||||
'plat_truk': 'B 9310 BXT'
|
||||
},
|
||||
'items': [
|
||||
{
|
||||
'nomor_sku': '12080101',
|
||||
'nama_barang': '920 FIESTA SPICY CHICK 400 G',
|
||||
'banyak': '1 BOX',
|
||||
'jumlah': '12 PAC'
|
||||
},
|
||||
{
|
||||
'nomor_sku': '13010513',
|
||||
'nama_barang': '304 Champ Chicken Sausage 375 Gr 15 Pack',
|
||||
'banyak': '1 BOX',
|
||||
'jumlah': '15 PAC'
|
||||
},
|
||||
{
|
||||
'nomor_sku': '13030502',
|
||||
'nama_barang': '298 Champ Chicken Ball 500 GR Fr',
|
||||
'banyak': '1 BOX',
|
||||
'jumlah': '10 PAC'
|
||||
}
|
||||
]
|
||||
}
|
||||
};
|
||||
|
||||
debugPrint('Dummy response generated');
|
||||
|
||||
return handler.resolve(
|
||||
Response(
|
||||
requestOptions: options,
|
||||
data: dummyData,
|
||||
statusCode: 200,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// For other requests, continue normally
|
||||
super.onRequest(options, handler);
|
||||
}
|
||||
}
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
/// Interceptor to simulate a 5-second delayed OCR processing response.
|
||||
/// This will only intercept POST requests to the upload document endpoint.
|
||||
class DummyResponseInterceptor extends Interceptor {
|
||||
@override
|
||||
Future<void> onRequest(RequestOptions options, RequestInterceptorHandler handler) async {
|
||||
// Check if it's the upload document endpoint
|
||||
if (options.path.contains('/documents/upload')) {
|
||||
debugPrint('Simulating 5-second processing delay for OCR...');
|
||||
|
||||
// Simulate 5 seconds delay
|
||||
await Future.delayed(const Duration(seconds: 5));
|
||||
|
||||
// Create a dummy successful response based on user schema requirements
|
||||
final dummyData = {
|
||||
'status': 'success',
|
||||
'message': 'Document processed successfully',
|
||||
'data': {
|
||||
'header': {
|
||||
'tanggal': '16 April 2026',
|
||||
'no_po': 'PO/26/0000140731',
|
||||
'no_so': '1691869400',
|
||||
'no_do': '1659896184'
|
||||
},
|
||||
'shipment': {
|
||||
'kepada_yth': 'PT.PRIMAFOOD INTERNATIONAL DKI AREA',
|
||||
'order_untuk': '',
|
||||
'alamat': 'JL. ANCOL BARAT VIII/1, ANCOL, PADEMANGAN, JAKARTA UTARA, 14430',
|
||||
'plat_truk': 'B 9310 BXT'
|
||||
},
|
||||
'items': [
|
||||
{
|
||||
'nomor_sku': '12080101',
|
||||
'nama_barang': '920 FIESTA SPICY CHICK 400 G',
|
||||
'banyak': '1 BOX',
|
||||
'jumlah': '12 PAC'
|
||||
},
|
||||
{
|
||||
'nomor_sku': '13010513',
|
||||
'nama_barang': '304 Champ Chicken Sausage 375 Gr 15 Pack',
|
||||
'banyak': '1 BOX',
|
||||
'jumlah': '15 PAC'
|
||||
},
|
||||
{
|
||||
'nomor_sku': '13030502',
|
||||
'nama_barang': '298 Champ Chicken Ball 500 GR Fr',
|
||||
'banyak': '1 BOX',
|
||||
'jumlah': '10 PAC'
|
||||
}
|
||||
]
|
||||
}
|
||||
};
|
||||
|
||||
debugPrint('Dummy response generated');
|
||||
|
||||
return handler.resolve(
|
||||
Response(
|
||||
requestOptions: options,
|
||||
data: dummyData,
|
||||
statusCode: 200,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// For other requests, continue normally
|
||||
super.onRequest(options, handler);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user