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:
@@ -21,6 +21,9 @@ class Report {
|
||||
/// Base64 encoded photo for web platform
|
||||
final String? base64Photo;
|
||||
|
||||
/// Remote image URL provided by backend (absolute URL)
|
||||
final String? imageUrl;
|
||||
|
||||
/// Geographic location where the issue was reported
|
||||
final LocationData location;
|
||||
|
||||
@@ -38,6 +41,8 @@ class Report {
|
||||
|
||||
/// Address or location description (placeholder for future use)
|
||||
final String? address;
|
||||
/// Name of the user who submitted the report (API reports)
|
||||
final String? submittedBy;
|
||||
|
||||
/// Source of the photo ("camera" or "gallery")
|
||||
final String source;
|
||||
@@ -61,12 +66,14 @@ class Report {
|
||||
required this.status,
|
||||
this.photoPath,
|
||||
this.base64Photo,
|
||||
this.imageUrl,
|
||||
required this.location,
|
||||
required this.createdAt,
|
||||
required this.updatedAt,
|
||||
required this.deviceId,
|
||||
this.notes,
|
||||
this.address,
|
||||
this.submittedBy,
|
||||
required this.source,
|
||||
this.editable = true,
|
||||
this.deletable = true,
|
||||
@@ -89,6 +96,8 @@ class Report {
|
||||
String? photoPath,
|
||||
String? base64Photo,
|
||||
String? notes,
|
||||
String? submittedBy,
|
||||
String? address,
|
||||
required String source,
|
||||
required String deviceId,
|
||||
required AISuggestion aiSuggestion,
|
||||
@@ -106,6 +115,8 @@ class Report {
|
||||
updatedAt: now,
|
||||
deviceId: deviceId,
|
||||
notes: notes,
|
||||
address: address,
|
||||
submittedBy: submittedBy,
|
||||
source: source,
|
||||
aiSuggestion: aiSuggestion,
|
||||
);
|
||||
@@ -118,6 +129,7 @@ class Report {
|
||||
Status? status,
|
||||
String? photoPath,
|
||||
String? base64Photo,
|
||||
String? imageUrl,
|
||||
LocationData? location,
|
||||
String? updatedAt,
|
||||
String? notes,
|
||||
@@ -133,6 +145,7 @@ class Report {
|
||||
status: status ?? this.status,
|
||||
photoPath: photoPath ?? this.photoPath,
|
||||
base64Photo: base64Photo ?? this.base64Photo,
|
||||
imageUrl: imageUrl ?? this.imageUrl,
|
||||
location: location ?? this.location,
|
||||
createdAt: createdAt,
|
||||
updatedAt: updatedAt ?? this.updatedAt,
|
||||
@@ -156,6 +169,7 @@ class Report {
|
||||
'status': status.key,
|
||||
'photoPath': photoPath,
|
||||
'base64Photo': base64Photo,
|
||||
'imageUrl': imageUrl,
|
||||
'location': {
|
||||
'lat': location.lat,
|
||||
'lng': location.lng,
|
||||
@@ -166,6 +180,7 @@ class Report {
|
||||
'deviceId': deviceId,
|
||||
'notes': notes,
|
||||
'address': address,
|
||||
'submittedBy': submittedBy,
|
||||
'source': source,
|
||||
'editable': editable,
|
||||
'deletable': deletable,
|
||||
@@ -187,6 +202,7 @@ class Report {
|
||||
status: (json['status'] as String).toStatus() ?? Status.submitted,
|
||||
photoPath: json['photoPath'] as String?,
|
||||
base64Photo: json['base64Photo'] as String?,
|
||||
imageUrl: json['imageUrl'] as String?,
|
||||
location: LocationData(
|
||||
lat: (json['location']['lat'] as num).toDouble(),
|
||||
lng: (json['location']['lng'] as num).toDouble(),
|
||||
@@ -199,6 +215,7 @@ class Report {
|
||||
deviceId: json['deviceId'] as String,
|
||||
notes: json['notes'] as String?,
|
||||
address: json['address'] as String?,
|
||||
submittedBy: json['submittedBy'] as String?,
|
||||
source: json['source'] as String,
|
||||
editable: json['editable'] as bool? ?? true,
|
||||
deletable: json['deletable'] as bool? ?? true,
|
||||
|
||||
@@ -12,7 +12,7 @@ import '../../l10n/i18n.dart';
|
||||
import '../../models/enums.dart';
|
||||
import '../../models/report.dart';
|
||||
import '../../services/location_service.dart';
|
||||
import '../../services/storage.dart';
|
||||
import '../../services/api_service.dart';
|
||||
import '../../widgets/severity_badge.dart';
|
||||
import '../../widgets/status_badge.dart';
|
||||
import '../my_reports/my_reports_screen.dart';
|
||||
@@ -59,7 +59,7 @@ class _MapScreenState extends State<MapScreen> {
|
||||
|
||||
Future<void> _refresh() async {
|
||||
setState(() => _loading = true);
|
||||
final reports = await StorageService.getReports();
|
||||
final reports = await ApiService.fetchTickets();
|
||||
setState(() {
|
||||
_allReports = reports;
|
||||
_loading = false;
|
||||
@@ -325,6 +325,17 @@ class _MapScreenState extends State<MapScreen> {
|
||||
child: Icon(Icons.photo, color: Colors.grey.shade600),
|
||||
);
|
||||
|
||||
// Prefer backend-provided image URL when available
|
||||
if (r.imageUrl != null && r.imageUrl!.isNotEmpty) {
|
||||
return Image.network(
|
||||
r.imageUrl!,
|
||||
width: 120,
|
||||
height: 90,
|
||||
fit: BoxFit.cover,
|
||||
errorBuilder: (_, __, ___) => placeholder,
|
||||
);
|
||||
}
|
||||
|
||||
if (kIsWeb) {
|
||||
if (r.base64Photo != null && r.base64Photo!.isNotEmpty) {
|
||||
try {
|
||||
@@ -776,7 +787,17 @@ class MapReportDetails extends StatelessWidget {
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
if (kIsWeb && report.base64Photo != null)
|
||||
if (report.imageUrl != null)
|
||||
Image.network(
|
||||
report.imageUrl!,
|
||||
errorBuilder: (_, __, ___) => Container(
|
||||
height: 180,
|
||||
color: Colors.grey.shade200,
|
||||
alignment: Alignment.center,
|
||||
child: const Icon(Icons.photo, size: 64),
|
||||
),
|
||||
)
|
||||
else if (kIsWeb && report.base64Photo != null)
|
||||
Image.memory(base64Decode(report.base64Photo!))
|
||||
else if (!kIsWeb && report.photoPath != null)
|
||||
Image.file(File(report.photoPath!))
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import '../../services/storage.dart';
|
||||
import '../../services/api_service.dart';
|
||||
import '../../models/report.dart';
|
||||
import '../../widgets/report_card.dart';
|
||||
import '../map/map_screen.dart';
|
||||
@@ -23,14 +24,46 @@ class _MyReportsScreenState extends State<MyReportsScreen> {
|
||||
}
|
||||
|
||||
Future<void> _loadReports() async {
|
||||
setState(() {
|
||||
_loading = true;
|
||||
});
|
||||
final reports = await StorageService.getReports();
|
||||
setState(() {
|
||||
_reports = reports.reversed.toList(); // newest first
|
||||
_loading = false;
|
||||
});
|
||||
setState(() => _loading = true);
|
||||
|
||||
try {
|
||||
// Try to fetch tickets from API and filter by this device's user id
|
||||
final userId = await ApiService.getUserId();
|
||||
final apiReports = await ApiService.fetchTickets();
|
||||
|
||||
// Keep only reports that belong to this device/user
|
||||
final myApiReports = apiReports.where((r) => r.deviceId == userId).toList();
|
||||
|
||||
// Also include any local reports stored that belong to this device
|
||||
final localReports = await StorageService.getReports();
|
||||
final myLocalReports = localReports.where((r) => r.deviceId == userId).toList();
|
||||
|
||||
// Merge by id, prefer API version when available
|
||||
final Map<String, Report> merged = {};
|
||||
for (final r in myApiReports) merged[r.id] = r;
|
||||
for (final r in myLocalReports) {
|
||||
if (!merged.containsKey(r.id)) merged[r.id] = r;
|
||||
}
|
||||
|
||||
final combined = merged.values.toList();
|
||||
|
||||
setState(() {
|
||||
if (combined.isNotEmpty) {
|
||||
_reports = combined.reversed.toList(); // newest first
|
||||
} else {
|
||||
// Fallback: show local reports if no API-backed reports found for this user
|
||||
_reports = localReports.reversed.toList();
|
||||
}
|
||||
_loading = false;
|
||||
});
|
||||
} catch (e) {
|
||||
// Conservative fallback to local storage
|
||||
final reports = await StorageService.getReports();
|
||||
setState(() {
|
||||
_reports = reports.reversed.toList();
|
||||
_loading = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
void _onViewReport(Report r) {
|
||||
|
||||
@@ -54,25 +54,35 @@ class _CaptureScreenState extends State<CaptureScreen> {
|
||||
|
||||
Future<void> _processImage(XFile image, ImageSource source) async {
|
||||
try {
|
||||
// Get current position (Geolocator.Position)
|
||||
// Get current position (optional - app can work without location)
|
||||
final position = await LocationService.getCurrentPosition();
|
||||
|
||||
if (position == null) {
|
||||
// Create location data even if position is null (with default values)
|
||||
LocationData? locationData;
|
||||
if (position != null) {
|
||||
locationData = LocationService.positionToLocationData(position);
|
||||
print('Location acquired: ${locationData.lat}, ${locationData.lng}');
|
||||
} else {
|
||||
// Create a fallback location with zero coordinates
|
||||
// This allows the app to continue working without location
|
||||
locationData = LocationData(lat: 0.0, lng: 0.0, accuracy: null);
|
||||
print(
|
||||
'Using fallback location (0.0, 0.0) - location services unavailable',
|
||||
);
|
||||
|
||||
// Show a non-blocking warning to the user
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: const Text(
|
||||
'Unable to get location. Please try again.',
|
||||
const SnackBar(
|
||||
content: Text(
|
||||
'Location unavailable. Report will be created without GPS coordinates.',
|
||||
), // TODO: Move to i18n
|
||||
duration: Duration(seconds: 3),
|
||||
),
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Convert Position -> LocationData (app model)
|
||||
final locationData = LocationService.positionToLocationData(position);
|
||||
|
||||
// Generate AI suggestion (seeded deterministic)
|
||||
final aiSuggestion = MockAIService.generateSuggestion(
|
||||
id: DateTime.now().millisecondsSinceEpoch.toString(),
|
||||
@@ -113,10 +123,12 @@ class _CaptureScreenState extends State<CaptureScreen> {
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
print('Critical error in image processing: $e');
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(I18n.t('error.imageProcessing', {'0': e.toString()})),
|
||||
backgroundColor: Colors.red,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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'] ?? ''),
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import 'package:flutter/material.dart';
|
||||
import '../models/report.dart';
|
||||
import '../models/enums.dart' as enums;
|
||||
import '../services/storage.dart';
|
||||
import '../services/api_service.dart';
|
||||
import '../l10n/i18n.dart';
|
||||
|
||||
class ReportCard extends StatelessWidget {
|
||||
@@ -22,6 +23,30 @@ class ReportCard extends StatelessWidget {
|
||||
});
|
||||
|
||||
Widget _buildThumbnail() {
|
||||
final placeholder = Container(
|
||||
width: 72,
|
||||
height: 72,
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.grey.shade200,
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: Icon(Icons.image, color: Colors.grey.shade600),
|
||||
);
|
||||
|
||||
// Prefer backend-provided image URL when available
|
||||
if (report.imageUrl != null && report.imageUrl!.isNotEmpty) {
|
||||
return ClipRRect(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
child: Image.network(
|
||||
report.imageUrl!,
|
||||
width: 72,
|
||||
height: 72,
|
||||
fit: BoxFit.cover,
|
||||
errorBuilder: (_, __, ___) => placeholder,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
if (kIsWeb && report.base64Photo != null) {
|
||||
try {
|
||||
final bytes = base64Decode(report.base64Photo!);
|
||||
@@ -32,21 +57,15 @@ class ReportCard extends StatelessWidget {
|
||||
} catch (_) {}
|
||||
} else if (report.photoPath != null) {
|
||||
final file = File(report.photoPath!);
|
||||
return ClipRRect(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
child: Image.file(file, width: 72, height: 72, fit: BoxFit.cover),
|
||||
);
|
||||
if (file.existsSync()) {
|
||||
return ClipRRect(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
child: Image.file(file, width: 72, height: 72, fit: BoxFit.cover),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return Container(
|
||||
width: 72,
|
||||
height: 72,
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.grey.shade200,
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: Icon(Icons.image, color: Colors.grey.shade600),
|
||||
);
|
||||
return placeholder;
|
||||
}
|
||||
|
||||
String _formatTime(String iso) {
|
||||
@@ -78,7 +97,19 @@ class ReportCard extends StatelessWidget {
|
||||
);
|
||||
|
||||
if (ok == true) {
|
||||
final success = await StorageService.deleteReport(report.id);
|
||||
bool success = false;
|
||||
try {
|
||||
success = await ApiService.deleteTicket(report.id);
|
||||
} catch (e) {
|
||||
print('Error deleting via API: $e');
|
||||
success = false;
|
||||
}
|
||||
|
||||
// Fallback to local delete if API delete fails
|
||||
if (!success) {
|
||||
success = await StorageService.deleteReport(report.id);
|
||||
}
|
||||
|
||||
if (success) {
|
||||
if (onDeleted != null) {
|
||||
onDeleted!();
|
||||
@@ -88,6 +119,12 @@ class ReportCard extends StatelessWidget {
|
||||
SnackBar(content: Text(I18n.t('toast.reportDeleted'))),
|
||||
);
|
||||
}
|
||||
} else {
|
||||
if (context.mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text(I18n.t('error.saving', {'0': 'Failed to delete report'}))),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -236,7 +273,24 @@ class ReportCard extends StatelessWidget {
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
const SizedBox(height: 8),
|
||||
// Submitted by (if available)
|
||||
if (report.submittedBy != null) ...[
|
||||
Row(
|
||||
children: [
|
||||
Icon(Icons.person, size: 14, color: cs.onSurface.withOpacity(0.6)),
|
||||
const SizedBox(width: 6),
|
||||
Expanded(
|
||||
child: Text(
|
||||
'Submitted by ${report.submittedBy}',
|
||||
style: TextStyle(fontSize: 12, color: cs.onSurface.withOpacity(0.7)),
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
],
|
||||
// Status indicators
|
||||
Row(
|
||||
children: [
|
||||
@@ -343,7 +397,9 @@ class ReportCard extends StatelessWidget {
|
||||
const SizedBox(width: 4),
|
||||
Expanded(
|
||||
child: Text(
|
||||
'${report.location.lat.toStringAsFixed(4)}, ${report.location.lng.toStringAsFixed(4)}',
|
||||
report.address != null && report.address!.isNotEmpty
|
||||
? report.address!
|
||||
: '${report.location.lat.toStringAsFixed(4)}, ${report.location.lng.toStringAsFixed(4)}',
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
color: cs.onSurface.withOpacity(0.6),
|
||||
@@ -374,40 +430,36 @@ class ReportCard extends StatelessWidget {
|
||||
}
|
||||
},
|
||||
itemBuilder: (_) => [
|
||||
const PopupMenuItem(
|
||||
PopupMenuItem(
|
||||
value: 0,
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(Icons.visibility),
|
||||
SizedBox(width: 8),
|
||||
Text(
|
||||
'View Details',
|
||||
), // TODO: Move to i18n but need to handle dynamic text in popup menu
|
||||
const Icon(Icons.visibility),
|
||||
const SizedBox(width: 8),
|
||||
Text(I18n.t('btn.viewDetails')),
|
||||
],
|
||||
),
|
||||
),
|
||||
const PopupMenuItem(
|
||||
PopupMenuItem(
|
||||
value: 1,
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(Icons.update),
|
||||
SizedBox(width: 8),
|
||||
Text(
|
||||
'Update Status',
|
||||
), // TODO: Move to i18n but need to handle dynamic text in popup menu
|
||||
const Icon(Icons.update),
|
||||
const SizedBox(width: 8),
|
||||
Text(I18n.t('report.updateStatus')),
|
||||
],
|
||||
),
|
||||
),
|
||||
const PopupMenuItem(
|
||||
PopupMenuItem(
|
||||
value: 2,
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(Icons.delete, color: Colors.red),
|
||||
SizedBox(width: 8),
|
||||
const Icon(Icons.delete, color: Colors.red),
|
||||
const SizedBox(width: 8),
|
||||
Text(
|
||||
'Delete',
|
||||
style: TextStyle(color: Colors.red),
|
||||
), // TODO: Move to i18n but need to handle dynamic text in popup menu
|
||||
I18n.t('report.delete'),
|
||||
style: const TextStyle(color: Colors.red),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
Reference in New Issue
Block a user