Code changes by azmat
This commit is contained in:
@@ -0,0 +1,52 @@
|
||||
import 'dart:math' as math;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Attendance math + filter rules (shared by UI and background service).
|
||||
//
|
||||
// Simple version:
|
||||
// - Wake every 5 min, take ONE gps reading, sleep again (battery safe).
|
||||
// - Throw away weak readings (error > 50 m).
|
||||
// - Throw away tiny jumps (< 20 m) so sitting still never invents fake km.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// How often the background service takes one GPS reading.
|
||||
const Duration kFixInterval = Duration(minutes: 5);
|
||||
|
||||
/// Max seconds to wait for a single GPS fix before giving up.
|
||||
const Duration kFixTimeout = Duration(seconds: 30);
|
||||
|
||||
/// Discard any fix whose own accuracy error is worse than this (meters).
|
||||
const double kMaxAcceptableAccuracyMeters = 50.0;
|
||||
|
||||
/// Ignore movement smaller than this (meters) - kills stationary drift.
|
||||
const double kMinMoveMeters = 20.0;
|
||||
|
||||
/// Straight-line distance between two lat/lng points, in meters.
|
||||
double haversineMeters(double lat1, double lon1, double lat2, double lon2) {
|
||||
const double earthRadius = 6371000.0; // meters
|
||||
final double dLat = _toRadians(lat2 - lat1);
|
||||
final double dLon = _toRadians(lon2 - lon1);
|
||||
final double a = math.sin(dLat / 2) * math.sin(dLat / 2) +
|
||||
math.cos(_toRadians(lat1)) *
|
||||
math.cos(_toRadians(lat2)) *
|
||||
math.sin(dLon / 2) *
|
||||
math.sin(dLon / 2);
|
||||
final double c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a));
|
||||
return earthRadius * c;
|
||||
}
|
||||
|
||||
double _toRadians(double degrees) => degrees * math.pi / 180.0;
|
||||
|
||||
/// Decides whether a new fix is worth storing. Returns true only when the
|
||||
/// reading is strong enough AND the person actually moved.
|
||||
bool shouldStorePoint({
|
||||
required double accuracy,
|
||||
required double distanceFromLastMeters,
|
||||
required bool isFirstPoint,
|
||||
}) {
|
||||
if (accuracy > kMaxAcceptableAccuracyMeters) return false; // weak signal
|
||||
if (!isFirstPoint && distanceFromLastMeters < kMinMoveMeters) {
|
||||
return false; // standing still (drift)
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,284 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_foreground_task/flutter_foreground_task.dart';
|
||||
import 'package:geolocator/geolocator.dart';
|
||||
import 'package:permission_handler/permission_handler.dart' as ph;
|
||||
|
||||
import 'attendance_math.dart';
|
||||
import 'attendance_storage.dart';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Background attendance tracking (wake every 5 min -> one GPS fix -> sleep).
|
||||
//
|
||||
// The task handler runs in a background isolate. It reads the open session id
|
||||
// that the UI saved, takes one fix, applies the accuracy/drift filters and
|
||||
// stores accepted dots in sqflite. It also pings the UI with live totals.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Entry point for the background isolate. Must stay top-level.
|
||||
@pragma('vm:entry-point')
|
||||
void attendanceCallback() {
|
||||
FlutterForegroundTask.setTaskHandler(AttendanceTaskHandler());
|
||||
}
|
||||
|
||||
class AttendanceTaskHandler extends TaskHandler {
|
||||
String? _sessionId;
|
||||
|
||||
@override
|
||||
Future<void> onStart(DateTime timestamp, TaskStarter starter) async {
|
||||
try {
|
||||
_sessionId =
|
||||
await FlutterForegroundTask.getData(key: 'attendance_session_id')
|
||||
as String?;
|
||||
} catch (_) {
|
||||
_sessionId = null;
|
||||
}
|
||||
// Fallback: SharedPreferences is visible from this isolate too.
|
||||
_sessionId ??= await AttendanceStorage.getActiveSession();
|
||||
}
|
||||
|
||||
@override
|
||||
void onRepeatEvent(DateTime timestamp) async {
|
||||
final String? sessionId = _sessionId ?? await _refreshSessionId();
|
||||
if (sessionId == null) return; // punched out already, nothing to do
|
||||
|
||||
try {
|
||||
final Position pos = await Geolocator.getCurrentPosition(
|
||||
locationSettings: LocationSettings(
|
||||
accuracy: LocationAccuracy.high,
|
||||
timeLimit: kFixTimeout,
|
||||
),
|
||||
);
|
||||
|
||||
final List<Map<String, dynamic>> existing =
|
||||
await AttendanceStorage.getPoints(sessionId);
|
||||
final bool isFirst = existing.isEmpty;
|
||||
double distanceFromLast = 0;
|
||||
if (!isFirst) {
|
||||
final last = existing.last;
|
||||
distanceFromLast = haversineMeters(
|
||||
(last['lat'] as num).toDouble(),
|
||||
(last['lng'] as num).toDouble(),
|
||||
pos.latitude,
|
||||
pos.longitude,
|
||||
);
|
||||
}
|
||||
|
||||
final bool keep = shouldStorePoint(
|
||||
accuracy: pos.accuracy,
|
||||
distanceFromLastMeters: distanceFromLast,
|
||||
isFirstPoint: isFirst,
|
||||
);
|
||||
|
||||
if (keep) {
|
||||
await AttendanceStorage.insertPoint(
|
||||
sessionId: sessionId,
|
||||
lat: pos.latitude,
|
||||
lng: pos.longitude,
|
||||
accuracy: pos.accuracy,
|
||||
isMocked: pos.isMocked,
|
||||
timestamp: pos.timestamp,
|
||||
);
|
||||
}
|
||||
|
||||
// Live totals for the open punch page (harmless if nobody listens).
|
||||
final updated = await AttendanceStorage.getPoints(sessionId);
|
||||
final double km = _totalKm(updated);
|
||||
FlutterForegroundTask.sendDataToMain({
|
||||
'sessionId': sessionId,
|
||||
'points': updated.length,
|
||||
'km': km,
|
||||
});
|
||||
try {
|
||||
await FlutterForegroundTask.updateService(
|
||||
notificationTitle: 'Duty tracking ON',
|
||||
notificationText:
|
||||
'${updated.length} points • ${km.toStringAsFixed(2)} km',
|
||||
);
|
||||
} catch (_) {}
|
||||
} catch (_) {
|
||||
// GPS off / timeout / no fix this round - just wait for next 5-min tick.
|
||||
}
|
||||
}
|
||||
|
||||
Future<String?> _refreshSessionId() async {
|
||||
_sessionId = await AttendanceStorage.getActiveSession();
|
||||
return _sessionId;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> onDestroy(DateTime timestamp, bool isTimeout) async {}
|
||||
|
||||
double _totalKm(List<Map<String, dynamic>> points) {
|
||||
double meters = 0;
|
||||
for (int i = 1; i < points.length; i++) {
|
||||
meters += haversineMeters(
|
||||
(points[i - 1]['lat'] as num).toDouble(),
|
||||
(points[i - 1]['lng'] as num).toDouble(),
|
||||
(points[i]['lat'] as num).toDouble(),
|
||||
(points[i]['lng'] as num).toDouble(),
|
||||
);
|
||||
}
|
||||
return meters / 1000.0;
|
||||
}
|
||||
}
|
||||
|
||||
/// Small result for the permission flow so the UI can explain, not just fail.
|
||||
class PermissionResult {
|
||||
final bool ok;
|
||||
final String message;
|
||||
PermissionResult(this.ok, this.message);
|
||||
}
|
||||
|
||||
class AttendanceService {
|
||||
static bool _initialized = false;
|
||||
|
||||
/// Call once from main() before runApp().
|
||||
static void initService() {
|
||||
if (_initialized) return;
|
||||
FlutterForegroundTask.init(
|
||||
androidNotificationOptions: AndroidNotificationOptions(
|
||||
channelId: 'attendance_tracking',
|
||||
channelName: 'Duty tracking',
|
||||
channelDescription:
|
||||
'Shows while your duty location is being recorded.',
|
||||
),
|
||||
iosNotificationOptions: const IOSNotificationOptions(
|
||||
showNotification: true,
|
||||
),
|
||||
foregroundTaskOptions: ForegroundTaskOptions(
|
||||
eventAction: ForegroundTaskEventAction.repeat(
|
||||
kFixInterval.inMilliseconds,
|
||||
),
|
||||
allowWakeLock: true,
|
||||
allowWifiLock: false,
|
||||
autoRunOnBoot: false,
|
||||
// Swiping the app away from recents must NOT stop duty tracking.
|
||||
stopWithTask: false,
|
||||
),
|
||||
);
|
||||
_initialized = true;
|
||||
}
|
||||
|
||||
/// Asks (in order): location -> always/background -> notifications + GPS on.
|
||||
static Future<PermissionResult> ensurePermissions() async {
|
||||
final bool serviceOn = await Geolocator.isLocationServiceEnabled();
|
||||
if (!serviceOn) {
|
||||
return PermissionResult(
|
||||
false, 'Please switch ON location (GPS) and try again.');
|
||||
}
|
||||
|
||||
ph.PermissionStatus loc = await ph.Permission.location.request();
|
||||
if (!loc.isGranted) {
|
||||
return PermissionResult(
|
||||
false, 'Location permission is needed for punch in.');
|
||||
}
|
||||
|
||||
// Android 10+: background needs its own grant (may open Settings).
|
||||
ph.PermissionStatus always = await ph.Permission.locationAlways.request();
|
||||
if (!always.isGranted) {
|
||||
return PermissionResult(true,
|
||||
'Background not granted - tracking works only while the app is open.');
|
||||
}
|
||||
|
||||
await ph.Permission.notification.request(); // for the tracking notice
|
||||
return PermissionResult(true, ' granted');
|
||||
}
|
||||
|
||||
static Future<bool> get isPunchedIn async {
|
||||
if (!await FlutterForegroundTask.isRunningService) {
|
||||
// Service dead but prefs say open (reboot/crash) -> still show open.
|
||||
return await AttendanceStorage.getActiveSession() != null;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/// Starts a duty session + background tracking. Returns the session id.
|
||||
static Future<String> punchIn() async {
|
||||
final String sessionId =
|
||||
'SES-${DateTime.now().millisecondsSinceEpoch}';
|
||||
final DateTime now = DateTime.now();
|
||||
await AttendanceStorage.createSession(sessionId, now);
|
||||
await AttendanceStorage.setActiveSession(sessionId);
|
||||
await FlutterForegroundTask.saveData(
|
||||
key: 'attendance_session_id', value: sessionId);
|
||||
|
||||
await FlutterForegroundTask.startService(
|
||||
serviceId: 1001,
|
||||
serviceTypes: [ForegroundServiceTypes.location],
|
||||
notificationTitle: 'Duty tracking ON',
|
||||
notificationText: 'Punched in at ${_hhmm(now)} • recording location',
|
||||
callback: attendanceCallback,
|
||||
);
|
||||
return sessionId;
|
||||
}
|
||||
|
||||
/// Stops tracking and closes the session. Returns a summary for the UI.
|
||||
static Future<Map<String, dynamic>> punchOut() async {
|
||||
final String? sessionId = await AttendanceStorage.getActiveSession();
|
||||
try {
|
||||
await FlutterForegroundTask.stopService();
|
||||
} catch (_) {}
|
||||
await FlutterForegroundTask.clearAllData();
|
||||
await AttendanceStorage.clearActiveSession();
|
||||
|
||||
if (sessionId == null) {
|
||||
return {'points': 0, 'km': 0.0};
|
||||
}
|
||||
final List<Map<String, dynamic>> points =
|
||||
await AttendanceStorage.getPoints(sessionId);
|
||||
double meters = 0;
|
||||
for (int i = 1; i < points.length; i++) {
|
||||
meters += haversineMeters(
|
||||
(points[i - 1]['lat'] as num).toDouble(),
|
||||
(points[i - 1]['lng'] as num).toDouble(),
|
||||
(points[i]['lat'] as num).toDouble(),
|
||||
(points[i]['lng'] as num).toDouble(),
|
||||
);
|
||||
}
|
||||
final double km = meters / 1000.0;
|
||||
final Map<String, dynamic>? session =
|
||||
await AttendanceStorage.getSession(sessionId);
|
||||
await AttendanceStorage.closeSession(sessionId, DateTime.now(), km);
|
||||
return {
|
||||
'sessionId': sessionId,
|
||||
'punchIn': session?['punch_in'],
|
||||
'points': points.length,
|
||||
'km': km,
|
||||
};
|
||||
}
|
||||
|
||||
static String _hhmm(DateTime t) =>
|
||||
'${t.hour.toString().padLeft(2, '0')}:${t.minute.toString().padLeft(2, '0')}';
|
||||
|
||||
/// Nudge to exempt the app from battery optimization (OEMs kill trackers).
|
||||
static Future<void> maybeAskBatteryExemption(BuildContext context) async {
|
||||
try {
|
||||
final bool ignoring =
|
||||
await FlutterForegroundTask.isIgnoringBatteryOptimizations;
|
||||
if (ignoring || !context.mounted) return;
|
||||
final bool? go = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (c) => AlertDialog(
|
||||
title: const Text('Keep tracking running'),
|
||||
content: const Text(
|
||||
'Xiaomi, Oppo, Vivo and Samsung phones stop background tracking '
|
||||
'to save battery. Allow "Unrestricted" battery use for this app '
|
||||
'so duty tracking keeps working when the screen is off?'),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(c).pop(false),
|
||||
child: const Text('Later')),
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(c).pop(true),
|
||||
child: const Text('Open settings')),
|
||||
],
|
||||
),
|
||||
);
|
||||
if (go == true) {
|
||||
await FlutterForegroundTask.requestIgnoreBatteryOptimization();
|
||||
}
|
||||
} catch (_) {}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
import 'package:path/path.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import 'package:sqflite/sqflite.dart';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Phone-only storage for attendance (no backend yet).
|
||||
//
|
||||
// - SharedPreferences keeps ONE value: the currently open session id
|
||||
// (so UI, background service and reboot recovery all agree).
|
||||
// - sqflite keeps every session + every GPS dot.
|
||||
//
|
||||
// NOTE: the database handle is opened per-isolate (statics are per-isolate),
|
||||
// so the background service gets its own safe handle.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
class AttendanceStorage {
|
||||
static const String _dbName = 'attendance.db';
|
||||
static const String _prefsActiveSessionKey = 'attendance_active_session';
|
||||
|
||||
static Database? _db;
|
||||
|
||||
static Future<Database> get _database async {
|
||||
if (_db != null) return _db!;
|
||||
final String path = join(await getDatabasesPath(), _dbName);
|
||||
_db = await openDatabase(
|
||||
path,
|
||||
version: 1,
|
||||
onCreate: (Database db, int version) async {
|
||||
await db.execute('''
|
||||
CREATE TABLE attendance_sessions(
|
||||
session_id TEXT PRIMARY KEY,
|
||||
punch_in TEXT NOT NULL,
|
||||
punch_out TEXT,
|
||||
status TEXT NOT NULL,
|
||||
total_km_haversine REAL DEFAULT 0
|
||||
)
|
||||
''');
|
||||
await db.execute('''
|
||||
CREATE TABLE attendance_points(
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
session_id TEXT NOT NULL,
|
||||
lat REAL NOT NULL,
|
||||
lng REAL NOT NULL,
|
||||
accuracy REAL NOT NULL,
|
||||
is_mocked INTEGER NOT NULL DEFAULT 0,
|
||||
timestamp TEXT NOT NULL
|
||||
)
|
||||
''');
|
||||
await db.execute('''
|
||||
CREATE INDEX idx_points_session ON attendance_points(session_id)
|
||||
''');
|
||||
},
|
||||
);
|
||||
return _db!;
|
||||
}
|
||||
|
||||
// ---------------- active session (SharedPreferences) ----------------
|
||||
|
||||
static Future<void> setActiveSession(String sessionId) async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setString(_prefsActiveSessionKey, sessionId);
|
||||
}
|
||||
|
||||
static Future<String?> getActiveSession() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
return prefs.getString(_prefsActiveSessionKey);
|
||||
}
|
||||
|
||||
static Future<void> clearActiveSession() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.remove(_prefsActiveSessionKey);
|
||||
}
|
||||
|
||||
// ---------------- sessions ----------------
|
||||
|
||||
static Future<void> createSession(String sessionId, DateTime punchIn) async {
|
||||
final db = await _database;
|
||||
await db.insert('attendance_sessions', {
|
||||
'session_id': sessionId,
|
||||
'punch_in': punchIn.toIso8601String(),
|
||||
'punch_out': null,
|
||||
'status': 'OPEN',
|
||||
'total_km_haversine': 0,
|
||||
});
|
||||
}
|
||||
|
||||
static Future<Map<String, dynamic>?> getSession(String sessionId) async {
|
||||
final db = await _database;
|
||||
final rows = await db.query(
|
||||
'attendance_sessions',
|
||||
where: 'session_id = ?',
|
||||
whereArgs: [sessionId],
|
||||
limit: 1,
|
||||
);
|
||||
if (rows.isEmpty) return null;
|
||||
return rows.first;
|
||||
}
|
||||
|
||||
static Future<void> closeSession(
|
||||
String sessionId,
|
||||
DateTime punchOut,
|
||||
double totalKmHaversine,
|
||||
) async {
|
||||
final db = await _database;
|
||||
await db.update(
|
||||
'attendance_sessions',
|
||||
{
|
||||
'punch_out': punchOut.toIso8601String(),
|
||||
'status': 'CLOSED',
|
||||
'total_km_haversine': totalKmHaversine,
|
||||
},
|
||||
where: 'session_id = ?',
|
||||
whereArgs: [sessionId],
|
||||
);
|
||||
}
|
||||
|
||||
static Future<List<Map<String, dynamic>>> getRecentSessions(
|
||||
{int limit = 20}) async {
|
||||
final db = await _database;
|
||||
return db.query(
|
||||
'attendance_sessions',
|
||||
orderBy: 'punch_in DESC',
|
||||
limit: limit,
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------- points ----------------
|
||||
|
||||
static Future<void> insertPoint({
|
||||
required String sessionId,
|
||||
required double lat,
|
||||
required double lng,
|
||||
required double accuracy,
|
||||
required bool isMocked,
|
||||
required DateTime timestamp,
|
||||
}) async {
|
||||
final db = await _database;
|
||||
await db.insert('attendance_points', {
|
||||
'session_id': sessionId,
|
||||
'lat': lat,
|
||||
'lng': lng,
|
||||
'accuracy': accuracy,
|
||||
'is_mocked': isMocked ? 1 : 0,
|
||||
'timestamp': timestamp.toIso8601String(),
|
||||
});
|
||||
}
|
||||
|
||||
static Future<List<Map<String, dynamic>>> getPoints(
|
||||
String sessionId) async {
|
||||
final db = await _database;
|
||||
return db.query(
|
||||
'attendance_points',
|
||||
where: 'session_id = ?',
|
||||
whereArgs: [sessionId],
|
||||
orderBy: 'timestamp ASC',
|
||||
);
|
||||
}
|
||||
|
||||
static Future<int> countPoints(String sessionId) async {
|
||||
final db = await _database;
|
||||
final rows = await db.rawQuery(
|
||||
'SELECT COUNT(*) AS c FROM attendance_points WHERE session_id = ?',
|
||||
[sessionId],
|
||||
);
|
||||
return (rows.first['c'] as int?) ?? 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,281 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_foreground_task/flutter_foreground_task.dart';
|
||||
|
||||
import '../../Utils/image_constant.dart';
|
||||
import '../../Utils/size_utils.dart';
|
||||
import '../../theme/app_style.dart';
|
||||
import '../../widgets/app_bar/appbar_image.dart';
|
||||
import '../../widgets/app_bar/appbar_title.dart';
|
||||
import '../../widgets/app_bar/custom_app_bar.dart';
|
||||
import '../../widgets/custom_button.dart';
|
||||
import 'attendance_math.dart';
|
||||
import 'attendance_service.dart';
|
||||
import 'attendance_storage.dart';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Duty punch page: Punch In -> background records one GPS dot every 5 min ->
|
||||
// Punch Out -> summary (points + km). Sessions stay on the phone (sqflite).
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
class PunchScreen extends StatefulWidget {
|
||||
const PunchScreen({super.key});
|
||||
|
||||
@override
|
||||
State<PunchScreen> createState() => _PunchScreenState();
|
||||
}
|
||||
|
||||
class _PunchScreenState extends State<PunchScreen> {
|
||||
bool _punchedIn = false;
|
||||
bool _busy = false;
|
||||
String? _sessionId;
|
||||
String? _punchInTime;
|
||||
int _points = 0;
|
||||
double _km = 0;
|
||||
List<Map<String, dynamic>> _history = [];
|
||||
Timer? _clock;
|
||||
|
||||
void _onTaskData(Object data) {
|
||||
if (data is Map && mounted) {
|
||||
setState(() {
|
||||
_points = (data['points'] as num?)?.toInt() ?? _points;
|
||||
_km = (data['km'] as num?)?.toDouble() ?? _km;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
FlutterForegroundTask.addTaskDataCallback(_onTaskData);
|
||||
_refresh();
|
||||
_clock = Timer.periodic(const Duration(seconds: 30), (_) {
|
||||
if (mounted && _punchedIn) setState(() {});
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
FlutterForegroundTask.removeTaskDataCallback(_onTaskData);
|
||||
_clock?.cancel();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Future<void> _refresh() async {
|
||||
final bool open = await AttendanceService.isPunchedIn;
|
||||
final String? sid = await AttendanceStorage.getActiveSession();
|
||||
List<Map<String, dynamic>> history =
|
||||
await AttendanceStorage.getRecentSessions(limit: 10);
|
||||
int points = 0;
|
||||
double km = 0;
|
||||
String? punchIn;
|
||||
if (open && sid != null) {
|
||||
final session = await AttendanceStorage.getSession(sid);
|
||||
punchIn = session?['punch_in'] as String?;
|
||||
final pts = await AttendanceStorage.getPoints(sid);
|
||||
points = pts.length;
|
||||
km = _sumKm(pts);
|
||||
}
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_punchedIn = open;
|
||||
_sessionId = sid;
|
||||
_punchInTime = punchIn;
|
||||
_points = points;
|
||||
_km = km;
|
||||
_history = history;
|
||||
});
|
||||
}
|
||||
|
||||
double _sumKm(List<Map<String, dynamic>> pts) {
|
||||
double meters = 0;
|
||||
for (int i = 1; i < pts.length; i++) {
|
||||
meters += haversineMeters(
|
||||
(pts[i - 1]['lat'] as num).toDouble(),
|
||||
(pts[i - 1]['lng'] as num).toDouble(),
|
||||
(pts[i]['lat'] as num).toDouble(),
|
||||
(pts[i]['lng'] as num).toDouble(),
|
||||
);
|
||||
}
|
||||
return meters / 1000.0;
|
||||
}
|
||||
|
||||
Future<void> _onPunchIn() async {
|
||||
setState(() => _busy = true);
|
||||
try {
|
||||
final PermissionResult perm =
|
||||
await AttendanceService.ensurePermissions();
|
||||
if (!perm.ok) {
|
||||
_msg(perm.message, true);
|
||||
return;
|
||||
}
|
||||
if (perm.message != ' granted') _msg(perm.message, false);
|
||||
await AttendanceService.punchIn();
|
||||
if (mounted) {
|
||||
await AttendanceService.maybeAskBatteryExemption(context);
|
||||
}
|
||||
await _refresh();
|
||||
_msg('Punched in - tracking every 5 min', false);
|
||||
} catch (e) {
|
||||
_msg('Punch in failed: $e', true);
|
||||
} finally {
|
||||
if (mounted) setState(() => _busy = false);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _onPunchOut() async {
|
||||
setState(() => _busy = true);
|
||||
try {
|
||||
final Map<String, dynamic> summary = await AttendanceService.punchOut();
|
||||
await _refresh();
|
||||
if (!mounted) return;
|
||||
final double km = (summary['km'] as num).toDouble();
|
||||
final int pts = summary['points'] as int;
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (c) => AlertDialog(
|
||||
title: const Text('Duty summary'),
|
||||
content: Text(
|
||||
'Points recorded: $pts\n'
|
||||
'Distance (straight line): ${km.toStringAsFixed(2)} km\n'
|
||||
'Road distance: coming in step 4 (free API).',
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(c).pop(),
|
||||
child: const Text('OK'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
} catch (e) {
|
||||
_msg('Punch out failed: $e', true);
|
||||
} finally {
|
||||
if (mounted) setState(() => _busy = false);
|
||||
}
|
||||
}
|
||||
|
||||
void _msg(String text, bool isError) {
|
||||
if (!mounted) return;
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(text),
|
||||
backgroundColor: isError ? Colors.red : Colors.green,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: CustomAppBar(
|
||||
height: getVerticalSize(49),
|
||||
leadingWidth: 40,
|
||||
leading: AppbarImage(
|
||||
height: getSize(24),
|
||||
width: getSize(24),
|
||||
svgPath: ImageConstant.imgArrowleftBlueGray900,
|
||||
margin: getMargin(left: 16, top: 12, bottom: 13),
|
||||
onTap: () => Navigator.pop(context),
|
||||
),
|
||||
centerTitle: true,
|
||||
title: AppbarTitle(text: 'Duty Punch'),
|
||||
),
|
||||
body: SingleChildScrollView(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
_statusCard(),
|
||||
const SizedBox(height: 16),
|
||||
CustomButton(
|
||||
height: getVerticalSize(50),
|
||||
text: _busy
|
||||
? 'Please wait...'
|
||||
: (_punchedIn ? 'Punch Out' : 'Punch In'),
|
||||
margin: getMargin(top: 8, bottom: 5),
|
||||
onTap: _busy ? () {} : (_punchedIn ? _onPunchOut : _onPunchIn),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
'Keeps recording one location every 5 min, even with the app '
|
||||
'minimized. For Xiaomi/Oppo/Vivo/Samsung allow Unrestricted '
|
||||
'battery use or tracking may pause.',
|
||||
style: AppStyle.txtGilroyMedium16Bluegray900.copyWith(
|
||||
fontSize: 12,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
Text('Recent duties',
|
||||
style: AppStyle.txtGilroyMedium16Bluegray900.copyWith(
|
||||
fontWeight: FontWeight.bold,
|
||||
)),
|
||||
const SizedBox(height: 8),
|
||||
..._history.map(_historyTile),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _statusCard() {
|
||||
final Color dot = _punchedIn ? Colors.green : Colors.grey;
|
||||
return Card(
|
||||
elevation: 2,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Container(
|
||||
width: 12,
|
||||
height: 12,
|
||||
decoration:
|
||||
BoxDecoration(color: dot, shape: BoxShape.circle),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Text(
|
||||
_punchedIn ? 'Punched IN' : 'Punched OUT',
|
||||
style: const TextStyle(
|
||||
fontSize: 18, fontWeight: FontWeight.bold),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Text('Session: ${_sessionId ?? '-'}'),
|
||||
if (_punchInTime != null) Text('Since: $_punchInTime'),
|
||||
const SizedBox(height: 8),
|
||||
Text('Points: $_points',
|
||||
style:
|
||||
const TextStyle(fontSize: 16, fontWeight: FontWeight.w600)),
|
||||
Text('Distance: ${_km.toStringAsFixed(2)} km',
|
||||
style:
|
||||
const TextStyle(fontSize: 16, fontWeight: FontWeight.w600)),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _historyTile(Map<String, dynamic> s) {
|
||||
final String status = (s['status'] ?? '') as String;
|
||||
final double km = ((s['total_km_haversine'] ?? 0) as num).toDouble();
|
||||
return Card(
|
||||
child: ListTile(
|
||||
title: Text('${s['punch_in']}',
|
||||
style: const TextStyle(fontSize: 12)),
|
||||
subtitle: Text(
|
||||
'Out: ${s['punch_out'] ?? '-'} • ${km.toStringAsFixed(2)} km',
|
||||
style: const TextStyle(fontSize: 11)),
|
||||
trailing: Text(status,
|
||||
style: TextStyle(
|
||||
color: status == 'OPEN' ? Colors.green : Colors.grey,
|
||||
fontWeight: FontWeight.bold,
|
||||
)),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user