12 Commits

Author SHA1 Message Date
redz1029 e49b52949c Fixed Edit Port Dialog on Network Map 2026-06-06 18:30:58 +08:00
redz1029 65a42039ee Enhanced Leave and Pass Slip UI/UX 2026-06-06 18:29:56 +08:00
redz1029 d813ee45a2 Network map enhancements and fixes 2026-06-05 16:42:56 +08:00
redz1029 e2ddc9a3ae Enhanced UI of IT Job Checklist 2026-06-05 10:48:53 +08:00
redz1029 5e20d14f23 Fixed attendance 2026-06-05 10:34:26 +08:00
redz1029 5d818e0d4f Enhanced APK Update Screen 2026-06-05 09:15:48 +08:00
redz1029 a91c049353 Scrollable Navigation Rail 2026-06-05 09:15:22 +08:00
redz1029 c31187ef7c Added keyboard visibility dependency 2026-06-05 07:11:18 +08:00
redz1029 1768ed7b04 Fixed custom shift type not appearing in dropdown.
Fixed inconsitent time reflection on edit.
2026-06-05 07:10:38 +08:00
redz1029 ce0be25136 Fixed IT Service Request Saving 2026-06-04 11:28:55 +08:00
redz1029 7475dbca41 Package updates 2026-06-04 07:43:46 +08:00
redz1029 f39bc2cc06 Fixed overtime checkin not showing 2026-06-04 07:43:23 +08:00
25 changed files with 5167 additions and 1679 deletions
+17 -10
View File
@@ -268,6 +268,21 @@ Future<void> main() async {
debugPrint('dotenv load failed or timed out: $e'); debugPrint('dotenv load failed or timed out: $e');
} }
// Read VAPID_KEY once at startup. trim() handles trailing whitespace / BOM
// artifacts that the .env parser may leave, which would cause isEmpty to
// return true even when the key is present with a non-empty value.
final vapidKey = kIsWeb ? (dotenv.env['VAPID_KEY']?.trim() ?? '') : '';
if (kIsWeb) {
if (vapidKey.isEmpty) {
debugPrint(
'Web FCM: VAPID_KEY not set in .env — web push notifications disabled. '
'Add VAPID_KEY=<key> from Firebase Console → Project Settings → Cloud Messaging.',
);
} else {
debugPrint('Web FCM: VAPID_KEY loaded (${vapidKey.length} chars).');
}
}
AppTime.initialize(location: 'Asia/Manila'); AppTime.initialize(location: 'Asia/Manila');
final supabaseUrl = dotenv.env['SUPABASE_URL'] ?? ''; final supabaseUrl = dotenv.env['SUPABASE_URL'] ?? '';
@@ -336,17 +351,9 @@ Future<void> main() async {
final event = data.event; final event = data.event;
// Web: register FCM token for iOS 16.4+ PWA push support. // Web: register FCM token for iOS 16.4+ PWA push support.
// Requires the VAPID key from Firebase Console → Project Settings → // vapidKey was read once at startup from dotenv — see boot sequence above.
// Cloud Messaging → Web Push certificates → Key pair.
// Add VAPID_KEY=<your_key> to your .env file.
if (kIsWeb) { if (kIsWeb) {
final vapidKey = dotenv.env['VAPID_KEY'] ?? ''; if (vapidKey.isEmpty) return; // already warned at startup
if (vapidKey.isEmpty) {
debugPrint(
'Web FCM: VAPID_KEY not set in .env — skipping token registration.',
);
return;
}
if (event == AuthChangeEvent.signedIn) { if (event == AuthChangeEvent.signedIn) {
try { try {
final token = await FirebaseMessaging.instance.getToken( final token = await FirebaseMessaging.instance.getToken(
+53
View File
@@ -1,6 +1,52 @@
import 'package:brick_offline_first_with_supabase/brick_offline_first_with_supabase.dart'; import 'package:brick_offline_first_with_supabase/brick_offline_first_with_supabase.dart';
import 'package:brick_supabase/brick_supabase.dart'; import 'package:brick_supabase/brick_supabase.dart';
enum NetworkDeviceStatus {
online,
offline,
warning,
unknown;
String get wire {
switch (this) {
case NetworkDeviceStatus.online:
return 'online';
case NetworkDeviceStatus.offline:
return 'offline';
case NetworkDeviceStatus.warning:
return 'warning';
case NetworkDeviceStatus.unknown:
return 'unknown';
}
}
String get label {
switch (this) {
case NetworkDeviceStatus.online:
return 'Online';
case NetworkDeviceStatus.offline:
return 'Offline';
case NetworkDeviceStatus.warning:
return 'Warning';
case NetworkDeviceStatus.unknown:
return 'Unknown';
}
}
static NetworkDeviceStatus fromWire(String? value) {
switch (value) {
case 'online':
return NetworkDeviceStatus.online;
case 'offline':
return NetworkDeviceStatus.offline;
case 'warning':
return NetworkDeviceStatus.warning;
default:
return NetworkDeviceStatus.unknown;
}
}
}
enum NetworkDeviceKind { enum NetworkDeviceKind {
router, router,
switchDevice, switchDevice,
@@ -173,6 +219,7 @@ class NetworkDevice extends OfflineFirstWithSupabaseModel {
final String? mac; final String? mac;
final String? locationId; final String? locationId;
final NetworkImportSource importSource; final NetworkImportSource importSource;
final NetworkDeviceStatus status;
final String? notes; final String? notes;
final DateTime createdAt; final DateTime createdAt;
final DateTime updatedAt; final DateTime updatedAt;
@@ -189,6 +236,7 @@ class NetworkDevice extends OfflineFirstWithSupabaseModel {
this.mac, this.mac,
this.locationId, this.locationId,
this.importSource = NetworkImportSource.manual, this.importSource = NetworkImportSource.manual,
this.status = NetworkDeviceStatus.unknown,
this.notes, this.notes,
required this.createdAt, required this.createdAt,
required this.updatedAt, required this.updatedAt,
@@ -207,6 +255,7 @@ class NetworkDevice extends OfflineFirstWithSupabaseModel {
mac: map['mac']?.toString(), mac: map['mac']?.toString(),
locationId: map['location_id'] as String?, locationId: map['location_id'] as String?,
importSource: NetworkImportSource.fromWire(map['import_source'] as String?), importSource: NetworkImportSource.fromWire(map['import_source'] as String?),
status: NetworkDeviceStatus.fromWire(map['status'] as String?),
notes: map['notes'] as String?, notes: map['notes'] as String?,
createdAt: createdAt:
DateTime.tryParse(map['created_at']?.toString() ?? '') ?? DateTime.now(), DateTime.tryParse(map['created_at']?.toString() ?? '') ?? DateTime.now(),
@@ -226,6 +275,7 @@ class NetworkDevice extends OfflineFirstWithSupabaseModel {
if (mac != null) 'mac': mac, if (mac != null) 'mac': mac,
if (locationId != null) 'location_id': locationId, if (locationId != null) 'location_id': locationId,
'import_source': importSource.wire, 'import_source': importSource.wire,
'status': status.wire,
if (notes != null) 'notes': notes, if (notes != null) 'notes': notes,
}; };
@@ -239,6 +289,7 @@ class NetworkDevice extends OfflineFirstWithSupabaseModel {
'mgmt_ip': mgmtIp, 'mgmt_ip': mgmtIp,
'mac': mac, 'mac': mac,
'location_id': locationId, 'location_id': locationId,
'status': status.wire,
'notes': notes, 'notes': notes,
}; };
@@ -252,6 +303,7 @@ class NetworkDevice extends OfflineFirstWithSupabaseModel {
String? mgmtIp, String? mgmtIp,
String? mac, String? mac,
String? locationId, String? locationId,
NetworkDeviceStatus? status,
String? notes, String? notes,
}) { }) {
return NetworkDevice( return NetworkDevice(
@@ -266,6 +318,7 @@ class NetworkDevice extends OfflineFirstWithSupabaseModel {
mac: mac ?? this.mac, mac: mac ?? this.mac,
locationId: locationId ?? this.locationId, locationId: locationId ?? this.locationId,
importSource: importSource, importSource: importSource,
status: status ?? this.status,
notes: notes ?? this.notes, notes: notes ?? this.notes,
createdAt: createdAt, createdAt: createdAt,
updatedAt: updatedAt, updatedAt: updatedAt,
@@ -78,6 +78,7 @@ class NetworkDevicesController {
String? mac, String? mac,
String? locationId, String? locationId,
NetworkImportSource importSource = NetworkImportSource.manual, NetworkImportSource importSource = NetworkImportSource.manual,
NetworkDeviceStatus status = NetworkDeviceStatus.unknown,
String? notes, String? notes,
}) async { }) async {
final client = ref.read(supabaseClientProvider); final client = ref.read(supabaseClientProvider);
@@ -94,6 +95,7 @@ class NetworkDevicesController {
'mac': ?mac, 'mac': ?mac,
'location_id': ?locationId, 'location_id': ?locationId,
'import_source': importSource.wire, 'import_source': importSource.wire,
'status': status.wire,
'notes': ?notes, 'notes': ?notes,
}) })
.select() .select()
File diff suppressed because it is too large Load Diff
+468 -155
View File
@@ -49,6 +49,7 @@ import '../../widgets/app_breakpoints.dart';
import '../../widgets/app_page_header.dart'; import '../../widgets/app_page_header.dart';
import '../../widgets/responsive_body.dart'; import '../../widgets/responsive_body.dart';
import '../../widgets/sync_pending_badge.dart'; import '../../widgets/sync_pending_badge.dart';
import '../../widgets/m3_card.dart';
class AttendanceScreen extends ConsumerStatefulWidget { class AttendanceScreen extends ConsumerStatefulWidget {
const AttendanceScreen({super.key}); const AttendanceScreen({super.key});
@@ -564,7 +565,7 @@ class _CheckInTabState extends ConsumerState<_CheckInTab> {
s.userId == profile.id || s.relieverIds.contains(profile.id); s.userId == profile.id || s.relieverIds.contains(profile.id);
final overlapsToday = final overlapsToday =
s.startTime.isBefore(tomorrowStart) && s.endTime.isAfter(todayStart); s.startTime.isBefore(tomorrowStart) && s.endTime.isAfter(todayStart);
return isAssigned && overlapsToday; return isAssigned && overlapsToday && s.shiftType != 'overtime';
}).toList(); }).toList();
// Find active attendance log (checked in but not out) // Find active attendance log (checked in but not out)
@@ -1593,7 +1594,15 @@ class _CheckInTabState extends ConsumerState<_CheckInTab> {
} }
} catch (e) { } catch (e) {
if (mounted) { if (mounted) {
showErrorSnackBar(context, 'Overtime check-in failed: $e'); final msg = e.toString();
final friendly = msg.contains('Outside geofence')
? 'You are outside the geofence area.'
: msg.contains('Not authenticated')
? 'Session expired. Please log in again.'
: msg.contains('no candidate')
? 'Overtime check-in is temporarily unavailable. Please try again.'
: 'Overtime check-in failed. Please try again.';
showErrorSnackBar(context, friendly);
} }
} finally { } finally {
if (mounted) setState(() => _loading = false); if (mounted) setState(() => _loading = false);
@@ -5623,8 +5632,9 @@ class _PassSlipTabState extends ConsumerState<_PassSlipTab> {
cardTitle = 'Active Pass Slip'; cardTitle = 'Active Pass Slip';
} }
return Card( return M3Card.elevated(
color: cardColor, color: cardColor,
margin: EdgeInsets.zero,
child: Padding( child: Padding(
padding: const EdgeInsets.all(16), padding: const EdgeInsets.all(16),
child: Column( child: Column(
@@ -5632,8 +5642,12 @@ class _PassSlipTabState extends ConsumerState<_PassSlipTab> {
children: [ children: [
Row( Row(
children: [ children: [
Icon(cardIcon, color: onCardColor), CircleAvatar(
const SizedBox(width: 8), radius: 18,
backgroundColor: onCardColor.withValues(alpha: 0.15),
child: Icon(cardIcon, color: onCardColor, size: 18),
),
const SizedBox(width: 12),
Expanded( Expanded(
child: Text( child: Text(
cardTitle, cardTitle,
@@ -5645,16 +5659,26 @@ class _PassSlipTabState extends ConsumerState<_PassSlipTab> {
), ),
], ],
), ),
const SizedBox(height: 8), const SizedBox(height: 10),
Text( Text(
'Reason: ${activeSlip.reason}', activeSlip.reason,
style: theme.textTheme.bodyMedium, style: theme.textTheme.bodyMedium?.copyWith(color: onCardColor),
), ),
if (activeSlip.slipStart != null && hasStarted) if (activeSlip.slipStart != null && hasStarted) ...[
const SizedBox(height: 4),
Row(
children: [
Icon(Icons.schedule, size: 14, color: onCardColor.withValues(alpha: 0.7)),
const SizedBox(width: 4),
Text( Text(
'Started: ${AppTime.formatTime(activeSlip.slipStart!)}', 'Started: ${AppTime.formatTime(activeSlip.slipStart!)}',
style: theme.textTheme.bodySmall, style: theme.textTheme.bodySmall?.copyWith(
color: onCardColor.withValues(alpha: 0.85),
), ),
),
],
),
],
const SizedBox(height: 12), const SizedBox(height: 12),
SizedBox( SizedBox(
width: double.infinity, width: double.infinity,
@@ -5662,7 +5686,7 @@ class _PassSlipTabState extends ConsumerState<_PassSlipTab> {
onPressed: _submitting onPressed: _submitting
? null ? null
: () => _completeSlip(activeSlip.id), : () => _completeSlip(activeSlip.id),
icon: const Icon(Icons.check), icon: const Icon(Icons.check_circle_outline),
label: const Text('Complete / Return'), label: const Text('Complete / Return'),
), ),
), ),
@@ -5678,12 +5702,25 @@ class _PassSlipTabState extends ConsumerState<_PassSlipTab> {
// Pending slips for admin approval // Pending slips for admin approval
if (isAdmin) ...[ if (isAdmin) ...[
Row(
children: [
Container(
width: 4,
height: 20,
decoration: BoxDecoration(
color: colors.tertiary,
borderRadius: BorderRadius.circular(2),
),
),
const SizedBox(width: 10),
Text( Text(
'Pending Approvals', 'Pending Approvals',
style: theme.textTheme.titleMedium?.copyWith( style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w600, fontWeight: FontWeight.w600,
), ),
), ),
],
),
const SizedBox(height: 8), const SizedBox(height: 8),
for (int i = 0; i < pendingSlipList.length; i++) for (int i = 0; i < pendingSlipList.length; i++)
M3FadeSlideIn( M3FadeSlideIn(
@@ -5698,24 +5735,43 @@ class _PassSlipTabState extends ConsumerState<_PassSlipTab> {
), ),
if (pendingSlipList.isEmpty) if (pendingSlipList.isEmpty)
Padding( Padding(
padding: const EdgeInsets.symmetric(vertical: 8), padding: const EdgeInsets.symmetric(vertical: 12),
child: Text( child: Row(
children: [
Icon(Icons.inbox_outlined, size: 20, color: colors.onSurfaceVariant),
const SizedBox(width: 8),
Text(
'No pending pass slip requests.', 'No pending pass slip requests.',
style: theme.textTheme.bodyMedium?.copyWith( style: theme.textTheme.bodyMedium?.copyWith(
color: colors.onSurfaceVariant, color: colors.onSurfaceVariant,
), ),
), ),
],
),
), ),
const SizedBox(height: 16), const SizedBox(height: 16),
], ],
// History // History
Row(
children: [
Container(
width: 4,
height: 20,
decoration: BoxDecoration(
color: colors.outlineVariant,
borderRadius: BorderRadius.circular(2),
),
),
const SizedBox(width: 10),
Text( Text(
'Pass Slip History', 'Pass Slip History',
style: theme.textTheme.titleMedium?.copyWith( style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w600, fontWeight: FontWeight.w600,
), ),
), ),
],
),
const SizedBox(height: 8), const SizedBox(height: 8),
for (int i = 0; i < historySlipList.length; i++) for (int i = 0; i < historySlipList.length; i++)
M3FadeSlideIn( M3FadeSlideIn(
@@ -5731,13 +5787,23 @@ class _PassSlipTabState extends ConsumerState<_PassSlipTab> {
if (slips.isEmpty) if (slips.isEmpty)
Center( Center(
child: Padding( child: Padding(
padding: const EdgeInsets.symmetric(vertical: 24), padding: const EdgeInsets.symmetric(vertical: 32),
child: Text( child: Column(
children: [
Icon(
Icons.receipt_long_outlined,
size: 48,
color: colors.onSurfaceVariant.withValues(alpha: 0.5),
),
const SizedBox(height: 12),
Text(
'No pass slip records.', 'No pass slip records.',
style: theme.textTheme.bodyMedium?.copyWith( style: theme.textTheme.bodyMedium?.copyWith(
color: colors.onSurfaceVariant, color: colors.onSurfaceVariant,
), ),
), ),
],
),
), ),
), ),
], ],
@@ -5761,20 +5827,25 @@ class _PassSlipTabState extends ConsumerState<_PassSlipTab> {
final name = p?.fullName ?? slip.userId; final name = p?.fullName ?? slip.userId;
Color statusColor; Color statusColor;
IconData statusIcon;
switch (slip.status) { switch (slip.status) {
case 'approved': case 'approved':
statusColor = Colors.green; statusColor = Colors.green;
statusIcon = Icons.check_circle;
case 'rejected': case 'rejected':
statusColor = colors.error; statusColor = colors.error;
statusIcon = Icons.cancel;
case 'completed': case 'completed':
statusColor = colors.primary; statusColor = colors.primary;
statusIcon = Icons.task_alt;
default: default:
statusColor = Colors.orange; statusColor = Colors.orange;
statusIcon = Icons.hourglass_top;
} }
return Padding( return Padding(
padding: const EdgeInsets.only(bottom: 8), padding: const EdgeInsets.only(bottom: 8),
child: Card( child: M3Card.outlined(
child: Padding( child: Padding(
padding: const EdgeInsets.all(12), padding: const EdgeInsets.all(12),
child: Column( child: Column(
@@ -5782,69 +5853,97 @@ class _PassSlipTabState extends ConsumerState<_PassSlipTab> {
children: [ children: [
Row( Row(
children: [ children: [
Expanded(child: Text(name, style: theme.textTheme.titleSmall)), Expanded(
child: Text(
name,
style: theme.textTheme.titleSmall?.copyWith(fontWeight: FontWeight.w600),
),
),
if (isPending) ...[ if (isPending) ...[
SyncPendingBadge(isPending: true, compact: true), SyncPendingBadge(isPending: true, compact: true),
const SizedBox(width: 8), const SizedBox(width: 8),
], ],
Container( Container(
padding: const EdgeInsets.symmetric( padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
horizontal: 10,
vertical: 4,
),
decoration: BoxDecoration( decoration: BoxDecoration(
color: statusColor.withValues(alpha: 0.15), color: statusColor.withValues(alpha: 0.12),
borderRadius: BorderRadius.circular(12), borderRadius: BorderRadius.circular(20),
), ),
child: Text( child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(statusIcon, size: 12, color: statusColor),
const SizedBox(width: 4),
Text(
slip.status.toUpperCase(), slip.status.toUpperCase(),
style: theme.textTheme.labelSmall?.copyWith( style: theme.textTheme.labelSmall?.copyWith(
color: statusColor, color: statusColor,
fontWeight: FontWeight.w600, fontWeight: FontWeight.w600,
), ),
), ),
],
),
), ),
], ],
), ),
const SizedBox(height: 4), const SizedBox(height: 6),
Text(slip.reason, style: theme.textTheme.bodyMedium), Text(slip.reason, style: theme.textTheme.bodyMedium),
const SizedBox(height: 4),
Row(
children: [
Icon(Icons.schedule, size: 13, color: colors.onSurfaceVariant),
const SizedBox(width: 4),
Text( Text(
'Requested: ${AppTime.formatDate(slip.requestedAt)} ${AppTime.formatTime(slip.requestedAt)}', 'Requested: ${AppTime.formatDate(slip.requestedAt)} ${AppTime.formatTime(slip.requestedAt)}',
style: theme.textTheme.bodySmall?.copyWith( style: theme.textTheme.bodySmall?.copyWith(color: colors.onSurfaceVariant),
color: colors.onSurfaceVariant,
), ),
],
), ),
if (slip.requestedStart != null) if (slip.requestedStart != null) ...[
const SizedBox(height: 2),
Row(
children: [
Icon(Icons.alarm, size: 13, color: colors.onSurfaceVariant),
const SizedBox(width: 4),
Text( Text(
'Preferred start: ${AppTime.formatTime(slip.requestedStart!)}', 'Preferred start: ${AppTime.formatTime(slip.requestedStart!)}',
style: theme.textTheme.bodySmall?.copyWith( style: theme.textTheme.bodySmall?.copyWith(color: colors.onSurfaceVariant),
color: colors.onSurfaceVariant,
), ),
],
), ),
if (slip.slipStart != null) ],
if (slip.slipStart != null) ...[
const SizedBox(height: 2),
Row(
children: [
Icon(Icons.directions_walk, size: 13, color: colors.onSurfaceVariant),
const SizedBox(width: 4),
Text( Text(
'Started: ${AppTime.formatTime(slip.slipStart!)}' 'Started: ${AppTime.formatTime(slip.slipStart!)}'
'${slip.slipEnd != null ? " · Ended: ${AppTime.formatTime(slip.slipEnd!)}" : ""}', '${slip.slipEnd != null ? " · Ended: ${AppTime.formatTime(slip.slipEnd!)}" : ""}',
style: theme.textTheme.bodySmall?.copyWith( style: theme.textTheme.bodySmall?.copyWith(color: colors.onSurfaceVariant),
color: colors.onSurfaceVariant,
), ),
],
), ),
],
if (showActions && slip.status == 'pending') ...[ if (showActions && slip.status == 'pending') ...[
const SizedBox(height: 8), const SizedBox(height: 10),
Row( Row(
mainAxisAlignment: MainAxisAlignment.end, mainAxisAlignment: MainAxisAlignment.end,
children: [ children: [
TextButton( OutlinedButton.icon(
onPressed: _submitting ? null : () => _rejectSlip(slip.id), onPressed: _submitting ? null : () => _rejectSlip(slip.id),
child: Text( icon: Icon(Icons.close, size: 16, color: colors.error),
'Reject', label: Text('Reject', style: TextStyle(color: colors.error)),
style: TextStyle(color: colors.error), style: OutlinedButton.styleFrom(
side: BorderSide(color: colors.error.withValues(alpha: 0.5)),
), ),
), ),
const SizedBox(width: 8), const SizedBox(width: 8),
FilledButton( FilledButton.icon(
onPressed: _submitting ? null : () => _approveSlip(slip.id), onPressed: _submitting ? null : () => _approveSlip(slip.id),
child: const Text('Approve'), icon: const Icon(Icons.check, size: 16),
label: const Text('Approve'),
), ),
], ],
), ),
@@ -5968,22 +6067,41 @@ class _LeaveTabState extends ConsumerState<_LeaveTab> {
children: [ children: [
// Pending Approvals (admin only) // Pending Approvals (admin only)
if (isAdmin) ...[ if (isAdmin) ...[
Row(
children: [
Container(
width: 4,
height: 20,
decoration: BoxDecoration(
color: colors.tertiary,
borderRadius: BorderRadius.circular(2),
),
),
const SizedBox(width: 10),
Text( Text(
'Pending Approvals', 'Pending Approvals',
style: theme.textTheme.titleMedium?.copyWith( style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w600, fontWeight: FontWeight.w600,
), ),
), ),
],
),
const SizedBox(height: 8), const SizedBox(height: 8),
if (pendingApprovals.isEmpty) if (pendingApprovals.isEmpty)
Padding( Padding(
padding: const EdgeInsets.symmetric(vertical: 8), padding: const EdgeInsets.symmetric(vertical: 12),
child: Text( child: Row(
children: [
Icon(Icons.inbox_outlined, size: 20, color: colors.onSurfaceVariant),
const SizedBox(width: 8),
Text(
'No pending leave requests.', 'No pending leave requests.',
style: theme.textTheme.bodyMedium?.copyWith( style: theme.textTheme.bodyMedium?.copyWith(
color: colors.onSurfaceVariant, color: colors.onSurfaceVariant,
), ),
), ),
],
),
), ),
for (int i = 0; i < pendingApprovals.length; i++) for (int i = 0; i < pendingApprovals.length; i++)
M3FadeSlideIn( M3FadeSlideIn(
@@ -6000,23 +6118,46 @@ class _LeaveTabState extends ConsumerState<_LeaveTab> {
], ],
// My Leave Applications // My Leave Applications
Row(
children: [
Container(
width: 4,
height: 20,
decoration: BoxDecoration(
color: colors.secondary,
borderRadius: BorderRadius.circular(2),
),
),
const SizedBox(width: 10),
Text( Text(
'My Leave Applications', 'My Leave Applications',
style: theme.textTheme.titleMedium?.copyWith( style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w600, fontWeight: FontWeight.w600,
), ),
), ),
],
),
const SizedBox(height: 8), const SizedBox(height: 8),
if (myLeaves.isEmpty) if (myLeaves.isEmpty)
Center( Center(
child: Padding( child: Padding(
padding: const EdgeInsets.symmetric(vertical: 24), padding: const EdgeInsets.symmetric(vertical: 32),
child: Text( child: Column(
children: [
Icon(
Icons.event_note_outlined,
size: 48,
color: colors.onSurfaceVariant.withValues(alpha: 0.5),
),
const SizedBox(height: 12),
Text(
'You have no leave applications.', 'You have no leave applications.',
style: theme.textTheme.bodyMedium?.copyWith( style: theme.textTheme.bodyMedium?.copyWith(
color: colors.onSurfaceVariant, color: colors.onSurfaceVariant,
), ),
), ),
],
),
), ),
), ),
for (int i = 0; i < myLeavesList.length; i++) for (int i = 0; i < myLeavesList.length; i++)
@@ -6034,12 +6175,25 @@ class _LeaveTabState extends ConsumerState<_LeaveTab> {
// All Leave History (admin only) // All Leave History (admin only)
if (isAdmin) ...[ if (isAdmin) ...[
const SizedBox(height: 24), const SizedBox(height: 24),
Row(
children: [
Container(
width: 4,
height: 20,
decoration: BoxDecoration(
color: colors.outlineVariant,
borderRadius: BorderRadius.circular(2),
),
),
const SizedBox(width: 10),
Text( Text(
'All Leave History', 'All Leave History',
style: theme.textTheme.titleMedium?.copyWith( style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w600, fontWeight: FontWeight.w600,
), ),
), ),
],
),
const SizedBox(height: 8), const SizedBox(height: 8),
for (int i = 0; i < allLeaveHistory.length; i++) for (int i = 0; i < allLeaveHistory.length; i++)
M3FadeSlideIn( M3FadeSlideIn(
@@ -6054,13 +6208,19 @@ class _LeaveTabState extends ConsumerState<_LeaveTab> {
), ),
if (allLeaveHistory.isEmpty) if (allLeaveHistory.isEmpty)
Padding( Padding(
padding: const EdgeInsets.symmetric(vertical: 8), padding: const EdgeInsets.symmetric(vertical: 12),
child: Text( child: Row(
children: [
Icon(Icons.history_outlined, size: 20, color: colors.onSurfaceVariant),
const SizedBox(width: 8),
Text(
'No leave history from other staff.', 'No leave history from other staff.',
style: theme.textTheme.bodyMedium?.copyWith( style: theme.textTheme.bodyMedium?.copyWith(
color: colors.onSurfaceVariant, color: colors.onSurfaceVariant,
), ),
), ),
],
),
), ),
], ],
const SizedBox(height: 80), const SizedBox(height: 80),
@@ -6085,20 +6245,35 @@ class _LeaveTabState extends ConsumerState<_LeaveTab> {
final name = p?.fullName ?? leave.userId; final name = p?.fullName ?? leave.userId;
Color statusColor; Color statusColor;
IconData statusIcon;
switch (leave.status) { switch (leave.status) {
case 'approved': case 'approved':
statusColor = Colors.teal; statusColor = Colors.teal;
statusIcon = Icons.check_circle;
case 'rejected': case 'rejected':
statusColor = colors.error; statusColor = colors.error;
statusIcon = Icons.cancel;
case 'cancelled': case 'cancelled':
statusColor = colors.onSurfaceVariant; statusColor = colors.onSurfaceVariant;
statusIcon = Icons.remove_circle_outline;
default: default:
statusColor = Colors.orange; statusColor = Colors.orange;
statusIcon = Icons.hourglass_top;
} }
const leaveTypeMeta = {
'emergency_leave': (Icons.warning_amber_rounded, Color(0xFFE65100)),
'parental_leave': (Icons.child_care_rounded, Color(0xFFAD1457)),
'sick_leave': (Icons.local_hospital_rounded, Color(0xFFC62828)),
'vacation_leave': (Icons.beach_access_rounded, Color(0xFF00695C)),
};
final meta = leaveTypeMeta[leave.leaveType];
final typeIcon = meta?.$1 ?? Icons.event_note;
final typeColor = meta?.$2 ?? colors.primary;
return Padding( return Padding(
padding: const EdgeInsets.only(bottom: 8), padding: const EdgeInsets.only(bottom: 8),
child: Card( child: M3Card.outlined(
child: Padding( child: Padding(
padding: const EdgeInsets.all(12), padding: const EdgeInsets.all(12),
child: Column( child: Column(
@@ -6106,81 +6281,113 @@ class _LeaveTabState extends ConsumerState<_LeaveTab> {
children: [ children: [
Row( Row(
children: [ children: [
Expanded(child: Text(name, style: theme.textTheme.titleSmall)), Expanded(
child: Text(
name,
style: theme.textTheme.titleSmall?.copyWith(fontWeight: FontWeight.w600),
),
),
if (isPending) ...[ if (isPending) ...[
SyncPendingBadge(isPending: true, compact: true), SyncPendingBadge(isPending: true, compact: true),
const SizedBox(width: 8), const SizedBox(width: 8),
], ],
Container( Container(
padding: const EdgeInsets.symmetric( padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
horizontal: 10,
vertical: 4,
),
decoration: BoxDecoration( decoration: BoxDecoration(
color: statusColor.withValues(alpha: 0.15), color: statusColor.withValues(alpha: 0.12),
borderRadius: BorderRadius.circular(12), borderRadius: BorderRadius.circular(20),
), ),
child: Text( child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(statusIcon, size: 12, color: statusColor),
const SizedBox(width: 4),
Text(
leave.status.toUpperCase(), leave.status.toUpperCase(),
style: theme.textTheme.labelSmall?.copyWith( style: theme.textTheme.labelSmall?.copyWith(
color: statusColor, color: statusColor,
fontWeight: FontWeight.w600, fontWeight: FontWeight.w600,
), ),
), ),
],
),
), ),
], ],
), ),
const SizedBox(height: 4), const SizedBox(height: 8),
Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
decoration: BoxDecoration(
color: typeColor.withValues(alpha: 0.10),
borderRadius: BorderRadius.circular(20),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(typeIcon, size: 13, color: typeColor),
const SizedBox(width: 5),
Text( Text(
leave.leaveTypeLabel, leave.leaveTypeLabel,
style: theme.textTheme.bodyMedium?.copyWith( style: theme.textTheme.labelSmall?.copyWith(
fontWeight: FontWeight.w500, color: typeColor,
fontWeight: FontWeight.w600,
), ),
), ),
],
),
),
const SizedBox(height: 6),
Text(leave.justification, style: theme.textTheme.bodyMedium), Text(leave.justification, style: theme.textTheme.bodyMedium),
Text( const SizedBox(height: 4),
Row(
children: [
Icon(Icons.calendar_month, size: 13, color: colors.onSurfaceVariant),
const SizedBox(width: 4),
Expanded(
child: Text(
'${AppTime.formatDate(leave.startTime)} ' '${AppTime.formatDate(leave.startTime)} '
'${AppTime.formatTime(leave.startTime)} ' '${AppTime.formatTime(leave.startTime)} '
'${AppTime.formatTime(leave.endTime)}', '${AppTime.formatTime(leave.endTime)}',
style: theme.textTheme.bodySmall?.copyWith( style: theme.textTheme.bodySmall?.copyWith(color: colors.onSurfaceVariant),
color: colors.onSurfaceVariant,
), ),
), ),
],
),
// Approve / Reject for admins on pending leaves // Approve / Reject for admins on pending leaves
if (showApproval && leave.status == 'pending') ...[ if (showApproval && leave.status == 'pending') ...[
const SizedBox(height: 8), const SizedBox(height: 10),
Row( Row(
mainAxisAlignment: MainAxisAlignment.end, mainAxisAlignment: MainAxisAlignment.end,
children: [ children: [
TextButton( OutlinedButton.icon(
onPressed: _submitting onPressed: _submitting ? null : () => _rejectLeave(leave.id),
? null icon: Icon(Icons.close, size: 16, color: colors.error),
: () => _rejectLeave(leave.id), label: Text('Reject', style: TextStyle(color: colors.error)),
child: Text( style: OutlinedButton.styleFrom(
'Reject', side: BorderSide(color: colors.error.withValues(alpha: 0.5)),
style: TextStyle(color: colors.error),
), ),
), ),
const SizedBox(width: 8), const SizedBox(width: 8),
FilledButton( FilledButton.icon(
onPressed: _submitting onPressed: _submitting ? null : () => _approveLeave(leave.id),
? null icon: const Icon(Icons.check, size: 16),
: () => _approveLeave(leave.id), label: const Text('Approve'),
child: const Text('Approve'),
), ),
], ],
), ),
], ],
// Cancel future approved leaves: // Cancel future approved leaves
// - user can cancel own
// - admin can cancel anyone
if (!showApproval && _canCancelFutureApproved(leave)) ...[ if (!showApproval && _canCancelFutureApproved(leave)) ...[
const SizedBox(height: 8), const SizedBox(height: 8),
Align( Align(
alignment: Alignment.centerRight, alignment: Alignment.centerRight,
child: TextButton( child: OutlinedButton.icon(
onPressed: _submitting ? null : () => _cancelLeave(leave.id), onPressed: _submitting ? null : () => _cancelLeave(leave.id),
child: Text('Cancel', style: TextStyle(color: colors.error)), icon: Icon(Icons.event_busy, size: 16, color: colors.error),
label: Text('Cancel Leave', style: TextStyle(color: colors.error)),
style: OutlinedButton.styleFrom(
side: BorderSide(color: colors.error.withValues(alpha: 0.5)),
),
), ),
), ),
], ],
@@ -6387,12 +6594,26 @@ class _PassSlipDialogState extends ConsumerState<_PassSlipDialog> {
Widget build(BuildContext context) { Widget build(BuildContext context) {
final theme = Theme.of(context); final theme = Theme.of(context);
final colors = theme.colorScheme;
final content = Column( final content = Column(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
Text('Request Pass Slip', style: theme.textTheme.headlineSmall), Row(
const SizedBox(height: 16), children: [
CircleAvatar(
radius: 22,
backgroundColor: colors.tertiaryContainer,
child: Icon(Icons.receipt_long, color: colors.onTertiaryContainer, size: 22),
),
const SizedBox(width: 14),
Expanded(
child: Text('Request Pass Slip', style: theme.textTheme.headlineSmall),
),
],
),
const SizedBox(height: 20),
Row( Row(
children: [ children: [
Expanded( Expanded(
@@ -6425,8 +6646,7 @@ class _PassSlipDialogState extends ConsumerState<_PassSlipDialog> {
], ],
), ),
const SizedBox(height: 16), const SizedBox(height: 16),
InkWell( M3Card.outlined(
borderRadius: BorderRadius.circular(12),
onTap: _submitting onTap: _submitting
? null ? null
: () async { : () async {
@@ -6438,33 +6658,44 @@ class _PassSlipDialogState extends ConsumerState<_PassSlipDialog> {
setState(() => _requestedStartTime = picked); setState(() => _requestedStartTime = picked);
} }
}, },
child: InputDecorator( child: Padding(
decoration: InputDecoration( padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
labelText: 'Preferred start time (optional)', child: Row(
border: OutlineInputBorder( children: [
borderRadius: BorderRadius.circular(12), Icon(Icons.schedule, color: colors.primary, size: 20),
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Preferred start time (optional)',
style: theme.textTheme.labelSmall?.copyWith(
color: colors.onSurfaceVariant,
), ),
prefixIcon: const Icon(Icons.schedule),
suffixIcon: _requestedStartTime != null
? IconButton(
icon: const Icon(Icons.clear),
onPressed: _submitting
? null
: () => setState(() => _requestedStartTime = null),
tooltip: 'Clear',
)
: null,
), ),
child: Text( const SizedBox(height: 2),
Text(
_requestedStartTime != null _requestedStartTime != null
? _requestedStartTime!.format(context) ? _requestedStartTime!.format(context)
: 'Immediately upon approval', : 'Immediately upon approval',
style: theme.textTheme.bodyLarge?.copyWith( style: theme.textTheme.bodyMedium?.copyWith(
color: _requestedStartTime != null color: _requestedStartTime != null ? null : colors.onSurfaceVariant,
? null
: theme.colorScheme.onSurfaceVariant,
), ),
), ),
],
),
),
if (_requestedStartTime != null)
IconButton(
icon: const Icon(Icons.clear, size: 18),
onPressed: _submitting ? null : () => setState(() => _requestedStartTime = null),
tooltip: 'Clear',
visualDensity: VisualDensity.compact,
padding: EdgeInsets.zero,
),
],
),
), ),
), ),
const SizedBox(height: 24), const SizedBox(height: 24),
@@ -6476,15 +6707,16 @@ class _PassSlipDialogState extends ConsumerState<_PassSlipDialog> {
child: const Text('Cancel'), child: const Text('Cancel'),
), ),
const SizedBox(width: 8), const SizedBox(width: 8),
FilledButton( FilledButton.icon(
onPressed: _submitting ? null : _submit, onPressed: _submitting ? null : _submit,
child: _submitting icon: _submitting
? const SizedBox( ? const SizedBox(
width: 16, width: 16,
height: 16, height: 16,
child: CircularProgressIndicator(strokeWidth: 2), child: CircularProgressIndicator(strokeWidth: 2),
) )
: const Text('Submit'), : const Icon(Icons.send, size: 18),
label: const Text('Submit'),
), ),
], ],
), ),
@@ -6677,65 +6909,133 @@ class _FileLeaveDialogState extends ConsumerState<_FileLeaveDialog> {
final theme = Theme.of(context); final theme = Theme.of(context);
final colors = theme.colorScheme; final colors = theme.colorScheme;
const leaveTypeMeta = {
'emergency_leave': (Icons.warning_amber_rounded, Color(0xFFE65100)),
'parental_leave': (Icons.child_care_rounded, Color(0xFFAD1457)),
'sick_leave': (Icons.local_hospital_rounded, Color(0xFFC62828)),
'vacation_leave': (Icons.beach_access_rounded, Color(0xFF00695C)),
};
final content = Column( final content = Column(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
Text('File Leave of Absence', style: theme.textTheme.headlineSmall),
const SizedBox(height: 16),
// Leave type
DropdownButtonFormField<String>(
// ignore: deprecated_member_use
value: _leaveType,
decoration: const InputDecoration(labelText: 'Leave Type'),
items: _leaveTypes.entries
.map((e) => DropdownMenuItem(value: e.key, child: Text(e.value)))
.toList(),
onChanged: (v) {
if (v != null) setState(() => _leaveType = v);
},
),
const SizedBox(height: 12),
// Date picker
ListTile(
contentPadding: EdgeInsets.zero,
leading: const Icon(Icons.calendar_today),
title: Text(
_startDate == null ? 'Select Date' : AppTime.formatDate(_startDate!),
),
subtitle: const Text('Current or future dates only'),
onTap: _pickDate,
),
// Time range
Row( Row(
children: [ children: [
CircleAvatar(
radius: 22,
backgroundColor: colors.secondaryContainer,
child: Icon(Icons.event_busy, color: colors.onSecondaryContainer, size: 22),
),
const SizedBox(width: 14),
Expanded( Expanded(
child: ListTile( child: Text('File Leave of Absence', style: theme.textTheme.headlineSmall),
contentPadding: EdgeInsets.zero,
leading: const Icon(Icons.access_time),
title: Text(_startTime == null ? 'Start Time' : _startTime!.format(context)),
onTap: _pickStartTime,
), ),
],
), ),
const Padding( const SizedBox(height: 20),
padding: EdgeInsets.symmetric(horizontal: 8),
child: Icon(Icons.arrow_forward), // Leave type chips
Text(
'Leave Type',
style: theme.textTheme.labelMedium?.copyWith(color: colors.onSurfaceVariant),
), ),
const SizedBox(height: 8),
Wrap(
spacing: 8,
runSpacing: 8,
children: _leaveTypes.entries.map((e) {
final meta = leaveTypeMeta[e.key];
final typeIcon = meta?.$1 ?? Icons.event_note;
final typeColor = meta?.$2 ?? colors.primary;
final isSelected = _leaveType == e.key;
return ChoiceChip(
avatar: Icon(
typeIcon,
size: 16,
color: isSelected ? colors.onPrimaryContainer : typeColor,
),
label: Text(e.value),
selected: isSelected,
selectedColor: colors.primaryContainer,
onSelected: (_) => setState(() => _leaveType = e.key),
);
}).toList(),
),
const SizedBox(height: 16),
// Date picker card
M3Card.outlined(
onTap: _pickDate,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
child: Row(
children: [
Icon(Icons.calendar_today, color: colors.primary, size: 20),
const SizedBox(width: 12),
Expanded( Expanded(
child: ListTile( child: Column(
contentPadding: EdgeInsets.zero, crossAxisAlignment: CrossAxisAlignment.start,
leading: const Icon(Icons.access_time), children: [
title: Text(_endTime == null ? 'End Time' : _endTime!.format(context)), Text(
subtitle: const Text('From shift schedule'), 'Date',
onTap: _pickEndTime, style: theme.textTheme.labelSmall?.copyWith(color: colors.onSurfaceVariant),
),
const SizedBox(height: 2),
Text(
_startDate == null ? 'Select date' : AppTime.formatDate(_startDate!),
style: theme.textTheme.bodyMedium?.copyWith(
color: _startDate == null ? colors.onSurfaceVariant : null,
), ),
), ),
], ],
), ),
const SizedBox(height: 12), ),
Icon(Icons.chevron_right, size: 18, color: colors.onSurfaceVariant),
],
),
),
),
const SizedBox(height: 10),
// Time range buttons
Row(
children: [
Expanded(
child: OutlinedButton.icon(
onPressed: _pickStartTime,
icon: Icon(Icons.access_time, size: 16, color: colors.primary),
label: Text(
_startTime == null ? 'Start Time' : _startTime!.format(context),
style: theme.textTheme.bodyMedium,
),
style: OutlinedButton.styleFrom(
alignment: Alignment.centerLeft,
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 14),
),
),
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 8),
child: Icon(Icons.arrow_forward, size: 16, color: colors.onSurfaceVariant),
),
Expanded(
child: OutlinedButton.icon(
onPressed: _pickEndTime,
icon: Icon(Icons.access_time, size: 16, color: colors.primary),
label: Text(
_endTime == null ? 'End Time' : _endTime!.format(context),
style: theme.textTheme.bodyMedium,
),
style: OutlinedButton.styleFrom(
alignment: Alignment.centerLeft,
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 14),
),
),
),
],
),
const SizedBox(height: 16),
// Justification with AI // Justification with AI
Row( Row(
@@ -6771,14 +7071,27 @@ class _FileLeaveDialogState extends ConsumerState<_FileLeaveDialog> {
), ),
const SizedBox(height: 16), const SizedBox(height: 16),
if (widget.isAdmin) if (widget.isAdmin) ...[
Padding( M3Card.filled(
padding: const EdgeInsets.only(bottom: 8), color: colors.primaryContainer,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),
child: Row(
children: [
Icon(Icons.verified_user, size: 16, color: colors.onPrimaryContainer),
const SizedBox(width: 8),
Expanded(
child: Text( child: Text(
'As admin, your leave will be auto-approved.', 'Your leave will be auto-approved.',
style: theme.textTheme.bodySmall?.copyWith(color: colors.primary), style: theme.textTheme.bodySmall?.copyWith(color: colors.onPrimaryContainer),
), ),
), ),
],
),
),
),
const SizedBox(height: 12),
],
// Actions // Actions
Row( Row(
@@ -39,6 +39,7 @@ class _NetworkMapDeviceEditScreenState
final _notesCtrl = TextEditingController(); final _notesCtrl = TextEditingController();
NetworkDeviceKind _kind = NetworkDeviceKind.switchDevice; NetworkDeviceKind _kind = NetworkDeviceKind.switchDevice;
NetworkDeviceRole? _role; NetworkDeviceRole? _role;
NetworkDeviceStatus _status = NetworkDeviceStatus.unknown;
String? _siteId; String? _siteId;
String? _locationId; String? _locationId;
bool _saving = false; bool _saving = false;
@@ -67,7 +68,7 @@ class _NetworkMapDeviceEditScreenState
_notesCtrl.text = d.notes ?? ''; _notesCtrl.text = d.notes ?? '';
_kind = d.kind; _kind = d.kind;
_role = d.role; _role = d.role;
// Resolve the device's location → its site for the pickers. _status = d.status;
if (d.locationId != null) { if (d.locationId != null) {
_locationId = d.locationId; _locationId = d.locationId;
for (final l in locations) { for (final l in locations) {
@@ -179,6 +180,7 @@ class _NetworkMapDeviceEditScreenState
name: _nameCtrl.text.trim(), name: _nameCtrl.text.trim(),
kind: _kind, kind: _kind,
role: _role, role: _role,
status: _status,
vendor: _vendorCtrl.text.trim().isEmpty ? null : _vendorCtrl.text.trim(), vendor: _vendorCtrl.text.trim().isEmpty ? null : _vendorCtrl.text.trim(),
model: _modelCtrl.text.trim().isEmpty ? null : _modelCtrl.text.trim(), model: _modelCtrl.text.trim().isEmpty ? null : _modelCtrl.text.trim(),
serial: _serialCtrl.text.trim().isEmpty ? null : _serialCtrl.text.trim(), serial: _serialCtrl.text.trim().isEmpty ? null : _serialCtrl.text.trim(),
@@ -195,6 +197,7 @@ class _NetworkMapDeviceEditScreenState
name: _nameCtrl.text.trim(), name: _nameCtrl.text.trim(),
kind: _kind, kind: _kind,
role: _role, role: _role,
status: _status,
vendor: _vendorCtrl.text.trim().isEmpty ? null : _vendorCtrl.text.trim(), vendor: _vendorCtrl.text.trim().isEmpty ? null : _vendorCtrl.text.trim(),
model: _modelCtrl.text.trim().isEmpty ? null : _modelCtrl.text.trim(), model: _modelCtrl.text.trim().isEmpty ? null : _modelCtrl.text.trim(),
serial: _serialCtrl.text.trim().isEmpty ? null : _serialCtrl.text.trim(), serial: _serialCtrl.text.trim().isEmpty ? null : _serialCtrl.text.trim(),
@@ -219,6 +222,20 @@ class _NetworkMapDeviceEditScreenState
); );
} }
Icon _statusIcon(BuildContext context) {
final cs = Theme.of(context).colorScheme;
switch (_status) {
case NetworkDeviceStatus.online:
return const Icon(Icons.circle, size: 14, color: Color(0xFF388E3C));
case NetworkDeviceStatus.offline:
return Icon(Icons.circle, size: 14, color: cs.error);
case NetworkDeviceStatus.warning:
return const Icon(Icons.circle, size: 14, color: Color(0xFFF57C00));
case NetworkDeviceStatus.unknown:
return Icon(Icons.circle_outlined, size: 14, color: cs.onSurfaceVariant);
}
}
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final existingAsync = widget.deviceId == null final existingAsync = widget.deviceId == null
@@ -227,8 +244,6 @@ class _NetworkMapDeviceEditScreenState
final sitesAsync = ref.watch(networkSitesProvider); final sitesAsync = ref.watch(networkSitesProvider);
final locationsAsync = ref.watch(networkLocationsProvider); final locationsAsync = ref.watch(networkLocationsProvider);
// For a new device under a specific site (from the /site/:id/device/new
// route), pre-fill the site picker so the user can save without picking.
if (!_initialized && widget.deviceId == null && widget.initialSiteId != null) { if (!_initialized && widget.deviceId == null && widget.initialSiteId != null) {
_siteId = widget.initialSiteId; _siteId = widget.initialSiteId;
} }
@@ -241,9 +256,18 @@ class _NetworkMapDeviceEditScreenState
), ),
title: Text(widget.deviceId == null ? 'New device' : 'Edit device'), title: Text(widget.deviceId == null ? 'New device' : 'Edit device'),
actions: [ actions: [
TextButton( Padding(
padding: const EdgeInsets.only(right: 8),
child: FilledButton(
onPressed: _saving ? null : _save, onPressed: _saving ? null : _save,
child: _saving ? const Text('Saving…') : const Text('Save'), child: _saving
? const SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(strokeWidth: 2),
)
: const Text('Save'),
),
), ),
], ],
), ),
@@ -262,53 +286,92 @@ class _NetworkMapDeviceEditScreenState
child: Form( child: Form(
key: _formKey, key: _formKey,
child: SingleChildScrollView( child: SingleChildScrollView(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
child: Column( child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch, crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
// ── Identity ────────────────────────────────────────────
_SectionCard(
icon: Icons.badge_outlined,
title: 'Identity',
children: [ children: [
TextFormField( TextFormField(
controller: _nameCtrl, controller: _nameCtrl,
autofocus: widget.deviceId == null,
decoration: const InputDecoration(labelText: 'Name *'), decoration: const InputDecoration(labelText: 'Name *'),
validator: (v) => (v == null || v.trim().isEmpty) validator: (v) => (v == null || v.trim().isEmpty)
? 'Name is required' ? 'Name is required'
: null, : null,
), ),
const SizedBox(height: 12), const SizedBox(height: 12),
DropdownButtonFormField<NetworkDeviceKind>( _FieldRow(
left: DropdownButtonFormField<NetworkDeviceKind>(
initialValue: _kind, initialValue: _kind,
items: NetworkDeviceKind.values items: NetworkDeviceKind.values
.map((k) => .map((k) => DropdownMenuItem(
DropdownMenuItem(value: k, child: Text(k.label))) value: k,
child: Text(k.label),
))
.toList(), .toList(),
onChanged: (v) => setState(() => _kind = v ?? _kind), onChanged: (v) => setState(() => _kind = v ?? _kind),
decoration: const InputDecoration(labelText: 'Type *'), decoration: const InputDecoration(labelText: 'Type *'),
), ),
const SizedBox(height: 12), right: DropdownButtonFormField<NetworkDeviceRole?>(
DropdownButtonFormField<NetworkDeviceRole?>(
initialValue: _role, initialValue: _role,
items: [ items: [
const DropdownMenuItem<NetworkDeviceRole?>( const DropdownMenuItem<NetworkDeviceRole?>(
value: null, child: Text('(none)')), value: null,
child: Text('(none)'),
),
for (final r in NetworkDeviceRole.values) for (final r in NetworkDeviceRole.values)
DropdownMenuItem(value: r, child: Text(r.label)), DropdownMenuItem(value: r, child: Text(r.label)),
], ],
onChanged: (v) => setState(() => _role = v), onChanged: (v) => setState(() => _role = v),
decoration: decoration: const InputDecoration(labelText: 'Role'),
const InputDecoration(labelText: 'Logical role'), ),
), ),
const SizedBox(height: 12), const SizedBox(height: 12),
DropdownButtonFormField<NetworkDeviceStatus>(
initialValue: _status,
items: NetworkDeviceStatus.values
.map((s) => DropdownMenuItem(
value: s,
child: Text(s.label),
))
.toList(),
onChanged: (v) => setState(
() => _status = v ?? NetworkDeviceStatus.unknown),
decoration: InputDecoration(
labelText: 'Status',
prefixIcon: Padding(
padding: const EdgeInsets.symmetric(horizontal: 12),
child: _statusIcon(context),
),
prefixIconConstraints:
const BoxConstraints(minWidth: 0, minHeight: 0),
),
),
],
),
const SizedBox(height: 16),
// ── Location ─────────────────────────────────────────────
_SectionCard(
icon: Icons.location_on_outlined,
title: 'Location',
children: [
DropdownButtonFormField<String?>( DropdownButtonFormField<String?>(
initialValue: _siteId, initialValue: _siteId,
items: [ items: [
const DropdownMenuItem<String?>( const DropdownMenuItem<String?>(
value: null, child: Text('Unassigned')), value: null,
child: Text('Unassigned'),
),
for (final s in sitesAsync.valueOrNull ?? []) for (final s in sitesAsync.valueOrNull ?? [])
DropdownMenuItem(value: s.id, child: Text(s.name)), DropdownMenuItem(value: s.id, child: Text(s.name)),
], ],
onChanged: (v) => setState(() { onChanged: (v) => setState(() {
_siteId = v; _siteId = v;
// Reset location when site changes — old location wouldn't
// belong to the new site.
_locationId = null; _locationId = null;
}), }),
decoration: const InputDecoration( decoration: const InputDecoration(
@@ -344,7 +407,7 @@ class _NetworkMapDeviceEditScreenState
labelText: 'Location', labelText: 'Location',
helperText: _siteId == null helperText: _siteId == null
? 'Pick a site first.' ? 'Pick a site first.'
: 'Specific building / floor / room / rack within the site.', : 'Building / floor / room / rack within the site.',
enabled: _siteId != null, enabled: _siteId != null,
), ),
), ),
@@ -352,64 +415,73 @@ class _NetworkMapDeviceEditScreenState
const SizedBox(width: 8), const SizedBox(width: 8),
IconButton.filledTonal( IconButton.filledTonal(
tooltip: 'Add new location to this site', tooltip: 'Add new location to this site',
onPressed: _siteId == null onPressed:
? null _siteId == null ? null : _showAddLocationDialog,
: _showAddLocationDialog,
icon: const Icon(Icons.add_location_alt_outlined), icon: const Icon(Icons.add_location_alt_outlined),
), ),
], ],
), ),
const SizedBox(height: 12), ],
TextFormField( ),
const SizedBox(height: 16),
// ── Hardware Details ─────────────────────────────────────
_SectionCard(
icon: Icons.memory_outlined,
title: 'Hardware Details',
children: [
_FieldRow(
left: TextFormField(
controller: _vendorCtrl, controller: _vendorCtrl,
decoration: const InputDecoration( decoration: const InputDecoration(
labelText: 'Vendor (e.g. Ruijie, TP-Link)', labelText: 'Vendor',
hintText: 'e.g. Ruijie, TP-Link',
), ),
), ),
const SizedBox(height: 12), right: TextFormField(
TextFormField(
controller: _modelCtrl, controller: _modelCtrl,
decoration: const InputDecoration(labelText: 'Model'), decoration: const InputDecoration(labelText: 'Model'),
), ),
const SizedBox(height: 12),
TextFormField(
controller: _serialCtrl,
decoration: const InputDecoration(labelText: 'Serial'),
), ),
const SizedBox(height: 12), const SizedBox(height: 12),
TextFormField( _FieldRow(
controller: _mgmtIpCtrl, left: TextFormField(
controller: _serialCtrl,
decoration: decoration:
const InputDecoration(labelText: 'Management IP'), const InputDecoration(labelText: 'Serial'),
),
right: TextFormField(
controller: _mgmtIpCtrl,
decoration: const InputDecoration(
labelText: 'Management IP'),
keyboardType: TextInputType.text, keyboardType: TextInputType.text,
), ),
),
const SizedBox(height: 12), const SizedBox(height: 12),
TextFormField( TextFormField(
controller: _macCtrl, controller: _macCtrl,
decoration: const InputDecoration(labelText: 'MAC address'), decoration:
const InputDecoration(labelText: 'MAC address'),
), ),
const SizedBox(height: 12), const SizedBox(height: 12),
TextFormField( TextFormField(
controller: _notesCtrl, controller: _notesCtrl,
decoration: const InputDecoration(labelText: 'Notes'), decoration: const InputDecoration(labelText: 'Notes'),
maxLines: 3, maxLines: 4,
), ),
],
),
// ── Ports (edit mode only) ────────────────────────────────
if (widget.deviceId != null) ...[ if (widget.deviceId != null) ...[
const SizedBox(height: 16),
_PortsSectionCard(
deviceId: widget.deviceId!,
onAddPort: () => _addPort(widget.deviceId!),
),
],
const SizedBox(height: 24), const SizedBox(height: 24),
Row(
children: [
Text('Ports',
style: Theme.of(context).textTheme.titleMedium),
const Spacer(),
TextButton.icon(
onPressed: () => _addPort(widget.deviceId!),
icon: const Icon(Icons.add),
label: const Text('Add port'),
),
],
),
_PortsList(deviceId: widget.deviceId!),
],
], ],
), ),
), ),
@@ -421,12 +493,138 @@ class _NetworkMapDeviceEditScreenState
} }
} }
// ── Helper widgets ────────────────────────────────────────────────────────────
/// Outlined card with a section header (icon + title) and field children.
class _SectionCard extends StatelessWidget {
const _SectionCard({
required this.icon,
required this.title,
required this.children,
});
final IconData icon;
final String title;
final List<Widget> children;
@override
Widget build(BuildContext context) {
final cs = Theme.of(context).colorScheme;
final tt = Theme.of(context).textTheme;
return Card.outlined(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Row(
children: [
Icon(icon, size: 16, color: cs.primary),
const SizedBox(width: 8),
Text(
title,
style: tt.labelLarge?.copyWith(color: cs.primary),
),
],
),
const SizedBox(height: 16),
...children,
],
),
),
);
}
}
/// Renders two widgets side-by-side on wide screens (≥480dp), stacked on narrow.
class _FieldRow extends StatelessWidget {
const _FieldRow({
required this.left,
required this.right,
});
final Widget left;
final Widget right;
static const double threshold = 480;
@override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (context, constraints) {
if (constraints.maxWidth >= threshold) {
return Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(child: left),
const SizedBox(width: 12),
Expanded(child: right),
],
);
}
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
left,
const SizedBox(height: 12),
right,
],
);
},
);
}
}
/// Ports section card with header and add-port button.
class _PortsSectionCard extends StatelessWidget {
const _PortsSectionCard({
required this.deviceId,
required this.onAddPort,
});
final String deviceId;
final VoidCallback onAddPort;
@override
Widget build(BuildContext context) {
final cs = Theme.of(context).colorScheme;
final tt = Theme.of(context).textTheme;
return Card.outlined(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Row(
children: [
Icon(Icons.cable_outlined, size: 16, color: cs.primary),
const SizedBox(width: 8),
Text(
'Ports',
style: tt.labelLarge?.copyWith(color: cs.primary),
),
const Spacer(),
FilledButton.tonal(
onPressed: onAddPort,
child: const Text('Add port'),
),
],
),
const SizedBox(height: 8),
_PortsList(deviceId: deviceId),
],
),
),
);
}
}
class _PortsList extends ConsumerWidget { class _PortsList extends ConsumerWidget {
const _PortsList({required this.deviceId}); const _PortsList({required this.deviceId});
final String deviceId; final String deviceId;
@override @override
Widget build(BuildContext context, WidgetRef ref) { Widget build(BuildContext context, WidgetRef ref) {
final cs = Theme.of(context).colorScheme;
final portsAsync = ref.watch(networkPortsByDeviceProvider(deviceId)); final portsAsync = ref.watch(networkPortsByDeviceProvider(deviceId));
return portsAsync.when( return portsAsync.when(
loading: () => const Padding( loading: () => const Padding(
@@ -436,9 +634,19 @@ class _PortsList extends ConsumerWidget {
error: (e, _) => Text('Error: $e'), error: (e, _) => Text('Error: $e'),
data: (ports) { data: (ports) {
if (ports.isEmpty) { if (ports.isEmpty) {
return const Padding( return Padding(
padding: EdgeInsets.symmetric(vertical: 8), padding: const EdgeInsets.symmetric(vertical: 16),
child: Text('No ports yet.'), child: Column(
children: [
Icon(Icons.cable_outlined,
size: 32, color: cs.onSurfaceVariant),
const SizedBox(height: 8),
Text(
'No ports configured yet.',
style: TextStyle(color: cs.onSurfaceVariant),
),
],
),
); );
} }
return Column( return Column(
@@ -447,8 +655,8 @@ class _PortsList extends ConsumerWidget {
PortListTile( PortListTile(
port: p, port: p,
canEdit: true, canEdit: true,
onTap: () => showPortEditDialog( onTap: (ctx) => showPortEditDialog(
context: context, context: ctx,
ref: ref, ref: ref,
deviceId: deviceId, deviceId: deviceId,
existing: p, existing: p,
@@ -7,6 +7,7 @@ import '../../providers/network_map/network_devices_provider.dart';
import '../../providers/profile_provider.dart'; import '../../providers/profile_provider.dart';
import '../../widgets/app_state_view.dart'; import '../../widgets/app_state_view.dart';
import '../../widgets/responsive_body.dart'; import '../../widgets/responsive_body.dart';
import 'widgets/link_edit_dialog.dart';
import 'widgets/port_edit_dialog.dart'; import 'widgets/port_edit_dialog.dart';
import 'widgets/port_list_tile.dart'; import 'widgets/port_list_tile.dart';
@@ -98,6 +99,13 @@ class NetworkMapDeviceScreen extends ConsumerWidget {
return null; return null;
} }
String? linkIdForPort(String portId) {
for (final link in links) {
if (link.portA == portId || link.portB == portId) return link.id;
}
return null;
}
return ResponsiveBody( return ResponsiveBody(
maxWidth: 720, maxWidth: 720,
child: ListView( child: ListView(
@@ -124,13 +132,36 @@ class NetworkMapDeviceScreen extends ConsumerWidget {
linkedPortLabel: otherPortLabel(port.id), linkedPortLabel: otherPortLabel(port.id),
canEdit: canEdit, canEdit: canEdit,
onTap: canEdit onTap: canEdit
? () => showPortEditDialog( ? (ctx) => showPortEditDialog(
context: context, context: ctx,
ref: ref, ref: ref,
deviceId: device.id, deviceId: device.id,
existing: port, existing: port,
) )
: null, : null,
onConnect: canEdit
? (ctx) => showLinkEditDialog(
context: ctx,
ref: ref,
portId: port.id,
currentDeviceId: device.id,
)
: null,
onDisconnect: canEdit
? (_) {
final lid = linkIdForPort(port.id);
if (lid != null) {
ref
.read(networkDevicesControllerProvider)
.deleteLink(lid);
}
}
: null,
onDelete: canEdit
? () => ref
.read(networkDevicesControllerProvider)
.deletePort(port.id)
: null,
), ),
if (device.notes != null && device.notes!.trim().isNotEmpty) ...[ if (device.notes != null && device.notes!.trim().isNotEmpty) ...[
Padding( Padding(
@@ -8,15 +8,48 @@ import '../../providers/network_map/network_topology_provider.dart';
import '../../providers/profile_provider.dart'; import '../../providers/profile_provider.dart';
import '../../widgets/app_state_view.dart'; import '../../widgets/app_state_view.dart';
import 'widgets/topology_canvas.dart'; import 'widgets/topology_canvas.dart';
import 'widgets/topology_legend.dart';
import 'widgets/topology_minimap.dart';
import 'widgets/zoom_controls.dart';
class NetworkMapSiteScreen extends ConsumerWidget { class NetworkMapSiteScreen extends ConsumerStatefulWidget {
const NetworkMapSiteScreen({super.key, required this.siteId}); const NetworkMapSiteScreen({super.key, required this.siteId});
final String siteId; final String siteId;
@override @override
Widget build(BuildContext context, WidgetRef ref) { ConsumerState<NetworkMapSiteScreen> createState() =>
final topologyAsync = ref.watch(topologyForSiteProvider(siteId)); _NetworkMapSiteScreenState();
}
class _NetworkMapSiteScreenState extends ConsumerState<NetworkMapSiteScreen> {
late final TransformationController _transformController;
Map<String, Offset> _nodePositions = const {};
Size _canvasSize = const Size(600, 400);
@override
void initState() {
super.initState();
_transformController = TransformationController();
}
@override
void dispose() {
_transformController.dispose();
super.dispose();
}
void _onLayoutUpdated(Map<String, Offset> positions, Size canvasSize) {
if (!mounted) return;
setState(() {
_nodePositions = positions;
_canvasSize = canvasSize;
});
}
@override
Widget build(BuildContext context) {
final topologyAsync = ref.watch(topologyForSiteProvider(widget.siteId));
final viewMode = ref.watch(topologyViewModeProvider); final viewMode = ref.watch(topologyViewModeProvider);
final sitesAsync = ref.watch(networkSitesProvider); final sitesAsync = ref.watch(networkSitesProvider);
final profileAsync = ref.watch(currentProfileProvider); final profileAsync = ref.watch(currentProfileProvider);
@@ -27,7 +60,7 @@ class NetworkMapSiteScreen extends ConsumerWidget {
final siteName = sitesAsync.valueOrNull final siteName = sitesAsync.valueOrNull
?.firstWhere( ?.firstWhere(
(s) => s.id == siteId, (s) => s.id == widget.siteId,
orElse: () => sitesAsync.valueOrNull!.first, orElse: () => sitesAsync.valueOrNull!.first,
) )
.name; .name;
@@ -64,7 +97,7 @@ class NetworkMapSiteScreen extends ConsumerWidget {
tooltip: 'Add device', tooltip: 'Add device',
icon: const Icon(Icons.add_circle_outline), icon: const Icon(Icons.add_circle_outline),
onPressed: () => onPressed: () =>
context.go('/network-map/site/$siteId/device/new'), context.go('/network-map/site/${widget.siteId}/device/new'),
), ),
], ],
), ),
@@ -72,15 +105,97 @@ class NetworkMapSiteScreen extends ConsumerWidget {
loading: () => const Center(child: CircularProgressIndicator()), loading: () => const Center(child: CircularProgressIndicator()),
error: (e, _) => AppErrorView( error: (e, _) => AppErrorView(
error: e, error: e,
onRetry: () => ref.invalidate(topologyForSiteProvider(siteId)), onRetry: () => ref.invalidate(topologyForSiteProvider(widget.siteId)),
), ),
data: (graph) => TopologyCanvas( data: (graph) => _CanvasWithOverlays(
graph: graph, graph: graph,
viewMode: viewMode, viewMode: viewMode,
onDeviceTap: (device) => siteId: widget.siteId,
context.go('/network-map/device/${device.id}'), transformController: _transformController,
nodePositions: _nodePositions,
canvasSize: _canvasSize,
onLayoutUpdated: _onLayoutUpdated,
), ),
), ),
); );
} }
} }
/// Canvas + all overlay widgets (legend, zoom controls, minimap) in a Stack.
class _CanvasWithOverlays extends StatelessWidget {
const _CanvasWithOverlays({
required this.graph,
required this.viewMode,
required this.siteId,
required this.transformController,
required this.nodePositions,
required this.canvasSize,
required this.onLayoutUpdated,
});
final TopologyGraph graph;
final TopologyViewMode viewMode;
final String siteId;
final TransformationController transformController;
final Map<String, Offset> nodePositions;
final Size canvasSize;
final void Function(Map<String, Offset>, Size) onLayoutUpdated;
@override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (context, constraints) {
final viewportSize = Size(constraints.maxWidth, constraints.maxHeight);
return Stack(
children: [
// ── Main topology canvas ─────────────────────────────────────
Positioned.fill(
child: TopologyCanvas(
graph: graph,
viewMode: viewMode,
transformationController: transformController,
onLayoutUpdated: onLayoutUpdated,
onDeviceTap: (device) =>
context.push('/network-map/device/${device.id}'),
),
),
// ── Legend — bottom-left ─────────────────────────────────────
Positioned(
left: 16,
bottom: 16,
child: const TopologyLegend(),
),
// ── Zoom controls + minimap — bottom-right ───────────────────
Positioned(
right: 16,
bottom: 16,
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.end,
children: [
// Minimap above zoom controls
TopologyMinimap(
graph: graph,
nodePositions: nodePositions,
canvasSize: canvasSize,
controller: transformController,
viewportSize: viewportSize,
),
const SizedBox(height: 8),
ZoomControls(
controller: transformController,
canvasSize: canvasSize,
viewportSize: viewportSize,
),
],
),
),
],
);
},
);
}
}
@@ -1,17 +1,12 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import '../../../models/network/network_device.dart'; import '../../../models/network/network_device.dart';
import 'network_device_icon.dart';
/// A styled node representing one network device on the topology canvas. /// A styled node representing one network device on the topology canvas.
/// ///
/// Designed to feel solid at ~120-160dp wide so it remains legible at the /// Accepts an explicit [nodeSize] so role-based sizing can be applied by the
/// "good for 200 nodes" zoom level called out in the V1 spec. /// canvas without this widget needing to know the layout strategy.
///
/// The node has three visual states beyond its default rest:
/// - [isSelected]: stronger primary-tinted background + 2dp primary border.
/// - [isHighlighted]: softer secondary tint + primary outline, used when an
/// edge touching this device is hovered on the canvas.
/// - [isSelected] takes precedence over [isHighlighted].
class DeviceNode extends StatelessWidget { class DeviceNode extends StatelessWidget {
const DeviceNode({ const DeviceNode({
super.key, super.key,
@@ -19,6 +14,7 @@ class DeviceNode extends StatelessWidget {
this.portCount, this.portCount,
this.isSelected = false, this.isSelected = false,
this.isHighlighted = false, this.isHighlighted = false,
this.nodeSize = const Size(160, 110),
this.onTap, this.onTap,
}); });
@@ -26,29 +22,9 @@ class DeviceNode extends StatelessWidget {
final int? portCount; final int? portCount;
final bool isSelected; final bool isSelected;
final bool isHighlighted; final bool isHighlighted;
final Size nodeSize;
final VoidCallback? onTap; final VoidCallback? onTap;
IconData _iconForKind(NetworkDeviceKind kind) {
switch (kind) {
case NetworkDeviceKind.router:
return Icons.router_outlined;
case NetworkDeviceKind.switchDevice:
return Icons.hub_outlined;
case NetworkDeviceKind.ap:
return Icons.wifi_outlined;
case NetworkDeviceKind.firewall:
return Icons.security_outlined;
case NetworkDeviceKind.server:
return Icons.dns_outlined;
case NetworkDeviceKind.endpoint:
return Icons.devices_outlined;
case NetworkDeviceKind.patchPanel:
return Icons.view_module_outlined;
case NetworkDeviceKind.other:
return Icons.device_unknown_outlined;
}
}
Color _accentForRole(ColorScheme cs, NetworkDeviceRole? role) { Color _accentForRole(ColorScheme cs, NetworkDeviceRole? role) {
switch (role) { switch (role) {
case NetworkDeviceRole.core: case NetworkDeviceRole.core:
@@ -65,11 +41,25 @@ class DeviceNode extends StatelessWidget {
} }
} }
Color? _statusColor(ColorScheme cs, NetworkDeviceStatus status) {
switch (status) {
case NetworkDeviceStatus.online:
return const Color(0xFF34A853); // Google green — universally understood
case NetworkDeviceStatus.offline:
return cs.error;
case NetworkDeviceStatus.warning:
return const Color(0xFFFBBC04); // Amber
case NetworkDeviceStatus.unknown:
return null; // No dot shown
}
}
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final cs = Theme.of(context).colorScheme; final cs = Theme.of(context).colorScheme;
final tt = Theme.of(context).textTheme; final tt = Theme.of(context).textTheme;
final accent = _accentForRole(cs, device.role); final accent = _accentForRole(cs, device.role);
final statusColor = _statusColor(cs, device.status);
final bgColor = isSelected final bgColor = isSelected
? cs.primaryContainer ? cs.primaryContainer
@@ -105,8 +95,10 @@ class DeviceNode extends StatelessWidget {
child: InkWell( child: InkWell(
onTap: onTap, onTap: onTap,
borderRadius: BorderRadius.circular(16), borderRadius: BorderRadius.circular(16),
child: Container( child: Stack(
width: 160, children: [
Container(
width: nodeSize.width,
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10), padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
child: Column( child: Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
@@ -114,7 +106,11 @@ class DeviceNode extends StatelessWidget {
children: [ children: [
Row( Row(
children: [ children: [
Icon(_iconForKind(device.kind), size: 18, color: accent), NetworkDeviceIcon(
kind: device.kind,
color: accent,
size: 20,
),
const SizedBox(width: 6), const SizedBox(width: 6),
Expanded( Expanded(
child: Text( child: Text(
@@ -140,7 +136,8 @@ class DeviceNode extends StatelessWidget {
if (device.vendor != null) device.vendor, if (device.vendor != null) device.vendor,
if (device.model != null) device.model, if (device.model != null) device.model,
].whereType<String>().join(''), ].whereType<String>().join(''),
style: tt.labelSmall?.copyWith(color: cs.onSurfaceVariant), style: tt.labelSmall?.copyWith(
color: cs.onSurfaceVariant),
maxLines: 1, maxLines: 1,
overflow: TextOverflow.ellipsis, overflow: TextOverflow.ellipsis,
), ),
@@ -167,6 +164,26 @@ class DeviceNode extends StatelessWidget {
], ],
), ),
), ),
// Status dot — top-right, only shown when status is not unknown
if (statusColor != null)
Positioned(
top: 8,
right: 8,
child: Container(
width: 8,
height: 8,
decoration: BoxDecoration(
color: statusColor,
shape: BoxShape.circle,
border: Border.all(
color: bgColor,
width: 1.5,
),
),
),
),
],
),
), ),
), ),
); );
@@ -0,0 +1,191 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../models/network/network_link.dart';
import '../../../models/network/network_port.dart';
import '../../../providers/network_map/network_devices_provider.dart';
/// Opens an M3 dialog to connect [portId] to a port on another device.
///
/// Returns true if a link was successfully created.
Future<bool> showLinkEditDialog({
required BuildContext context,
required WidgetRef ref,
required String portId,
required String currentDeviceId,
}) async {
final result = await showDialog<bool>(
context: context,
builder: (_) => _LinkEditDialog(
portId: portId,
currentDeviceId: currentDeviceId,
),
);
return result == true;
}
class _LinkEditDialog extends ConsumerStatefulWidget {
const _LinkEditDialog({
required this.portId,
required this.currentDeviceId,
});
final String portId;
final String currentDeviceId;
@override
ConsumerState<_LinkEditDialog> createState() => _LinkEditDialogState();
}
class _LinkEditDialogState extends ConsumerState<_LinkEditDialog> {
String? _selectedDeviceId;
String? _selectedPortId;
NetworkLinkKind? _linkKind;
final _cableLabelCtrl = TextEditingController();
bool _saving = false;
@override
void dispose() {
_cableLabelCtrl.dispose();
super.dispose();
}
Future<void> _save() async {
final portA = widget.portId;
final portB = _selectedPortId;
if (portB == null) return;
setState(() => _saving = true);
try {
ref.invalidate(networkLinksProvider);
final controller = ref.read(networkDevicesControllerProvider);
await controller.createLink(
portA: portA,
portB: portB,
linkKind: _linkKind,
cableLabel: _cableLabelCtrl.text.trim().isEmpty
? null
: _cableLabelCtrl.text.trim(),
);
if (mounted) Navigator.of(context).pop(true);
} catch (e) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Failed to create link: $e'),
backgroundColor: Theme.of(context).colorScheme.error,
),
);
}
} finally {
if (mounted) setState(() => _saving = false);
}
}
@override
Widget build(BuildContext context) {
final devicesAsync = ref.watch(networkDevicesProvider);
final portsAsync = _selectedDeviceId != null
? ref.watch(networkPortsByDeviceProvider(_selectedDeviceId!))
: const AsyncValue<List<NetworkPort>>.data([]);
final allLinksAsync = ref.watch(networkLinksProvider);
final otherDevices = (devicesAsync.valueOrNull ?? const [])
.where((d) => d.id != widget.currentDeviceId)
.toList()
..sort((a, b) => a.name.compareTo(b.name));
final allLinks = allLinksAsync.valueOrNull ?? const [];
final usedPortIds = <String>{
for (final link in allLinks) ...[link.portA, link.portB],
};
final devicePorts = portsAsync.valueOrNull ?? const [];
final availablePorts =
devicePorts.where((p) => !usedPortIds.contains(p.id)).toList();
final canSave = _selectedPortId != null && !_saving;
return AlertDialog(
title: const Text('Connect port'),
content: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 420),
child: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
DropdownButtonFormField<String>(
initialValue: _selectedDeviceId,
decoration:
const InputDecoration(labelText: 'Remote device *'),
items: [
for (final d in otherDevices)
DropdownMenuItem(value: d.id, child: Text(d.name)),
],
onChanged: (v) => setState(() {
_selectedDeviceId = v;
_selectedPortId = null;
}),
),
const SizedBox(height: 12),
DropdownButtonFormField<String>(
key: ValueKey(_selectedDeviceId),
initialValue: _selectedPortId,
decoration: InputDecoration(
labelText: 'Remote port *',
helperText: _selectedDeviceId == null
? 'Select a device first'
: availablePorts.isEmpty
? 'No available ports on this device'
: null,
),
items: [
for (final p in availablePorts)
DropdownMenuItem(
value: p.id,
child: Text(p.portNumber),
),
],
onChanged: _selectedDeviceId == null
? null
: (v) => setState(() => _selectedPortId = v),
),
const SizedBox(height: 12),
DropdownButtonFormField<NetworkLinkKind?>(
initialValue: _linkKind,
decoration: const InputDecoration(labelText: 'Link type'),
items: [
const DropdownMenuItem<NetworkLinkKind?>(
value: null,
child: Text('(unknown)'),
),
for (final k in NetworkLinkKind.values)
DropdownMenuItem(value: k, child: Text(k.label)),
],
onChanged: (v) => setState(() => _linkKind = v),
),
const SizedBox(height: 12),
TextField(
controller: _cableLabelCtrl,
decoration: const InputDecoration(
labelText: 'Cable label',
helperText: 'e.g. "CAT6-01", "SMF-A3" (optional)',
),
),
],
),
),
),
actions: [
TextButton(
onPressed: _saving ? null : () => Navigator.pop(context, false),
child: const Text('Cancel'),
),
FilledButton(
onPressed: canSave ? _save : null,
child: Text(_saving ? 'Saving…' : 'Connect'),
),
],
);
}
}
@@ -0,0 +1,374 @@
import 'dart:math' as math;
import 'package:flutter/material.dart';
import '../../../models/network/network_device.dart';
/// Custom-painted network equipment icon for each [NetworkDeviceKind].
///
/// Draws simplified but recognizable symbols matching professional network
/// topology diagram conventions (Cisco-style silhouettes).
class NetworkDeviceIcon extends StatelessWidget {
const NetworkDeviceIcon({
super.key,
required this.kind,
required this.color,
this.size = 20,
});
final NetworkDeviceKind kind;
final Color color;
final double size;
@override
Widget build(BuildContext context) {
return SizedBox(
width: size,
height: size,
child: CustomPaint(
painter: _DeviceIconPainter(kind: kind, color: color),
),
);
}
}
class _DeviceIconPainter extends CustomPainter {
_DeviceIconPainter({required this.kind, required this.color});
final NetworkDeviceKind kind;
final Color color;
@override
void paint(Canvas canvas, Size size) {
switch (kind) {
case NetworkDeviceKind.router:
_drawRouter(canvas, size);
case NetworkDeviceKind.switchDevice:
_drawSwitch(canvas, size);
case NetworkDeviceKind.ap:
_drawAp(canvas, size);
case NetworkDeviceKind.firewall:
_drawFirewall(canvas, size);
case NetworkDeviceKind.server:
_drawServer(canvas, size);
case NetworkDeviceKind.endpoint:
_drawEndpoint(canvas, size);
case NetworkDeviceKind.patchPanel:
_drawPatchPanel(canvas, size);
case NetworkDeviceKind.other:
_drawOther(canvas, size);
}
}
Paint get _stroke => Paint()
..color = color
..style = PaintingStyle.stroke
..strokeCap = StrokeCap.round
..strokeJoin = StrokeJoin.round
..strokeWidth = 1.4;
Paint get _fill => Paint()
..color = color
..style = PaintingStyle.fill;
// ─── Router: cylinder body + 4 arrows ─────────────────────────────────────
void _drawRouter(Canvas canvas, Size s) {
final cx = s.width / 2;
final cy = s.height / 2;
final r = s.width * 0.28;
final p = _stroke;
// Circle body
canvas.drawCircle(Offset(cx, cy), r, p);
// 4 directional arrows at N/S/E/W
const arrowLen = 0.22;
const arrowHead = 0.1;
for (var i = 0; i < 4; i++) {
final angle = i * math.pi / 2;
final ax = cx + math.cos(angle) * (r + s.width * arrowLen);
final ay = cy + math.sin(angle) * (r + s.width * arrowLen);
final bx = cx + math.cos(angle) * (r + 1);
final by = cy + math.sin(angle) * (r + 1);
canvas.drawLine(Offset(bx, by), Offset(ax, ay), p);
// Arrowhead
final perp = angle + math.pi / 2;
final hw = s.width * arrowHead;
canvas.drawPath(
Path()
..moveTo(ax, ay)
..lineTo(
ax - math.cos(angle) * hw + math.cos(perp) * hw / 2,
ay - math.sin(angle) * hw + math.sin(perp) * hw / 2,
)
..lineTo(
ax - math.cos(angle) * hw - math.cos(perp) * hw / 2,
ay - math.sin(angle) * hw - math.sin(perp) * hw / 2,
)
..close(),
_fill,
);
}
}
// ─── Switch: rectangle + port lines ───────────────────────────────────────
void _drawSwitch(Canvas canvas, Size s) {
final w = s.width * 0.86;
final h = s.height * 0.42;
final left = (s.width - w) / 2;
final top = (s.height - h) / 2;
final p = _stroke;
// Body
canvas.drawRRect(
RRect.fromRectAndRadius(
Rect.fromLTWH(left, top, w, h),
const Radius.circular(2),
),
p,
);
// Port lines (8 evenly spaced)
const ports = 8;
final portSpacing = w / (ports + 1);
final portH = h * 0.5;
final portTop = top + h * 0.2;
for (var i = 1; i <= ports; i++) {
final px = left + portSpacing * i;
canvas.drawLine(
Offset(px, portTop),
Offset(px, portTop + portH),
p,
);
}
// Two legs at bottom center
final legX1 = s.width * 0.38;
final legX2 = s.width * 0.62;
final bodyBottom = top + h;
canvas.drawLine(
Offset(legX1, bodyBottom),
Offset(legX1, s.height * 0.85),
p,
);
canvas.drawLine(
Offset(legX2, bodyBottom),
Offset(legX2, s.height * 0.85),
p,
);
canvas.drawLine(
Offset(legX1, s.height * 0.85),
Offset(legX2, s.height * 0.85),
p,
);
}
// ─── AP: semicircle waves + stem ──────────────────────────────────────────
void _drawAp(Canvas canvas, Size s) {
final cx = s.width / 2;
final base = s.height * 0.72;
final p = _stroke;
// Stem
canvas.drawLine(Offset(cx, base), Offset(cx, s.height * 0.88), p);
canvas.drawLine(
Offset(cx - s.width * 0.15, s.height * 0.88),
Offset(cx + s.width * 0.15, s.height * 0.88),
p,
);
// 3 concentric arcs from narrow to wide
for (var i = 1; i <= 3; i++) {
final r = s.width * 0.13 * i;
final rect = Rect.fromCircle(center: Offset(cx, base), radius: r);
canvas.drawArc(rect, math.pi, -math.pi, false, p);
}
}
// ─── Firewall: brick-wall grid ─────────────────────────────────────────────
void _drawFirewall(Canvas canvas, Size s) {
final w = s.width * 0.8;
final h = s.height * 0.72;
final left = (s.width - w) / 2;
final top = (s.height - h) / 2;
final p = _stroke;
// Outer rect
canvas.drawRect(Rect.fromLTWH(left, top, w, h), p);
// 3 rows, 2 staggered bricks each
final rowH = h / 3;
for (var row = 0; row < 3; row++) {
final rowTop = top + row * rowH;
// horizontal mortar line
if (row > 0) {
canvas.drawLine(
Offset(left, rowTop),
Offset(left + w, rowTop),
p,
);
}
// vertical mortar — offset every other row by half a brick
final offset = (row % 2 == 0) ? w / 2 : w / 4;
canvas.drawLine(
Offset(left + offset, rowTop),
Offset(left + offset, rowTop + rowH),
p,
);
}
}
// ─── Server: rack unit with LED dots ──────────────────────────────────────
void _drawServer(Canvas canvas, Size s) {
final w = s.width * 0.72;
final h = s.height * 0.78;
final left = (s.width - w) / 2;
final top = (s.height - h) / 2;
final p = _stroke;
final fp = _fill;
// Body
canvas.drawRRect(
RRect.fromRectAndRadius(
Rect.fromLTWH(left, top, w, h),
const Radius.circular(2),
),
p,
);
// 3 horizontal rack-unit dividers + LED dots
final unitH = h / 3;
for (var i = 0; i < 3; i++) {
final unitTop = top + i * unitH;
if (i > 0) {
canvas.drawLine(
Offset(left, unitTop),
Offset(left + w, unitTop),
p,
);
}
// Small LED dot on right side of each unit
canvas.drawCircle(
Offset(left + w - w * 0.15, unitTop + unitH / 2),
s.width * 0.05,
fp,
);
}
}
// ─── Endpoint: monitor + stand ─────────────────────────────────────────────
void _drawEndpoint(Canvas canvas, Size s) {
final monW = s.width * 0.76;
final monH = s.height * 0.52;
final left = (s.width - monW) / 2;
final top = s.height * 0.08;
final p = _stroke;
// Monitor bezel
canvas.drawRRect(
RRect.fromRectAndRadius(
Rect.fromLTWH(left, top, monW, monH),
const Radius.circular(2),
),
p,
);
// Screen inner (inset 2dp)
canvas.drawRRect(
RRect.fromRectAndRadius(
Rect.fromLTWH(left + 3, top + 3, monW - 6, monH - 6),
const Radius.circular(1),
),
p,
);
// Neck
final neckX = s.width / 2;
final neckTop = top + monH;
canvas.drawLine(
Offset(neckX, neckTop),
Offset(neckX, neckTop + s.height * 0.18),
p,
);
// Base
canvas.drawLine(
Offset(s.width * 0.25, s.height * 0.88),
Offset(s.width * 0.75, s.height * 0.88),
p,
);
}
// ─── Patch panel: flat rect with 2 rows of port circles ──────────────────
void _drawPatchPanel(Canvas canvas, Size s) {
final w = s.width * 0.9;
final h = s.height * 0.44;
final left = (s.width - w) / 2;
final top = (s.height - h) / 2;
final p = _stroke;
// Body
canvas.drawRRect(
RRect.fromRectAndRadius(
Rect.fromLTWH(left, top, w, h),
const Radius.circular(2),
),
p,
);
// 2 rows × 5 port circles
const cols = 5;
const rows = 2;
final colSpacing = w / (cols + 1);
final rowSpacing = h / (rows + 1);
final dotR = s.width * 0.04;
for (var row = 1; row <= rows; row++) {
for (var col = 1; col <= cols; col++) {
canvas.drawCircle(
Offset(left + colSpacing * col, top + rowSpacing * row),
dotR,
p,
);
}
}
}
// ─── Other: circle with question mark ─────────────────────────────────────
void _drawOther(Canvas canvas, Size s) {
final cx = s.width / 2;
final cy = s.height / 2;
final r = s.width * 0.42;
final p = _stroke;
canvas.drawCircle(Offset(cx, cy), r, p);
// "?" drawn as a small arc + dot
final tp = TextPainter(
text: TextSpan(
text: '?',
style: TextStyle(
fontSize: s.width * 0.52,
fontWeight: FontWeight.w700,
color: color,
height: 1,
),
),
textDirection: TextDirection.ltr,
)..layout();
tp.paint(
canvas,
Offset(cx - tp.width / 2, cy - tp.height / 2),
);
}
@override
bool shouldRepaint(covariant _DeviceIconPainter old) =>
old.kind != kind || old.color != color;
}
@@ -131,18 +131,19 @@ class _PortEditDialogState extends ConsumerState<_PortEditDialog> {
return AlertDialog( return AlertDialog(
title: Text(widget.existing == null ? 'Add port' : 'Edit port'), title: Text(widget.existing == null ? 'Add port' : 'Edit port'),
content: ConstrainedBox( content: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 420), constraints: const BoxConstraints(minWidth: 320, maxWidth: 480),
child: SingleChildScrollView( child: SingleChildScrollView(
child: Column( child: Column(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch, crossAxisAlignment: CrossAxisAlignment.stretch,
children: [ children: [
// ── Identity ─────────────────────────────────────────
TextField( TextField(
controller: _numberCtrl, controller: _numberCtrl,
autofocus: widget.existing == null, autofocus: widget.existing == null,
decoration: const InputDecoration( decoration: const InputDecoration(
labelText: 'Port number *', labelText: 'Port number *',
helperText: 'Exactly as labeled on the device (e.g. Gi0/1, eth0, 24)', helperText: 'e.g. Gi0/1, eth0, port24',
), ),
), ),
const SizedBox(height: 12), const SizedBox(height: 12),
@@ -161,6 +162,7 @@ class _PortEditDialogState extends ConsumerState<_PortEditDialog> {
), ),
const SizedBox(height: 12), const SizedBox(height: 12),
Row( Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
Expanded( Expanded(
child: TextField( child: TextField(
@@ -182,39 +184,43 @@ class _PortEditDialogState extends ConsumerState<_PortEditDialog> {
inputFormatters: [FilteringTextInputFormatter.digitsOnly], inputFormatters: [FilteringTextInputFormatter.digitsOnly],
decoration: InputDecoration( decoration: InputDecoration(
labelText: 'Access VLAN', labelText: 'Access VLAN',
helperText: _isTrunk helperText: _isTrunk ? 'Disabled for trunk' : '14094',
? 'Disabled — trunk port'
: 'Single VLAN ID (14094)',
), ),
), ),
), ),
], ],
), ),
const SizedBox(height: 12), // ── Switching config ──────────────────────────────────
const Divider(height: 28),
SwitchListTile.adaptive( SwitchListTile.adaptive(
value: _isTrunk, value: _isTrunk,
onChanged: (v) => setState(() => _isTrunk = v), onChanged: (v) => setState(() => _isTrunk = v),
contentPadding: EdgeInsets.zero, contentPadding: EdgeInsets.zero,
title: const Text('Trunk port'), title: const Text('Trunk port'),
subtitle: Text( subtitle: Text('Carries multiple VLANs', style: tt.bodySmall),
'Carries multiple VLANs',
style: tt.bodySmall,
), ),
), AnimatedSize(
if (_isTrunk) ...[ duration: const Duration(milliseconds: 200),
const SizedBox(height: 4), curve: Curves.easeInOut,
TextField( child: _isTrunk
? Padding(
padding: const EdgeInsets.only(top: 8),
child: TextField(
controller: _trunkVlansCtrl, controller: _trunkVlansCtrl,
decoration: const InputDecoration( decoration: const InputDecoration(
labelText: 'Allowed VLANs (comma-separated)', labelText: 'Allowed VLANs',
helperText: 'e.g. 10, 20, 100-105', helperText: 'Comma-separated, e.g. 10, 20, 100',
), ),
), ),
], )
: const SizedBox.shrink(),
),
// ── Notes ─────────────────────────────────────────────
const SizedBox(height: 12), const SizedBox(height: 12),
TextField( TextField(
controller: _notesCtrl, controller: _notesCtrl,
maxLines: 2, minLines: 2,
maxLines: 4,
decoration: const InputDecoration(labelText: 'Notes'), decoration: const InputDecoration(labelText: 'Notes'),
), ),
], ],
@@ -228,7 +234,13 @@ class _PortEditDialogState extends ConsumerState<_PortEditDialog> {
), ),
FilledButton( FilledButton(
onPressed: _saving ? null : _save, onPressed: _saving ? null : _save,
child: Text(_saving ? 'Saving…' : 'Save'), child: _saving
? const SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(strokeWidth: 2),
)
: Text(widget.existing == null ? 'Add' : 'Save'),
), ),
], ],
); );
@@ -2,6 +2,8 @@ import 'package:flutter/material.dart';
import '../../../models/network/network_port.dart'; import '../../../models/network/network_port.dart';
enum _PortAction { editPort, connect, disconnect, deletePort }
class PortListTile extends StatelessWidget { class PortListTile extends StatelessWidget {
const PortListTile({ const PortListTile({
super.key, super.key,
@@ -10,6 +12,8 @@ class PortListTile extends StatelessWidget {
this.linkedPortLabel, this.linkedPortLabel,
this.canEdit = false, this.canEdit = false,
this.onTap, this.onTap,
this.onConnect,
this.onDisconnect,
this.onDelete, this.onDelete,
}); });
@@ -17,7 +21,9 @@ class PortListTile extends StatelessWidget {
final String? linkedDeviceName; final String? linkedDeviceName;
final String? linkedPortLabel; final String? linkedPortLabel;
final bool canEdit; final bool canEdit;
final VoidCallback? onTap; final void Function(BuildContext)? onTap;
final void Function(BuildContext)? onConnect;
final void Function(BuildContext)? onDisconnect;
final VoidCallback? onDelete; final VoidCallback? onDelete;
@override @override
@@ -34,7 +40,7 @@ class PortListTile extends StatelessWidget {
]; ];
return ListTile( return ListTile(
onTap: onTap, onTap: onTap == null ? null : () => onTap!(context),
leading: CircleAvatar( leading: CircleAvatar(
backgroundColor: isLinked backgroundColor: isLinked
? cs.primaryContainer ? cs.primaryContainer
@@ -64,10 +70,56 @@ class PortListTile extends StatelessWidget {
], ],
), ),
trailing: canEdit trailing: canEdit
? IconButton( ? PopupMenuButton<_PortAction>(
icon: const Icon(Icons.delete_outline), tooltip: 'Port actions',
tooltip: 'Delete port', onSelected: (action) {
onPressed: onDelete, switch (action) {
case _PortAction.editPort:
onTap?.call(context);
case _PortAction.connect:
onConnect?.call(context);
case _PortAction.disconnect:
onDisconnect?.call(context);
case _PortAction.deletePort:
onDelete?.call();
}
},
itemBuilder: (_) => [
const PopupMenuItem(
value: _PortAction.editPort,
child: ListTile(
leading: Icon(Icons.edit_outlined),
title: Text('Edit port'),
contentPadding: EdgeInsets.zero,
),
),
if (!isLinked)
const PopupMenuItem(
value: _PortAction.connect,
child: ListTile(
leading: Icon(Icons.add_link),
title: Text('Connect to…'),
contentPadding: EdgeInsets.zero,
),
),
if (isLinked)
const PopupMenuItem(
value: _PortAction.disconnect,
child: ListTile(
leading: Icon(Icons.link_off),
title: Text('Disconnect'),
contentPadding: EdgeInsets.zero,
),
),
const PopupMenuItem(
value: _PortAction.deletePort,
child: ListTile(
leading: Icon(Icons.delete_outline),
title: Text('Delete port'),
contentPadding: EdgeInsets.zero,
),
),
],
) )
: null, : null,
); );
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,245 @@
import 'package:flutter/material.dart';
import '../../../models/network/network_device.dart';
import '../../../models/network/network_link.dart';
/// Collapsible legend overlay explaining device role border colours and link
/// type colours. Positioned at the bottom-left of the topology canvas view.
class TopologyLegend extends StatefulWidget {
const TopologyLegend({super.key});
@override
State<TopologyLegend> createState() => _TopologyLegendState();
}
class _TopologyLegendState extends State<TopologyLegend>
with SingleTickerProviderStateMixin {
bool _expanded = false;
late final AnimationController _anim;
late final Animation<double> _fade;
@override
void initState() {
super.initState();
_anim = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 200),
);
_fade = CurvedAnimation(parent: _anim, curve: Curves.easeOut);
}
@override
void dispose() {
_anim.dispose();
super.dispose();
}
void _toggle() {
setState(() => _expanded = !_expanded);
if (_expanded) {
_anim.forward();
} else {
_anim.reverse();
}
}
Color _roleColor(ColorScheme cs, NetworkDeviceRole role) {
switch (role) {
case NetworkDeviceRole.core:
return cs.error;
case NetworkDeviceRole.distribution:
return cs.tertiary;
case NetworkDeviceRole.access:
return cs.primary;
case NetworkDeviceRole.edge:
return cs.secondary;
case NetworkDeviceRole.endpoint:
return cs.outline;
}
}
Color _linkColor(ColorScheme cs, NetworkLinkKind kind) {
switch (kind) {
case NetworkLinkKind.copper:
return cs.primary;
case NetworkLinkKind.fiber:
return cs.tertiary;
case NetworkLinkKind.wireless:
return cs.secondary;
case NetworkLinkKind.virtual:
return cs.outline;
case NetworkLinkKind.unknown:
return cs.outline;
}
}
@override
Widget build(BuildContext context) {
final cs = Theme.of(context).colorScheme;
final tt = Theme.of(context).textTheme;
return Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Expand/collapse toggle chip
Material(
color: cs.surfaceContainerHigh,
borderRadius: BorderRadius.circular(20),
elevation: 2,
child: InkWell(
onTap: _toggle,
borderRadius: BorderRadius.circular(20),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
Icons.legend_toggle_outlined,
size: 16,
color: cs.onSurfaceVariant,
),
const SizedBox(width: 6),
Text(
'Legend',
style: tt.labelSmall?.copyWith(
color: cs.onSurfaceVariant,
fontWeight: FontWeight.w600,
),
),
const SizedBox(width: 4),
AnimatedRotation(
turns: _expanded ? 0.5 : 0,
duration: const Duration(milliseconds: 200),
child: Icon(
Icons.expand_more,
size: 16,
color: cs.onSurfaceVariant,
),
),
],
),
),
),
),
// Expandable panel
FadeTransition(
opacity: _fade,
child: SizeTransition(
sizeFactor: _fade,
axisAlignment: -1,
child: Padding(
padding: const EdgeInsets.only(top: 6),
child: Material(
color: cs.surfaceContainerHigh,
borderRadius: BorderRadius.circular(12),
elevation: 3,
child: Padding(
padding: const EdgeInsets.all(12),
child: SizedBox(
width: 200,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
// Device Roles
Text(
'Device Roles',
style: tt.labelSmall?.copyWith(
color: cs.onSurfaceVariant,
fontWeight: FontWeight.w700,
letterSpacing: 0.8,
),
),
const SizedBox(height: 6),
for (final role in NetworkDeviceRole.values)
_LegendRow(
color: _roleColor(cs, role),
label: role.label,
isLine: false,
),
const SizedBox(height: 10),
Divider(
height: 1,
color: cs.outlineVariant.withValues(alpha: 0.5)),
const SizedBox(height: 10),
// Link Types
Text(
'Link Types',
style: tt.labelSmall?.copyWith(
color: cs.onSurfaceVariant,
fontWeight: FontWeight.w700,
letterSpacing: 0.8,
),
),
const SizedBox(height: 6),
for (final kind in NetworkLinkKind.values)
_LegendRow(
color: _linkColor(cs, kind),
label: kind.label,
isLine: true,
),
],
),
),
),
),
),
),
),
],
);
}
}
class _LegendRow extends StatelessWidget {
const _LegendRow({
required this.color,
required this.label,
required this.isLine,
});
final Color color;
final String label;
final bool isLine;
@override
Widget build(BuildContext context) {
final tt = Theme.of(context).textTheme;
return Padding(
padding: const EdgeInsets.symmetric(vertical: 2),
child: Row(
children: [
if (isLine)
// Coloured line segment for link types
Container(
width: 20,
height: 3,
decoration: BoxDecoration(
color: color,
borderRadius: BorderRadius.circular(2),
),
)
else
// Coloured square for device roles (border indicator)
Container(
width: 12,
height: 12,
decoration: BoxDecoration(
border: Border.all(color: color, width: 2),
borderRadius: BorderRadius.circular(3),
),
),
const SizedBox(width: 8),
Text(
label,
style: tt.labelSmall?.copyWith(
color: Theme.of(context).colorScheme.onSurface,
),
),
],
),
);
}
}
@@ -0,0 +1,248 @@
import 'package:flutter/material.dart';
import '../../../models/network/network_device.dart';
import '../../../models/network/topology_graph.dart';
/// Scaled-down overview of the topology canvas with a viewport indicator.
///
/// Shows all device nodes as small colour-coded rectangles and all edges as
/// thin lines. A semi-transparent white rectangle indicates the current
/// viewport within the full canvas. Tapping on the minimap pans the main
/// canvas to centre on that point.
class TopologyMinimap extends StatefulWidget {
const TopologyMinimap({
super.key,
required this.graph,
required this.nodePositions,
required this.canvasSize,
required this.controller,
required this.viewportSize,
});
final TopologyGraph graph;
/// Current interpolated node positions (top-left corners) from the canvas.
final Map<String, Offset> nodePositions;
final Size canvasSize;
final TransformationController controller;
final Size viewportSize;
static const Size _minimapSize = Size(160, 100);
@override
State<TopologyMinimap> createState() => _TopologyMinimapState();
}
class _TopologyMinimapState extends State<TopologyMinimap> {
@override
void initState() {
super.initState();
widget.controller.addListener(_onTransformChanged);
}
@override
void didUpdateWidget(covariant TopologyMinimap oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.controller != widget.controller) {
oldWidget.controller.removeListener(_onTransformChanged);
widget.controller.addListener(_onTransformChanged);
}
}
@override
void dispose() {
widget.controller.removeListener(_onTransformChanged);
super.dispose();
}
void _onTransformChanged() => setState(() {});
double get _scaleX {
if (widget.canvasSize.width == 0) return 1;
return TopologyMinimap._minimapSize.width / widget.canvasSize.width;
}
double get _scaleY {
if (widget.canvasSize.height == 0) return 1;
return TopologyMinimap._minimapSize.height / widget.canvasSize.height;
}
double get _scale => _scaleX < _scaleY ? _scaleX : _scaleY;
Offset _toMinimap(Offset canvasPoint) {
final s = _scale;
final offsetX = (TopologyMinimap._minimapSize.width - widget.canvasSize.width * s) / 2;
final offsetY = (TopologyMinimap._minimapSize.height - widget.canvasSize.height * s) / 2;
return Offset(canvasPoint.dx * s + offsetX, canvasPoint.dy * s + offsetY);
}
/// Convert a tap on the minimap to a canvas point, then pan the main canvas
/// so that point appears at the viewport centre.
void _onTap(Offset localPos) {
final s = _scale;
if (s == 0) return;
final offsetX = (TopologyMinimap._minimapSize.width - widget.canvasSize.width * s) / 2;
final offsetY = (TopologyMinimap._minimapSize.height - widget.canvasSize.height * s) / 2;
final canvasX = (localPos.dx - offsetX) / s;
final canvasY = (localPos.dy - offsetY) / s;
final currentScale = widget.controller.value.getMaxScaleOnAxis();
final tx = widget.viewportSize.width / 2 - canvasX * currentScale;
final ty = widget.viewportSize.height / 2 - canvasY * currentScale;
final result = Matrix4.translationValues(tx, ty, 0);
result.multiply(Matrix4.diagonal3Values(currentScale, currentScale, 1.0));
widget.controller.value = result;
}
@override
Widget build(BuildContext context) {
final cs = Theme.of(context).colorScheme;
return GestureDetector(
onTapDown: (d) => _onTap(d.localPosition),
child: Material(
color: cs.surfaceContainerHighest,
borderRadius: BorderRadius.circular(8),
elevation: 2,
child: ClipRRect(
borderRadius: BorderRadius.circular(8),
child: SizedBox(
width: TopologyMinimap._minimapSize.width,
height: TopologyMinimap._minimapSize.height,
child: CustomPaint(
painter: _MinimapPainter(
graph: widget.graph,
nodePositions: widget.nodePositions,
canvasSize: widget.canvasSize,
controller: widget.controller,
viewportSize: widget.viewportSize,
colorScheme: cs,
scale: _scale,
toMinimap: _toMinimap,
),
),
),
),
),
);
}
}
class _MinimapPainter extends CustomPainter {
_MinimapPainter({
required this.graph,
required this.nodePositions,
required this.canvasSize,
required this.controller,
required this.viewportSize,
required this.colorScheme,
required this.scale,
required this.toMinimap,
});
final TopologyGraph graph;
final Map<String, Offset> nodePositions;
final Size canvasSize;
final TransformationController controller;
final Size viewportSize;
final ColorScheme colorScheme;
final double scale;
final Offset Function(Offset) toMinimap;
static const Size _nodeRectSize = Size(8, 5);
Color _roleColor(NetworkDeviceRole? role) {
switch (role) {
case NetworkDeviceRole.core:
return colorScheme.error;
case NetworkDeviceRole.distribution:
return colorScheme.tertiary;
case NetworkDeviceRole.access:
return colorScheme.primary;
case NetworkDeviceRole.edge:
return colorScheme.secondary;
case NetworkDeviceRole.endpoint:
case null:
return colorScheme.outline;
}
}
@override
void paint(Canvas canvas, Size size) {
// Edges
final edgePaint = Paint()
..color = colorScheme.outline.withValues(alpha: 0.4)
..strokeWidth = 0.6
..style = PaintingStyle.stroke
..strokeCap = StrokeCap.round;
for (final edge in graph.edges) {
final fromPos = nodePositions[edge.fromDeviceId];
final toPos = nodePositions[edge.toDeviceId];
if (fromPos == null || toPos == null) continue;
// Use node centres
final from = toMinimap(fromPos + const Offset(80, 55));
final to = toMinimap(toPos + const Offset(80, 55));
canvas.drawLine(from, to, edgePaint);
}
// Device nodes
for (final node in graph.nodes) {
final pos = nodePositions[node.device.id];
if (pos == null) continue;
final minimapPos = toMinimap(pos);
final rect = Rect.fromLTWH(
minimapPos.dx - _nodeRectSize.width / 2,
minimapPos.dy - _nodeRectSize.height / 2,
_nodeRectSize.width,
_nodeRectSize.height,
);
canvas.drawRRect(
RRect.fromRectAndRadius(rect, const Radius.circular(1.5)),
Paint()
..color = _roleColor(node.device.role)
..style = PaintingStyle.fill,
);
}
// Viewport rectangle
final m = controller.value;
final currentScale = m.getMaxScaleOnAxis();
if (currentScale > 0) {
// The translation is in the 3rd column of the matrix
final tx = m.getTranslation().x;
final ty = m.getTranslation().y;
// Viewport in canvas coordinates
final vpLeft = -tx / currentScale;
final vpTop = -ty / currentScale;
final vpWidth = viewportSize.width / currentScale;
final vpHeight = viewportSize.height / currentScale;
final tl = toMinimap(Offset(vpLeft, vpTop));
final br = toMinimap(Offset(vpLeft + vpWidth, vpTop + vpHeight));
final vpRect = Rect.fromPoints(tl, br);
// Fill
canvas.drawRect(
vpRect,
Paint()
..color = colorScheme.primary.withValues(alpha: 0.08)
..style = PaintingStyle.fill,
);
// Border
canvas.drawRect(
vpRect,
Paint()
..color = colorScheme.primary.withValues(alpha: 0.6)
..strokeWidth = 1.0
..style = PaintingStyle.stroke,
);
}
}
@override
bool shouldRepaint(covariant _MinimapPainter old) => true;
}
@@ -0,0 +1,130 @@
import 'package:flutter/material.dart';
/// Vertical +//fit-to-view zoom controls for the topology canvas.
/// Requires a [TransformationController] shared with the [InteractiveViewer].
class ZoomControls extends StatelessWidget {
const ZoomControls({
super.key,
required this.controller,
required this.canvasSize,
required this.viewportSize,
});
final TransformationController controller;
/// Full canvas size (from [computeSugiyamaLayout] result).
final Size canvasSize;
/// Viewport widget size (the screen area the canvas is displayed in).
final Size viewportSize;
static const double _zoomIn = 1.25;
static const double _zoomOut = 0.8;
static const double _minScale = 0.2;
static const double _maxScale = 2.5;
void _applyZoom(double factor) {
final current = controller.value.getMaxScaleOnAxis();
final next = (current * factor).clamp(_minScale, _maxScale);
final scale = next / current;
final cx = viewportSize.width / 2;
final cy = viewportSize.height / 2;
// Compose: T(cx,cy) * Scale(s) * T(-cx,-cy) * currentTransform
final result = Matrix4.translationValues(cx, cy, 0);
result.multiply(Matrix4.diagonal3Values(scale, scale, 1.0));
result.multiply(Matrix4.translationValues(-cx, -cy, 0));
result.multiply(controller.value);
controller.value = result;
}
void _fitToView() {
if (canvasSize.isEmpty) return;
final scaleX = viewportSize.width / canvasSize.width;
final scaleY = viewportSize.height / canvasSize.height;
final scale = (scaleX < scaleY ? scaleX : scaleY).clamp(_minScale, _maxScale);
final tx = (viewportSize.width - canvasSize.width * scale) / 2;
final ty = (viewportSize.height - canvasSize.height * scale) / 2;
// Build: T(tx,ty,0) * Scale(s,s,1) maps canvas (0,0) (tx,ty) on screen
final result = Matrix4.translationValues(tx, ty, 0);
result.multiply(Matrix4.diagonal3Values(scale, scale, 1.0));
controller.value = result;
}
@override
Widget build(BuildContext context) {
final cs = Theme.of(context).colorScheme;
return Material(
color: cs.surfaceContainerHigh,
borderRadius: BorderRadius.circular(12),
elevation: 2,
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 4),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
_ZoomButton(
icon: Icons.add,
tooltip: 'Zoom in',
onTap: () => _applyZoom(_zoomIn),
),
_Divider(color: cs.outlineVariant.withValues(alpha: 0.4)),
_ZoomButton(
icon: Icons.remove,
tooltip: 'Zoom out',
onTap: () => _applyZoom(_zoomOut),
),
_Divider(color: cs.outlineVariant.withValues(alpha: 0.4)),
_ZoomButton(
icon: Icons.fit_screen_outlined,
tooltip: 'Fit to view',
onTap: _fitToView,
),
],
),
),
);
}
}
class _ZoomButton extends StatelessWidget {
const _ZoomButton({
required this.icon,
required this.tooltip,
required this.onTap,
});
final IconData icon;
final String tooltip;
final VoidCallback onTap;
@override
Widget build(BuildContext context) {
final cs = Theme.of(context).colorScheme;
return Tooltip(
message: tooltip,
child: InkWell(
onTap: onTap,
borderRadius: BorderRadius.circular(8),
child: SizedBox(
width: 40,
height: 40,
child: Icon(icon, size: 18, color: cs.onSurfaceVariant),
),
),
);
}
}
class _Divider extends StatelessWidget {
const _Divider({required this.color});
final Color color;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 8),
child: Divider(height: 1, color: color),
);
}
}
File diff suppressed because it is too large Load Diff
+163 -48
View File
@@ -808,7 +808,10 @@ class _ScheduleGeneratorPanelState
final isRamadan = ref.watch(isRamadanActiveProvider); final isRamadan = ref.watch(isRamadanActiveProvider);
final colorScheme = Theme.of(context).colorScheme;
return Card( return Card(
clipBehavior: Clip.antiAlias,
child: Padding( child: Padding(
padding: const EdgeInsets.all(16), padding: const EdgeInsets.all(16),
child: Column( child: Column(
@@ -827,11 +830,9 @@ class _ScheduleGeneratorPanelState
Chip( Chip(
label: const Text('Ramadan'), label: const Text('Ramadan'),
avatar: const Icon(Icons.nights_stay, size: 16), avatar: const Icon(Icons.nights_stay, size: 16),
backgroundColor: Theme.of( backgroundColor: colorScheme.tertiaryContainer,
context,
).colorScheme.tertiaryContainer,
labelStyle: TextStyle( labelStyle: TextStyle(
color: Theme.of(context).colorScheme.onTertiaryContainer, color: colorScheme.onTertiaryContainer,
), ),
), ),
], ],
@@ -843,6 +844,14 @@ class _ScheduleGeneratorPanelState
), ),
], ],
), ),
if (_isGenerating) ...[
const SizedBox(height: 8),
LinearProgressIndicator(
backgroundColor: colorScheme.surfaceContainerHighest,
color: colorScheme.primary,
borderRadius: BorderRadius.circular(2),
),
],
const SizedBox(height: 12), const SizedBox(height: 12),
_dateField( _dateField(
context, context,
@@ -861,15 +870,19 @@ class _ScheduleGeneratorPanelState
Row( Row(
children: [ children: [
Expanded( Expanded(
child: FilledButton( child: FilledButton.icon(
onPressed: _isGenerating ? null : _handleGenerate, onPressed: _isGenerating ? null : _handleGenerate,
child: _isGenerating icon: _isGenerating
? const SizedBox( ? const SizedBox(
height: 18, height: 16,
width: 18, width: 16,
child: CircularProgressIndicator(strokeWidth: 2), child: CircularProgressIndicator(
strokeWidth: 2,
color: Colors.white,
),
) )
: const Text('Generate preview'), : const Icon(Icons.auto_awesome, size: 18),
label: const Text('Generate preview'),
), ),
), ),
const SizedBox(width: 12), const SizedBox(width: 12),
@@ -891,22 +904,25 @@ class _ScheduleGeneratorPanelState
const SizedBox(height: 12), const SizedBox(height: 12),
Row( Row(
children: [ children: [
OutlinedButton.icon( FilledButton.tonalIcon(
onPressed: _isSaving ? null : _addDraft, onPressed: _isSaving ? null : _addDraft,
icon: const Icon(Icons.add), icon: const Icon(Icons.add, size: 18),
label: const Text('Add shift'), label: const Text('Add shift'),
), ),
const Spacer(), const Spacer(),
FilledButton.icon( FilledButton.icon(
onPressed: _isSaving ? null : _commitDraft, onPressed: _isSaving ? null : _commitDraft,
icon: const Icon(Icons.check_circle), icon: _isSaving
label: _isSaving
? const SizedBox( ? const SizedBox(
height: 18, height: 16,
width: 18, width: 16,
child: CircularProgressIndicator(strokeWidth: 2), child: CircularProgressIndicator(
strokeWidth: 2,
color: Colors.white,
),
) )
: const Text('Commit schedule'), : const Icon(Icons.check_circle_outline, size: 18),
label: const Text('Commit schedule'),
), ),
], ],
), ),
@@ -924,9 +940,13 @@ class _ScheduleGeneratorPanelState
required VoidCallback onTap, required VoidCallback onTap,
}) { }) {
return InkWell( return InkWell(
borderRadius: BorderRadius.circular(4),
onTap: onTap, onTap: onTap,
child: InputDecorator( child: InputDecorator(
decoration: InputDecoration(labelText: label), decoration: InputDecoration(
labelText: label,
suffixIcon: const Icon(Icons.calendar_today_outlined, size: 18),
),
child: Text(value == null ? 'Select date' : AppTime.formatDate(value)), child: Text(value == null ? 'Select date' : AppTime.formatDate(value)),
), ),
); );
@@ -1013,17 +1033,25 @@ class _ScheduleGeneratorPanelState
Widget _buildWarningPanel(BuildContext context) { Widget _buildWarningPanel(BuildContext context) {
final colorScheme = Theme.of(context).colorScheme; final colorScheme = Theme.of(context).colorScheme;
return Container( return Container(
padding: const EdgeInsets.all(12), padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
decoration: BoxDecoration( decoration: BoxDecoration(
color: colorScheme.tertiaryContainer, color: colorScheme.errorContainer.withValues(alpha: 0.6),
borderRadius: BorderRadius.circular( borderRadius: BorderRadius.circular(
AppSurfaces.of(context).compactCardRadius, AppSurfaces.of(context).compactCardRadius,
), ),
border: Border.all(
color: colorScheme.error.withValues(alpha: 0.3),
width: 1,
),
), ),
child: Row( child: Row(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
Icon(Icons.warning_amber, color: colorScheme.onTertiaryContainer), Icon(
Icons.info_outline,
size: 18,
color: colorScheme.onErrorContainer,
),
const SizedBox(width: 8), const SizedBox(width: 8),
Expanded( Expanded(
child: Column( child: Column(
@@ -1031,17 +1059,20 @@ class _ScheduleGeneratorPanelState
children: [ children: [
Text( Text(
'Uncovered shifts', 'Uncovered shifts',
style: Theme.of(context).textTheme.titleSmall?.copyWith( style: Theme.of(context).textTheme.labelMedium?.copyWith(
fontWeight: FontWeight.w700, fontWeight: FontWeight.w700,
color: colorScheme.onTertiaryContainer, color: colorScheme.onErrorContainer,
), ),
), ),
const SizedBox(height: 6), const SizedBox(height: 4),
for (final warning in _warnings) for (final warning in _warnings)
Text( Padding(
padding: const EdgeInsets.only(top: 2),
child: Text(
warning, warning,
style: Theme.of(context).textTheme.bodySmall?.copyWith( style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: colorScheme.onTertiaryContainer, color: colorScheme.onErrorContainer,
),
), ),
), ),
], ],
@@ -1090,6 +1121,14 @@ class _ScheduleGeneratorPanelState
: id, : id,
) )
.toList(); .toList();
final colorScheme = Theme.of(context).colorScheme;
final shiftInitial =
_shiftLabel(draft.shiftType, rotationConfig).isNotEmpty
? _shiftLabel(
draft.shiftType,
rotationConfig,
)[0].toUpperCase()
: '?';
return Card( return Card(
child: Padding( child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10), padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
@@ -1097,6 +1136,24 @@ class _ScheduleGeneratorPanelState
children: [ children: [
Row( Row(
children: [ children: [
Container(
width: 36,
height: 36,
margin: const EdgeInsets.only(right: 10),
decoration: BoxDecoration(
color: colorScheme.primaryContainer,
borderRadius: BorderRadius.circular(8),
),
alignment: Alignment.center,
child: Text(
shiftInitial,
style: TextStyle(
color: colorScheme.onPrimaryContainer,
fontWeight: FontWeight.w700,
fontSize: 14,
),
),
),
Expanded( Expanded(
child: Column( child: Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
@@ -1106,9 +1163,9 @@ class _ScheduleGeneratorPanelState
style: Theme.of(context).textTheme.bodyMedium style: Theme.of(context).textTheme.bodyMedium
?.copyWith(fontWeight: FontWeight.w600), ?.copyWith(fontWeight: FontWeight.w600),
), ),
const SizedBox(height: 4), const SizedBox(height: 2),
Text( Text(
'${AppTime.formatDate(draft.startTime)} · ${AppTime.formatTime(draft.startTime)} - ${AppTime.formatTime(draft.endTime)}', '${AppTime.formatDate(draft.startTime)} · ${AppTime.formatTime(draft.startTime)} ${AppTime.formatTime(draft.endTime)}',
style: Theme.of(context).textTheme.bodySmall, style: Theme.of(context).textTheme.bodySmall,
), ),
], ],
@@ -1117,12 +1174,16 @@ class _ScheduleGeneratorPanelState
IconButton( IconButton(
tooltip: 'Edit', tooltip: 'Edit',
onPressed: () => _editDraft(draft), onPressed: () => _editDraft(draft),
icon: const Icon(Icons.edit), icon: const Icon(Icons.edit_outlined, size: 18),
), ),
IconButton( IconButton(
tooltip: 'Delete', tooltip: 'Delete',
onPressed: () => _deleteDraft(draft), onPressed: () => _deleteDraft(draft),
icon: const Icon(Icons.delete_outline), icon: Icon(
Icons.delete_outline,
size: 18,
color: colorScheme.error,
),
), ),
], ],
), ),
@@ -1180,10 +1241,16 @@ class _ScheduleGeneratorPanelState
return; return;
} }
final rotationConfig = ref.read(rotationConfigProvider).valueOrNull;
final shiftTypeConfigs =
rotationConfig?.shiftTypes ?? RotationConfig().shiftTypes;
final start = existing?.startTime ?? _startDate ?? AppTime.now(); final start = existing?.startTime ?? _startDate ?? AppTime.now();
var selectedDate = DateTime(start.year, start.month, start.day); var selectedDate = DateTime(start.year, start.month, start.day);
var selectedUserId = existing?.userId ?? staff.first.id; var selectedUserId = existing?.userId ?? staff.first.id;
var selectedShift = existing?.shiftType ?? 'am'; var selectedShift =
existing?.shiftType ??
(shiftTypeConfigs.isNotEmpty ? shiftTypeConfigs.first.id : 'am');
var startTime = TimeOfDay.fromDateTime(existing?.startTime ?? start); var startTime = TimeOfDay.fromDateTime(existing?.startTime ?? start);
var endTime = TimeOfDay.fromDateTime( var endTime = TimeOfDay.fromDateTime(
existing?.endTime ?? start.add(const Duration(hours: 8)), existing?.endTime ?? start.add(const Duration(hours: 8)),
@@ -1194,6 +1261,17 @@ class _ScheduleGeneratorPanelState
builder: (dialogContext) { builder: (dialogContext) {
return StatefulBuilder( return StatefulBuilder(
builder: (context, setDialogState) { builder: (context, setDialogState) {
final startMinutes = startTime.hour * 60 + startTime.minute;
final endMinutes = endTime.hour * 60 + endTime.minute;
final durationMinutes = endMinutes > startMinutes
? endMinutes - startMinutes
: (endMinutes + 1440) - startMinutes;
final durationHours = durationMinutes ~/ 60;
final durationRem = durationMinutes % 60;
final durationLabel = durationRem == 0
? '${durationHours}h'
: '${durationHours}h ${durationRem}m';
return AlertDialog( return AlertDialog(
title: Text(existing == null ? 'Add shift' : 'Edit shift'), title: Text(existing == null ? 'Add shift' : 'Edit shift'),
content: SingleChildScrollView( content: SingleChildScrollView(
@@ -1217,22 +1295,20 @@ class _ScheduleGeneratorPanelState
if (value == null) return; if (value == null) return;
setDialogState(() => selectedUserId = value); setDialogState(() => selectedUserId = value);
}, },
decoration: const InputDecoration(labelText: 'Assignee'), decoration: const InputDecoration(
labelText: 'Assignee',
filled: true,
),
), ),
const SizedBox(height: 12), const SizedBox(height: 12),
DropdownButtonFormField<String>( DropdownButtonFormField<String>(
initialValue: selectedShift, initialValue: selectedShift,
items: const [ items: [
DropdownMenuItem(value: 'am', child: Text('AM Duty')), for (final s in shiftTypeConfigs)
DropdownMenuItem( DropdownMenuItem(
value: 'normal', value: s.id,
child: Text('Normal Duty'), child: Text(s.label),
), ),
DropdownMenuItem(
value: 'on_call',
child: Text('On Call'),
),
DropdownMenuItem(value: 'pm', child: Text('PM Duty')),
], ],
onChanged: (value) { onChanged: (value) {
if (value == null) return; if (value == null) return;
@@ -1240,6 +1316,7 @@ class _ScheduleGeneratorPanelState
}, },
decoration: const InputDecoration( decoration: const InputDecoration(
labelText: 'Shift type', labelText: 'Shift type',
filled: true,
), ),
), ),
const SizedBox(height: 12), const SizedBox(height: 12),
@@ -1260,7 +1337,10 @@ class _ScheduleGeneratorPanelState
}, },
), ),
const SizedBox(height: 12), const SizedBox(height: 12),
_dialogTimeField( Row(
children: [
Expanded(
child: _dialogTimeField(
label: 'Start time', label: 'Start time',
value: startTime, value: startTime,
onTap: () async { onTap: () async {
@@ -1272,8 +1352,10 @@ class _ScheduleGeneratorPanelState
setDialogState(() => startTime = picked); setDialogState(() => startTime = picked);
}, },
), ),
const SizedBox(height: 12), ),
_dialogTimeField( const SizedBox(width: 8),
Expanded(
child: _dialogTimeField(
label: 'End time', label: 'End time',
value: endTime, value: endTime,
onTap: () async { onTap: () async {
@@ -1285,6 +1367,27 @@ class _ScheduleGeneratorPanelState
setDialogState(() => endTime = picked); setDialogState(() => endTime = picked);
}, },
), ),
),
],
),
const SizedBox(height: 12),
Align(
alignment: Alignment.centerLeft,
child: Chip(
avatar: const Icon(Icons.schedule, size: 16),
label: Text('Duration: $durationLabel'),
visualDensity: VisualDensity.compact,
backgroundColor: Theme.of(
context,
).colorScheme.secondaryContainer,
labelStyle: TextStyle(
color: Theme.of(
context,
).colorScheme.onSecondaryContainer,
fontSize: 12,
),
),
),
], ],
), ),
), ),
@@ -1295,7 +1398,7 @@ class _ScheduleGeneratorPanelState
), ),
FilledButton( FilledButton(
onPressed: () { onPressed: () {
final startDateTime = DateTime( var startDateTime = DateTime(
selectedDate.year, selectedDate.year,
selectedDate.month, selectedDate.month,
selectedDate.day, selectedDate.day,
@@ -1312,6 +1415,8 @@ class _ScheduleGeneratorPanelState
if (!endDateTime.isAfter(startDateTime)) { if (!endDateTime.isAfter(startDateTime)) {
endDateTime = endDateTime.add(const Duration(days: 1)); endDateTime = endDateTime.add(const Duration(days: 1));
} }
startDateTime = AppTime.toAppTime(startDateTime);
endDateTime = AppTime.toAppTime(endDateTime);
final draft = final draft =
existing ?? existing ??
@@ -1361,9 +1466,14 @@ class _ScheduleGeneratorPanelState
required VoidCallback onTap, required VoidCallback onTap,
}) { }) {
return InkWell( return InkWell(
borderRadius: BorderRadius.circular(4),
onTap: onTap, onTap: onTap,
child: InputDecorator( child: InputDecorator(
decoration: InputDecoration(labelText: label), decoration: InputDecoration(
labelText: label,
filled: true,
suffixIcon: const Icon(Icons.calendar_today_outlined, size: 18),
),
child: Text(value), child: Text(value),
), ),
); );
@@ -1375,9 +1485,14 @@ class _ScheduleGeneratorPanelState
required VoidCallback onTap, required VoidCallback onTap,
}) { }) {
return InkWell( return InkWell(
borderRadius: BorderRadius.circular(4),
onTap: onTap, onTap: onTap,
child: InputDecorator( child: InputDecorator(
decoration: InputDecoration(labelText: label), decoration: InputDecoration(
labelText: label,
filled: true,
suffixIcon: const Icon(Icons.schedule, size: 18),
),
child: Text(value.format(context)), child: Text(value.format(context)),
), ),
); );
+121 -28
View File
@@ -126,7 +126,7 @@ class AppScaffold extends ConsumerWidget {
} }
} }
class AppNavigationRail extends StatelessWidget { class AppNavigationRail extends StatefulWidget {
const AppNavigationRail({ const AppNavigationRail({
super.key, super.key,
required this.items, required this.items,
@@ -142,60 +142,153 @@ class AppNavigationRail extends StatelessWidget {
final String displayName; final String displayName;
final VoidCallback onLogout; final VoidCallback onLogout;
@override
State<AppNavigationRail> createState() => _AppNavigationRailState();
}
class _AppNavigationRailState extends State<AppNavigationRail> {
final _scrollController = ScrollController();
@override
void dispose() {
_scrollController.dispose();
super.dispose();
}
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final currentIndex = _currentIndex(location, items);
final cs = Theme.of(context).colorScheme; final cs = Theme.of(context).colorScheme;
final currentIndex = _currentIndex(widget.location, widget.items);
// M3 Expressive: tonal surface container instead of a hard border divider. // M3 Expressive: tonal surface container instead of a hard border divider.
// Custom scrollable layout replaces NavigationRail so items are reachable
// on small viewport heights (web, small laptop screens).
return Container( return Container(
decoration: BoxDecoration(color: cs.surfaceContainerLow), decoration: BoxDecoration(color: cs.surfaceContainerLow),
child: NavigationRail( child: Column(
backgroundColor: Colors.transparent, children: [
extended: extended, Padding(
selectedIndex: currentIndex,
onDestinationSelected: (value) {
items[value].onTap(context, onLogout: onLogout);
},
leading: Padding(
padding: EdgeInsets.symmetric( padding: EdgeInsets.symmetric(
vertical: extended ? 12 : 8, vertical: widget.extended ? 12 : 8,
horizontal: extended ? 16 : 0, horizontal: widget.extended ? 16 : 0,
), ),
child: Center( child: Center(
child: Image.asset( child: Image.asset(
'assets/tasq_ico.png', 'assets/tasq_ico.png',
width: extended ? 48 : 40, width: widget.extended ? 48 : 40,
height: extended ? 48 : 40, height: widget.extended ? 48 : 40,
), ),
), ),
), ),
trailing: Expanded( Expanded(
child: Align( child: Scrollbar(
alignment: Alignment.bottomCenter, controller: _scrollController,
child: Padding( child: SingleChildScrollView(
controller: _scrollController,
child: Column(
children: [
for (int i = 0; i < widget.items.length; i++)
_NavRailItem(
item: widget.items[i],
selected: i == currentIndex,
extended: widget.extended,
onTap: () => widget.items[i]
.onTap(context, onLogout: widget.onLogout),
),
],
),
),
),
),
Padding(
padding: const EdgeInsets.only(bottom: 16), padding: const EdgeInsets.only(bottom: 16),
child: IconButton( child: IconButton(
tooltip: 'Sign out', tooltip: 'Sign out',
onPressed: onLogout, onPressed: widget.onLogout,
icon: const Icon(Icons.logout), icon: const Icon(Icons.logout),
), ),
), ),
),
),
destinations: [
for (final item in items)
NavigationRailDestination(
icon: Icon(item.icon),
selectedIcon: Icon(item.selectedIcon ?? item.icon),
label: Text(item.label),
),
], ],
), ),
); );
} }
} }
class _NavRailItem extends StatelessWidget {
const _NavRailItem({
required this.item,
required this.selected,
required this.extended,
required this.onTap,
});
final NavItem item;
final bool selected;
final bool extended;
final VoidCallback onTap;
@override
Widget build(BuildContext context) {
final cs = Theme.of(context).colorScheme;
final icon = Icon(
selected ? (item.selectedIcon ?? item.icon) : item.icon,
size: 24,
color: selected ? cs.onSecondaryContainer : cs.onSurfaceVariant,
);
final indicator = AnimatedContainer(
duration: const Duration(milliseconds: 200),
width: 56,
height: 32,
decoration: BoxDecoration(
color: selected ? cs.secondaryContainer : Colors.transparent,
borderRadius: BorderRadius.circular(16),
),
child: Center(child: icon),
);
final Widget content = extended
? Padding(
padding: const EdgeInsets.symmetric(horizontal: 12),
child: Row(
children: [
indicator,
const SizedBox(width: 12),
Expanded(
child: Text(
item.label,
style: Theme.of(context).textTheme.labelLarge?.copyWith(
color: selected
? cs.onSecondaryContainer
: cs.onSurfaceVariant,
fontWeight: selected
? FontWeight.w600
: FontWeight.normal,
),
overflow: TextOverflow.ellipsis,
),
),
],
),
)
: Center(child: indicator);
final tile = InkWell(
onTap: onTap,
borderRadius: BorderRadius.circular(8),
child: SizedBox(
height: 56,
width: double.infinity,
child: content,
),
);
if (extended) return tile;
return Tooltip(message: item.label, child: tile);
}
}
class AppBottomNav extends StatelessWidget { class AppBottomNav extends StatelessWidget {
const AppBottomNav({ const AppBottomNav({
super.key, super.key,
+10 -10
View File
@@ -373,10 +373,10 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: characters name: characters
sha256: faf38497bda5ead2a8c7615f4f7939df04333478bf32e4173fcb06d428b5716b sha256: f71061c654a3380576a52b451dd5532377954cf9dbd272a78fc8479606670803
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "1.4.1" version: "1.4.0"
charcode: charcode:
dependency: transitive dependency: transitive
description: description:
@@ -802,10 +802,10 @@ packages:
dependency: "direct main" dependency: "direct main"
description: description:
name: flutter_keyboard_visibility name: flutter_keyboard_visibility
sha256: "4983655c26ab5b959252ee204c2fffa4afeb4413cd030455194ec0caa3b8e7cb" sha256: "98664be7be0e3ffca00de50f7f6a287ab62c763fc8c762e0a21584584a3ff4f8"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "5.4.1" version: "6.0.0"
flutter_keyboard_visibility_linux: flutter_keyboard_visibility_linux:
dependency: transitive dependency: transitive
description: description:
@@ -1337,18 +1337,18 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: matcher name: matcher
sha256: "12956d0ad8390bbcc63ca2e1469c0619946ccb52809807067a7020d57e647aa6" sha256: dc58c723c3c24bf8d3e2d3ad3f2f9d7bd9cf43ec6feaa64181775e60190153f2
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "0.12.18" version: "0.12.17"
material_color_utilities: material_color_utilities:
dependency: transitive dependency: transitive
description: description:
name: material_color_utilities name: material_color_utilities
sha256: "9c337007e82b1889149c82ed242ed1cb24a66044e30979c44912381e9be4c48b" sha256: f7142bb1154231d7ea5f96bc7bde4bda2a0945d2806bb11670e30b850d56bdec
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "0.13.0" version: "0.11.1"
meta: meta:
dependency: transitive dependency: transitive
description: description:
@@ -2038,10 +2038,10 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: test_api name: test_api
sha256: "93167629bfc610f71560ab9312acdda4959de4df6fac7492c89ff0d3886f6636" sha256: ab2726c1a94d3176a45960b6234466ec367179b87dd74f1611adb1f3b5fb9d55
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "0.7.9" version: "0.7.7"
timezone: timezone:
dependency: "direct main" dependency: "direct main"
description: description:
+3
View File
@@ -78,6 +78,9 @@ flutter:
- assets/ - assets/
- assets/fonts/ - assets/fonts/
dependency_overrides:
flutter_keyboard_visibility: ^6.0.0
flutter_launcher_icons: flutter_launcher_icons:
android: true android: true
ios: true ios: true
@@ -0,0 +1,43 @@
-- Fix: insert_it_service_request_with_number did not accept p_id, causing the
-- Flutter createRequest RPC call to fail because rpcParams always includes p_id
-- for offline-replay idempotency. Add p_id as an optional param; if supplied the
-- row uses that UUID (offline sync), otherwise a new one is generated (normal flow).
CREATE OR REPLACE FUNCTION insert_it_service_request_with_number(
p_event_name text,
p_services text[],
p_creator_id uuid,
p_id uuid DEFAULT NULL,
p_office_id uuid DEFAULT NULL,
p_requested_by text DEFAULT NULL,
p_requested_by_user_id uuid DEFAULT NULL,
p_status text DEFAULT 'draft'
)
RETURNS TABLE(id uuid, request_number text) AS $$
DECLARE
v_seq int;
v_id uuid;
v_number text;
BEGIN
SELECT COALESCE(MAX(
CAST(NULLIF(regexp_replace(r.request_number, '^ISR-\d{4}-', ''), '') AS int)
), 0) + 1
INTO v_seq
FROM it_service_requests r
WHERE r.request_number LIKE 'ISR-' || EXTRACT(YEAR FROM now())::text || '-%';
v_number := 'ISR-' || EXTRACT(YEAR FROM now())::text || '-' || LPAD(v_seq::text, 4, '0');
v_id := COALESCE(p_id, gen_random_uuid());
INSERT INTO it_service_requests (
id, request_number, event_name, services,
creator_id, office_id, requested_by, requested_by_user_id, status
)
VALUES (
v_id, v_number, p_event_name, p_services,
p_creator_id, p_office_id, p_requested_by, p_requested_by_user_id, p_status
);
RETURN QUERY SELECT v_id, v_number;
END;
$$ LANGUAGE plpgsql;
@@ -0,0 +1,61 @@
-- Fix overtime_check_in to accept p_accuracy and p_is_mocked.
-- Migration 20260504000000 added these to attendance_check_in/out but missed
-- overtime_check_in, causing a PostgREST "no candidate" error during overtime
-- check-in when Flutter passes these two params.
--
-- The attendance_logs columns check_in_accuracy and check_in_is_mocked already
-- exist (added in 20260504000000), so only the function signature needs updating.
CREATE OR REPLACE FUNCTION public.overtime_check_in(
p_lat double precision,
p_lng double precision,
p_justification text DEFAULT NULL,
p_accuracy double precision DEFAULT NULL,
p_is_mocked boolean DEFAULT false
) RETURNS uuid
LANGUAGE plpgsql SECURITY DEFINER
AS $$
DECLARE
v_uid uuid := auth.uid();
v_now timestamptz := now();
v_schedule_id uuid;
v_log_id uuid;
v_end_time timestamptz;
BEGIN
IF v_uid IS NULL THEN
RAISE EXCEPTION 'Not authenticated';
END IF;
v_end_time := v_now + interval '8 hours';
INSERT INTO duty_schedules (
user_id, shift_type, start_time, end_time,
status, check_in_at, check_in_location
)
VALUES (
v_uid, 'overtime', v_now, v_end_time,
'arrival'::duty_status, v_now,
ST_SetSRID(ST_MakePoint(p_lng, p_lat), 4326)::geography
)
RETURNING id INTO v_schedule_id;
INSERT INTO attendance_logs (
user_id, duty_schedule_id, check_in_at,
check_in_lat, check_in_lng,
justification, check_in_accuracy, check_in_is_mocked
)
VALUES (
v_uid, v_schedule_id, v_now,
p_lat, p_lng,
p_justification, p_accuracy, p_is_mocked
)
RETURNING id INTO v_log_id;
RETURN v_log_id;
END;
$$;
-- Drop the old 3-param attendance_check_in overload (from 20260307090000).
-- The 5-param version (with p_accuracy, p_is_mocked) is the only correct one.
-- Mirrors the cleanup done for attendance_check_out in 20260309090000.
DROP FUNCTION IF EXISTS public.attendance_check_in(uuid, double precision, double precision);
@@ -0,0 +1,4 @@
-- Add status column to network_devices for online/offline/warning indicators.
ALTER TABLE network_devices
ADD COLUMN IF NOT EXISTS status TEXT NOT NULL DEFAULT 'unknown'
CHECK (status IN ('online', 'offline', 'warning', 'unknown'));