Code changes by azmat

This commit is contained in:
risnaman
2026-09-30 09:13:45 +05:30
parent c95a3f1581
commit 63ecc3e7e6
316 changed files with 28050 additions and 27216 deletions
+9
View File
@@ -7,6 +7,15 @@
# The following line activates a set of recommended lints for Flutter apps, # The following line activates a set of recommended lints for Flutter apps,
# packages, and plugins designed to encourage good coding practices. # packages, and plugins designed to encourage good coding practices.
analyzer:
exclude:
- build/**
- android/**
- ios/**
- web/**
- windows/**
- macos/**
- linux/**
include: package:flutter_lints/flutter.yaml include: package:flutter_lints/flutter.yaml
linter: linter:
+8
View File
@@ -1,4 +1,12 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"> <manifest xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Attendance tracking: foreground + background location -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_LOCATION" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
<application <application
android:label="authsec_flutter_hybrid" android:label="authsec_flutter_hybrid"
android:name="${applicationName}" android:name="${applicationName}"
+4
View File
@@ -1,3 +1,7 @@
org.gradle.jvmargs=-Xmx4G org.gradle.jvmargs=-Xmx4G
android.useAndroidX=true android.useAndroidX=true
android.enableJetifier=true android.enableJetifier=true
# This builtInKotlin flag was added automatically by Flutter migrator
android.builtInKotlin=false
# This newDsl flag was added automatically by Flutter migrator
android.newDsl=false
+1 -1
View File
@@ -2,4 +2,4 @@ distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.11.1-all.zip distributionUrl=https\://services.gradle.org/distributions/gradle-8.14-all.zip
+1 -1
View File
@@ -23,7 +23,7 @@ pluginManagement {
plugins { plugins {
id "dev.flutter.flutter-plugin-loader" version "1.0.0" id "dev.flutter.flutter-plugin-loader" version "1.0.0"
id "com.android.application" version "8.9.1" apply false id "com.android.application" version "8.11.1" apply false
id "org.jetbrains.kotlin.android" version "2.3.0" apply false id "org.jetbrains.kotlin.android" version "2.3.0" apply false
} }
+4
View File
@@ -5,6 +5,7 @@ import 'package:sqflite/sqflite.dart';
import 'package:sqflite_common_ffi/sqflite_ffi.dart'; import 'package:sqflite_common_ffi/sqflite_ffi.dart';
import 'package:sqlite3/sqlite3.dart'; import 'package:sqlite3/sqlite3.dart';
import 'screens/Attendance/attendance_service.dart';
import 'screens/splash_screen/splash_screen.dart'; import 'screens/splash_screen/splash_screen.dart';
//const simplePeriodicTask = "simplePeriodicTask"; //const simplePeriodicTask = "simplePeriodicTask";
@@ -33,6 +34,9 @@ void main() async {
databaseFactory = databaseFactoryFfi; databaseFactory = databaseFactoryFfi;
} }
// Background duty-tracking service (5-min GPS snapshots while punched in).
AttendanceService.initService();
//Request notification permissions //Request notification permissions
// await _requestNotificationPermissions(); // await _requestNotificationPermissions();
+1 -1
View File
@@ -1,3 +1,3 @@
class ApiConstants { class ApiConstants {
static const baseUrl = 'http://localhost:9292'; static const baseUrl = 'http://10.228.210.239:9292';
} }
@@ -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;
}
}
+281
View File
@@ -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,
)),
),
);
}
}
@@ -25,6 +25,7 @@ import '../../providers/token_manager.dart';
import '../../resources/api_constants.dart'; import '../../resources/api_constants.dart';
import '../../theme/app_decoration.dart'; import '../../theme/app_decoration.dart';
import '../../theme/app_style.dart'; import '../../theme/app_style.dart';
import '../Attendance/punch_screen.dart';
import '../Bookmarks/Bookmarks_entity_list_screen.dart'; import '../Bookmarks/Bookmarks_entity_list_screen.dart';
import '../Incident_Ticket/ticket_create.dart'; import '../Incident_Ticket/ticket_create.dart';
import '../LayoutReportBuilder/LayoutReportBuilder.dart'; import '../LayoutReportBuilder/LayoutReportBuilder.dart';
@@ -347,6 +348,21 @@ class _TabbedLayoutComponentState extends State<TabbedLayoutComponent> {
}, },
), ),
PopupMenuItem<String>(
child: Text(
'Duty Punch',
style: AppStyle.txtGilroySemiBold16,
),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const PunchScreen(),
),
);
},
),
// NEW MENU // NEW MENU
+16 -8
View File
@@ -462,6 +462,14 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "2.4.0" version: "2.4.0"
flutter_foreground_task:
dependency: "direct main"
description:
name: flutter_foreground_task
sha256: fc5c01a5e1b8f7bb51d0c737714f0c50440dbdf1aeddc5f8cbba313aa6fd4856
url: "https://pub.dev"
source: hosted
version: "9.2.2"
flutter_highlight: flutter_highlight:
dependency: transitive dependency: transitive
description: description:
@@ -1100,10 +1108,10 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: matcher name: matcher
sha256: "12956d0ad8390bbcc63ca2e1469c0619946ccb52809807067a7020d57e647aa6" sha256: "31bd099b47c10cd1aeb55146a2d46ce0277630ecef3f7dae54ad7873f36696cd"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "0.12.18" version: "0.12.20"
material_color_utilities: material_color_utilities:
dependency: transitive dependency: transitive
description: description:
@@ -1116,10 +1124,10 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: meta name: meta
sha256: "23f08335362185a5ea2ad3a4e597f1375e78bce8a040df5c600c8d3552ef2394" sha256: "307249ce4ff29d58a18e97f6345f539382eb9c9c29ecda628900f31de0443dd9"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "1.17.0" version: "1.19.0"
mgrs_dart: mgrs_dart:
dependency: transitive dependency: transitive
description: description:
@@ -1665,10 +1673,10 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: test_api name: test_api
sha256: "93167629bfc610f71560ab9312acdda4959de4df6fac7492c89ff0d3886f6636" sha256: "2a122cbe059f8b610d3a5415f42e255b6c17b1f21eee1d960f31080237fb4f11"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "0.7.9" version: "0.7.12"
timezone: timezone:
dependency: transitive dependency: transitive
description: description:
@@ -1801,10 +1809,10 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: vector_math name: vector_math
sha256: d530bd74fea330e6e364cda7a85019c434070188383e1cd8d9777ee586914c5b sha256: "92b9910f66ed1057fd4da7b040ae7c74cafacf885bdc81be496928d5049b032d"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "2.2.0" version: "2.4.3"
video_player: video_player:
dependency: "direct main" dependency: "direct main"
description: description:
+1
View File
@@ -88,6 +88,7 @@ dependencies:
intl: ^0.20.2 intl: ^0.20.2
sqlite3: ^3.5.2 sqlite3: ^3.5.2
connectivity_plus: ^7.3.1 connectivity_plus: ^7.3.1
flutter_foreground_task: ^9.1.0