Adopt agents-settings kit, ship Product/SKU scan models, harden auth, verify OCR accuracy
Backend (app-pfm-ocr-v2/backend): - Product/SKU scan feature complete: trained DINOv2 index (118 reference photos, 16 SKU classes) and YOLO classifier (83.3% top-1 val accuracy), fixed scripts/install-pipeline.sh (was missing ultralytics/torch), fully browser-verified end-to-end on /scan-pfm. Mobile m-scan-pfm page cancelled (Flutter app handles mobile; web UI is desktop-only for pipeline testing). - Fixed a real data-loss bug: Save Ground Truth (scan-pfm and the DO-flow's manual-label) was silently writing into the pfm-web-app container's ephemeral filesystem instead of the host, because /sources wasn't bind-mounted in docker-compose.yml. Added the mount, recovered an orphaned entry. - accounts.password is now bcrypt-hashed (bcryptjs, idempotent migration in db/init.ts) instead of plaintext; login route compares hashes. - /api/v1/documents/* (list, PUT, upload) now enforces real 401 auth, matching what the Flutter client already sends. The "classic" routes deliberately stay open — they're dev-only web UI with no login flow and won't exist in production. - OCR accuracy investigated end-to-end: real baseline is 95.10% overall (target met; accuracy_report.md was stale at 75.04%, now flagged). Fixed one genuine parser.ts bug (SO/DO field duplication in the global fallback regex); remaining gaps are OCR/layout-model limitations, not parser bugs. - Adopted a standalone copy of the fhanyuh/agents-settings e/n workflow scoped to backend/ (AGENTS.md Part A/B split, SKILLS.md, plans/, docs/), independent of the root copy which now covers Flutter only. - next-implementation.md deleted; content folded into backend/plans/next-enhancements.md for traceability. Root: - Adopted fhanyuh/agents-settings kit (AGENTS.md, SKILLS.md, plans/, docs/feature-list.md), scoped to the Flutter app only. - Pending documents queue now persists to Hive (lib/core/storage) instead of memory-only, surviving an app kill mid-upload. Removed backend_backup/ (stale Express/Prisma prototype, superseded by pfm-web-app) and the completed plans/next-enhancement-plan.md checklist. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
3df9f6ec5d
commit
e60ab63154
129 files changed
+8520
-6684
No files matched your search
@@ -2,6 +2,7 @@ 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;
|
||||
@@ -11,7 +12,11 @@ class ApiClient {
|
||||
BaseOptions(
|
||||
baseUrl: AppConfig.apiBaseUrl,
|
||||
connectTimeout: const Duration(seconds: 10),
|
||||
receiveTimeout: const Duration(minutes: 2),
|
||||
// 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',
|
||||
@@ -41,36 +46,17 @@ class ApiClient {
|
||||
responseBody: true,
|
||||
));
|
||||
|
||||
// Standardized Error Interceptor
|
||||
// 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) {
|
||||
String errorMessage = 'Terjadi kesalahan yang tidak terduga';
|
||||
if (e.type == DioExceptionType.connectionTimeout ||
|
||||
e.type == DioExceptionType.receiveTimeout) {
|
||||
errorMessage = 'Koneksi timeout. Silakan coba lagi.';
|
||||
} else if (e.response != null) {
|
||||
// Standardized HTTP error formatting
|
||||
final statusCode = e.response?.statusCode;
|
||||
String serverMsg = 'Tidak diketahui';
|
||||
final responseData = e.response?.data;
|
||||
if (responseData is Map) {
|
||||
serverMsg = responseData['message'] ?? 'Tidak diketahui';
|
||||
} else if (responseData is String) {
|
||||
// Truncate raw string if it's a long HTML page
|
||||
serverMsg = responseData.length > 100
|
||||
? '${responseData.substring(0, 100)}...'
|
||||
: responseData;
|
||||
}
|
||||
errorMessage = 'Kesalahan server ($statusCode): $serverMsg';
|
||||
} else if (e.type == DioExceptionType.connectionError) {
|
||||
errorMessage = 'Tidak ada koneksi internet.';
|
||||
}
|
||||
|
||||
final apiException = ApiException.fromDioException(e);
|
||||
final customError = DioException(
|
||||
requestOptions: e.requestOptions,
|
||||
response: e.response,
|
||||
type: e.type,
|
||||
error: errorMessage,
|
||||
error: apiException,
|
||||
);
|
||||
return handler.next(customError);
|
||||
},
|
||||
|
||||
@@ -0,0 +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');
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user