feat(api,ui,db): add address, guest users, image URLs; update API

- Backend:
  - Add address column to tickets and migration script
  - Create guest users when user_id is missing; accept user_name and address
  - Normalize stored image paths and expose absolute image_url
  - Introduce utils for path normalization and ticket serialization
  - Add CORS configuration for dashboard/emulator origins
  - Tickets API:
    - Serialize via ticket_to_dict with consistent schema
    - Change status update to PATCH /api/tickets/{id}/status with JSON body
    - Add DELETE /api/tickets/{id} with safe file removal
- Dashboard:
  - Fetch tickets from backend, show thumbnails, absolute image URLs
  - Status select + PATCH updates, toasts for feedback
  - Add i18n key btn.viewDetails
- Mobile app:
  - Persist device user_id via SharedPreferences
  - Fetch and merge API tickets; prefer network imageUrl
  - Submit user_name and address; delete via API when available
  - Make location acquisition robust with fallbacks and non-blocking UX
- Android/deps:
  - Disable Geolocator NMEA listener to prevent crashes
  - Downgrade geolocator to ^11.0.0 for stability

BREAKING CHANGE:
- Status endpoint changed from PATCH /api/tickets/{id}?new_status=... to
  PATCH /api/tickets/{id}/status with JSON body: {"status":"in_progress"}.
- /api/tickets and /api/tickets/{id} responses now use "id" (replacing
  "ticket_id"), include "image_url", and normalize fields for clients. Update
  consumers to use the new schema.
This commit is contained in:
2025-09-27 09:31:40 +08:00
parent 0e3eea7de9
commit 77d5be8fd1
27 changed files with 800 additions and 256 deletions

View File

@@ -1,5 +1,6 @@
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';
import 'package:uuid/uuid.dart';
import '../models/report.dart';
import '../models/enums.dart';
@@ -8,14 +9,24 @@ import '../models/enums.dart';
class ApiService {
// Configure this to match your backend URL
// Use localhost for web/desktop, network IP for mobile/emulator
static const String _baseUrl = 'http://192.168.100.59:8000/api';
static const String _uploadsUrl = 'http://192.168.100.59:8000/static/uploads';
static const String BASE_URL = 'http://192.168.100.59:8000';
static const String _baseUrl = '$BASE_URL/api';
static const String _uploadsUrl = '$BASE_URL/static/uploads';
// Create a user ID for this device if not exists
// Create a user ID for this device if not exists (persisted)
static Future<String> _getOrCreateUserId() async {
// For now, generate a UUID for this device
// In a real app, this would be stored securely
return const Uuid().v4();
try {
final prefs = await SharedPreferences.getInstance();
const key = 'fixmate_user_id';
final existing = prefs.getString(key);
if (existing != null && existing.isNotEmpty) return existing;
final newId = Uuid().v4();
await prefs.setString(key, newId);
return newId;
} catch (e) {
// If SharedPreferences fails for any reason, fallback to an in-memory UUID
return Uuid().v4();
}
}
/// Create a new user
@@ -42,6 +53,9 @@ class ApiService {
}
}
/// Get or create the current device / user id used when submitting reports
static Future<String> getUserId() => _getOrCreateUserId();
/// Submit a report to the backend
static Future<String> submitReport({
required double latitude,
@@ -49,6 +63,8 @@ class ApiService {
required String description,
required List<int> imageBytes,
required String imageName,
String? userName,
String? address,
}) async {
try {
final userId = await _getOrCreateUserId();
@@ -61,6 +77,8 @@ class ApiService {
request.fields['latitude'] = latitude.toString();
request.fields['longitude'] = longitude.toString();
request.fields['description'] = description;
if (userName != null && userName.isNotEmpty) request.fields['user_name'] = userName;
if (address != null && address.isNotEmpty) request.fields['address'] = address;
// Add the image file
request.files.add(
@@ -101,6 +119,9 @@ class ApiService {
}
}
/// Preferred API name for fetching tickets (alias for getReports)
static Future<List<Report>> fetchTickets() => getReports();
/// Get a single ticket by ID
static Future<Report?> getReportById(String ticketId) async {
try {
@@ -132,6 +153,24 @@ class ApiService {
}
}
/// Delete a ticket by ID
static Future<bool> deleteTicket(String ticketId) async {
try {
final response = await http.delete(
Uri.parse('$_baseUrl/tickets/$ticketId'),
);
if (response.statusCode == 200 || response.statusCode == 204) {
return true;
} else {
print('Failed to delete ticket: ${response.statusCode} ${response.body}');
return false;
}
} catch (e) {
print('Error deleting ticket: $e');
return false;
}
}
/// Get analytics data
static Future<Map<String, dynamic>> getAnalytics() async {
try {
@@ -150,22 +189,30 @@ class ApiService {
/// Convert API ticket response to Report model
static Report _convertApiTicketToReport(Map<String, dynamic> data) {
final id = (data['id'] ?? data['ticket_id'] ?? '').toString();
final imageUrl = (data['image_url'] as String?) ??
(data['image_path'] != null
? '$_uploadsUrl/${(data['image_path'] as String).split('/').last}'
: null);
return Report(
id: data['ticket_id'] ?? '',
id: id,
category: _normalizeCategory(data['category'] ?? ''),
severity: _normalizeSeverity(data['severity'] ?? 'N/A'),
status: _normalizeStatus(data['status'] ?? 'New'),
photoPath: data['image_path'] != null
? '$_uploadsUrl/${data['image_path'].split('/').last}'
: null,
// For API-provided tickets prefer imageUrl; photoPath is for local files
photoPath: null,
imageUrl: imageUrl,
location: LocationData(
lat: (data['latitude'] as num?)?.toDouble() ?? 0.0,
lng: (data['longitude'] as num?)?.toDouble() ?? 0.0,
),
createdAt: data['created_at'] ?? DateTime.now().toIso8601String(),
updatedAt: data['updated_at'] ?? DateTime.now().toIso8601String(),
deviceId: 'api-${data['ticket_id'] ?? ''}',
createdAt: (data['created_at'] ?? data['createdAt'] ?? DateTime.now().toIso8601String()) as String,
updatedAt: (data['updated_at'] ?? data['updatedAt'] ?? DateTime.now().toIso8601String()) as String,
deviceId: data['user_id'] != null ? data['user_id'].toString() : 'api-$id',
notes: data['description'] as String?,
address: data['address'] as String?,
submittedBy: data['user_name'] as String?,
source: 'api',
aiSuggestion: AISuggestion(
category: _normalizeCategory(data['category'] ?? ''),

View File

@@ -9,6 +9,13 @@ class LocationService {
return await Geolocator.isLocationServiceEnabled();
} catch (e) {
print('Error checking location service: $e');
// Handle specific Android exceptions that can cause crashes
if (e.toString().contains('DeadSystemException') ||
e.toString().contains('DeadSystemRuntimeException') ||
e.toString().contains('SecurityException')) {
print('System-level location service error detected, returning false');
return false;
}
return false;
}
}
@@ -19,6 +26,13 @@ class LocationService {
return await Geolocator.checkPermission();
} catch (e) {
print('Error checking location permission: $e');
// Handle specific Android exceptions that can cause crashes
if (e.toString().contains('DeadSystemException') ||
e.toString().contains('DeadSystemRuntimeException') ||
e.toString().contains('SecurityException')) {
print('System-level permission error detected, returning denied');
return LocationPermission.denied;
}
return LocationPermission.denied;
}
}
@@ -29,6 +43,15 @@ class LocationService {
return await Geolocator.requestPermission();
} catch (e) {
print('Error requesting location permission: $e');
// Handle specific Android exceptions that can cause crashes
if (e.toString().contains('DeadSystemException') ||
e.toString().contains('DeadSystemRuntimeException') ||
e.toString().contains('SecurityException')) {
print(
'System-level permission request error detected, returning denied',
);
return LocationPermission.denied;
}
return LocationPermission.denied;
}
}
@@ -58,17 +81,46 @@ class LocationService {
return null;
}
// Get current position
return await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.high,
timeLimit: const Duration(seconds: 30),
);
// Get current position with multiple fallback strategies
return await _getPositionWithFallback();
} catch (e) {
print('Error getting current position: $e');
return null;
}
}
/// Get position with fallback strategies to avoid crashes
static Future<Position?> _getPositionWithFallback() async {
try {
// Try high accuracy first with a reasonable timeout
return await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.high,
timeLimit: const Duration(seconds: 15),
);
} catch (e) {
print('High accuracy failed, trying medium accuracy: $e');
try {
// Fallback to medium accuracy
return await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.medium,
timeLimit: const Duration(seconds: 10),
);
} catch (e2) {
print('Medium accuracy failed, trying low accuracy: $e2');
try {
// Final fallback to low accuracy
return await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.low,
timeLimit: const Duration(seconds: 5),
);
} catch (e3) {
print('All accuracy levels failed: $e3');
return null;
}
}
}
}
/// Get current position with best available accuracy
static Future<Position?> getBestAvailablePosition() async {
try {
@@ -181,7 +233,10 @@ class LocationService {
}
/// Get address from coordinates (placeholder - would need geocoding service)
static Future<String?> getAddressFromCoordinates(double lat, double lng) async {
static Future<String?> getAddressFromCoordinates(
double lat,
double lng,
) async {
// This is a placeholder implementation
// In a real app, you would use a geocoding service like Google Maps API
// or OpenStreetMap Nominatim API
@@ -198,4 +253,4 @@ class LocationService {
acc != null &&
acc >= 0;
}
}
}

View File

@@ -57,6 +57,8 @@ class StorageService {
description: report.notes ?? '',
imageBytes: imageBytes,
imageName: '${report.id}.jpg',
userName: report.submittedBy,
address: report.address,
);
return true;
}
@@ -85,32 +87,38 @@ class StorageService {
/// Delete a report from storage (API first, fallback to local)
static Future<bool> deleteReport(String reportId) async {
try {
// Try API first (note: API doesn't have delete endpoint, so this will always fallback)
final apiReport = await ApiService.getReportById(reportId);
if (apiReport != null) {
// For now, the API doesn't have a delete endpoint, so we can't delete from API
// This would need to be added to the backend
print('API delete not available, keeping local copy');
// Try API delete first
final apiDeleted = await ApiService.deleteTicket(reportId);
if (apiDeleted) {
// Clean up local copies if any
try {
final reports = await getReports();
final updatedReports = reports.where((r) => r.id != reportId).toList();
if (!kIsWeb) {
await _deletePhotoFile(reportId);
}
await _saveReportsList(updatedReports);
} catch (e) {
print('Error cleaning local copies after API delete: $e');
}
return true;
}
} catch (e) {
print('API not available: $e');
print('API delete failed or API not available: $e');
}
// Fallback to local storage
// Fallback to local storage deletion
try {
final reports = await getReports();
final updatedReports = reports.where((r) => r.id != reportId).toList();
// Delete photo file if it exists
if (kIsWeb) {
// On web, base64 is stored in memory, no file to delete
} else {
if (!kIsWeb) {
await _deletePhotoFile(reportId);
}
return await _saveReportsList(updatedReports);
} catch (e) {
print('Error deleting report: $e');
print('Error deleting report locally: $e');
return false;
}
}