Scroll: the Flutter operator console for the DBBASIC Object Server, for people building alongside AI agents.

0 downloads

dbbasic-scroll/lib/main.dart
Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-scroll.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-scroll.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-scroll.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

quellhorst Extension fields + schema conflict field names e8a817f 4 months, 1 week ago History
main.dart · 688.3 KB · 15679 lines
1import 'dart:async';
2import 'dart:convert';
3import 'dart:io';
4import 'package:file_selector/file_selector.dart';
5import 'package:flutter/material.dart';
6import 'api.dart';
7import 'data.dart';
8import 'realtime.dart';
9import 'schema_form.dart';
10
11/// Record keys that are internal plumbing, never shown as a data column:
12/// the id, the owner pointer, and the `extra` overflow blob (a JSON string
13/// holding collision-proof user data — its declared fields surface at top
14/// level, so the raw key itself is noise).
15const _internalRecordKeys = {'id', 'record_id', 'owner_id', 'extra'};
16
17void main() {
18 WidgetsFlutterBinding.ensureInitialized();
19 runApp(const ScrollApp());
20}
21
22class ScrollApp extends StatelessWidget {
23 const ScrollApp({super.key});
24
25 @override
26 Widget build(BuildContext context) {
27 return MaterialApp(
28 title: 'DBBasic Scroll',
29 debugShowCheckedModeBanner: false,
30 theme: ThemeData.dark(useMaterial3: true).copyWith(
31 colorScheme: ColorScheme.fromSeed(
32 seedColor: const Color(0xFF6C63FF),
33 brightness: Brightness.dark,
34 ),
35 ),
36 home: const ConnectScreen(),
37 );
38 }
39}
40
41// ---------------------------------------------------------------------------
42// Admin state — shared via InheritedWidget
43// ---------------------------------------------------------------------------
44
45class AdminState extends InheritedWidget {
46 final bool adminMode;
47 final VoidCallback onToggle;
48 const AdminState({
49 super.key,
50 required this.adminMode,
51 required this.onToggle,
52 required super.child,
53 });
54
55 static AdminState? of(BuildContext context) {
56 return context.dependOnInheritedWidgetOfExactType<AdminState>();
57 }
58
59 static bool isAdmin(BuildContext context) {
60 return of(context)?.adminMode ?? false;
61 }
62
63 @override
64 bool updateShouldNotify(AdminState oldWidget) =>
65 adminMode != oldWidget.adminMode;
66}
67
68// ---------------------------------------------------------------------------
69// AdminFieldOverlay — wraps any field to make it editable in admin mode
70// ---------------------------------------------------------------------------
71
72class AdminFieldOverlay extends StatefulWidget {
73 final Widget child;
74 final String fieldName;
75 final String fieldType;
76 final Map<String, String> rolePermissions; // role -> 'edit'|'read'|'hidden'
77 final bool required;
78
79 const AdminFieldOverlay({
80 super.key,
81 required this.child,
82 required this.fieldName,
83 this.fieldType = 'text',
84 this.rolePermissions = const {},
85 this.required = false,
86 });
87
88 @override
89 State<AdminFieldOverlay> createState() => _AdminFieldOverlayState();
90}
91
92class _AdminFieldOverlayState extends State<AdminFieldOverlay> {
93 bool _hovered = false;
94 bool _editing = false;
95
96 @override
97 Widget build(BuildContext context) {
98 final isAdmin = AdminState.isAdmin(context);
99 if (!isAdmin) return widget.child;
100
101 return Column(
102 crossAxisAlignment: CrossAxisAlignment.start,
103 children: [
104 MouseRegion(
105 onEnter: (_) => setState(() => _hovered = true),
106 onExit: (_) => setState(() => _hovered = false),
107 child: GestureDetector(
108 onTap: () => setState(() => _editing = !_editing),
109 child: Stack(
110 children: [
111 Container(
112 decoration: BoxDecoration(
113 border: Border.all(
114 color: _editing
115 ? Colors.amber
116 : (_hovered
117 ? Colors.amber.withOpacity(0.7)
118 : Colors.amber.withOpacity(0.4)),
119 width: _editing ? 2 : 1.5,
120 strokeAlign: BorderSide.strokeAlignOutside,
121 ),
122 borderRadius: BorderRadius.circular(6),
123 color: _hovered ? Colors.amber.withOpacity(0.03) : null,
124 ),
125 child: IgnorePointer(ignoring: true, child: widget.child),
126 ),
127 // Edit badge
128 Positioned(
129 top: -8,
130 right: -4,
131 child: AnimatedOpacity(
132 opacity: _hovered || _editing ? 1.0 : 0.7,
133 duration: const Duration(milliseconds: 150),
134 child: Container(
135 padding: const EdgeInsets.symmetric(
136 horizontal: 6,
137 vertical: 2,
138 ),
139 decoration: BoxDecoration(
140 color: Colors.amber,
141 borderRadius: BorderRadius.circular(4),
142 ),
143 child: Row(
144 mainAxisSize: MainAxisSize.min,
145 children: [
146 Icon(Icons.edit, size: 10, color: Colors.black87),
147 const SizedBox(width: 2),
148 Text(
149 widget.fieldName,
150 style: TextStyle(
151 fontSize: 9,
152 color: Colors.black87,
153 fontWeight: FontWeight.bold,
154 ),
155 ),
156 ],
157 ),
158 ),
159 ),
160 ),
161 ],
162 ),
163 ),
164 ),
165 // Inline config panel
166 if (_editing) _buildConfigPanel(context),
167 ],
168 );
169 }
170
171 Widget _buildConfigPanel(BuildContext context) {
172 return Container(
173 margin: const EdgeInsets.only(top: 4, bottom: 8),
174 padding: const EdgeInsets.all(12),
175 decoration: BoxDecoration(
176 color: Colors.amber.withOpacity(0.06),
177 borderRadius: BorderRadius.circular(8),
178 border: Border.all(color: Colors.amber.withOpacity(0.25)),
179 ),
180 child: Column(
181 crossAxisAlignment: CrossAxisAlignment.start,
182 children: [
183 Row(
184 children: [
185 Icon(Icons.settings, size: 14, color: Colors.amber),
186 const SizedBox(width: 6),
187 Text(
188 'FIELD CONFIG',
189 style: TextStyle(
190 fontSize: 10,
191 fontWeight: FontWeight.bold,
192 color: Colors.amber,
193 letterSpacing: 1,
194 ),
195 ),
196 const Spacer(),
197 InkWell(
198 onTap: () => setState(() => _editing = false),
199 child: Icon(Icons.close, size: 16, color: Colors.white38),
200 ),
201 ],
202 ),
203 const SizedBox(height: 12),
204 Row(
205 children: [
206 // Field name
207 Expanded(
208 child: SizedBox(
209 height: 36,
210 child: TextField(
211 controller: TextEditingController(text: widget.fieldName),
212 decoration: const InputDecoration(
213 labelText: 'Field Name',
214 border: OutlineInputBorder(),
215 isDense: true,
216 contentPadding: EdgeInsets.symmetric(
217 horizontal: 10,
218 vertical: 8,
219 ),
220 ),
221 style: const TextStyle(fontSize: 12),
222 ),
223 ),
224 ),
225 const SizedBox(width: 8),
226 // Type
227 Expanded(
228 child: SizedBox(
229 height: 36,
230 child: DropdownButtonFormField<String>(
231 value: widget.fieldType,
232 decoration: const InputDecoration(
233 labelText: 'Type',
234 border: OutlineInputBorder(),
235 isDense: true,
236 contentPadding: EdgeInsets.symmetric(
237 horizontal: 10,
238 vertical: 8,
239 ),
240 ),
241 style: const TextStyle(fontSize: 12),
242 items:
243 [
244 'text',
245 'number',
246 'currency',
247 'date',
248 'email',
249 'phone',
250 'dropdown',
251 'relation',
252 'computed',
253 'textarea',
254 'checkbox',
255 'file',
256 ]
257 .map(
258 (t) => DropdownMenuItem(
259 value: t,
260 child: Text(
261 t,
262 style: const TextStyle(fontSize: 12),
263 ),
264 ),
265 )
266 .toList(),
267 onChanged: (_) {},
268 ),
269 ),
270 ),
271 const SizedBox(width: 8),
272 // Required
273 Row(
274 children: [
275 Checkbox(
276 value: widget.required,
277 onChanged: (_) {},
278 visualDensity: VisualDensity.compact,
279 ),
280 Text(
281 'Required',
282 style: TextStyle(fontSize: 12, color: Colors.white54),
283 ),
284 ],
285 ),
286 ],
287 ),
288 const SizedBox(height: 12),
289 // Role permissions
290 Text(
291 'ROLE PERMISSIONS',
292 style: TextStyle(
293 fontSize: 10,
294 fontWeight: FontWeight.bold,
295 color: Colors.white38,
296 letterSpacing: 1,
297 ),
298 ),
299 const SizedBox(height: 8),
300 _rolePermRow('admin', 'edit'),
301 _rolePermRow('manager', 'edit'),
302 _rolePermRow('sales', widget.rolePermissions['sales'] ?? 'edit'),
303 _rolePermRow('viewer', 'read'),
304 const SizedBox(height: 8),
305 Row(
306 children: [
307 FilledButton(
308 onPressed: () => setState(() => _editing = false),
309 style: FilledButton.styleFrom(
310 backgroundColor: Colors.amber,
311 foregroundColor: Colors.black87,
312 padding: const EdgeInsets.symmetric(horizontal: 16),
313 visualDensity: VisualDensity.compact,
314 ),
315 child: const Text('Apply', style: TextStyle(fontSize: 12)),
316 ),
317 const SizedBox(width: 8),
318 TextButton(
319 onPressed: () => setState(() => _editing = false),
320 child: const Text('Cancel', style: TextStyle(fontSize: 12)),
321 ),
322 const Spacer(),
323 TextButton.icon(
324 onPressed: () {},
325 icon: Icon(
326 Icons.delete_outline,
327 size: 14,
328 color: Colors.red[300],
329 ),
330 label: Text(
331 'Remove Field',
332 style: TextStyle(fontSize: 12, color: Colors.red[300]),
333 ),
334 ),
335 ],
336 ),
337 ],
338 ),
339 );
340 }
341
342 Widget _rolePermRow(String role, String perm) {
343 return Padding(
344 padding: const EdgeInsets.symmetric(vertical: 2),
345 child: Row(
346 children: [
347 SizedBox(
348 width: 80,
349 child: Text(
350 role,
351 style: TextStyle(fontSize: 12, color: Colors.white54),
352 ),
353 ),
354 const SizedBox(width: 8),
355 _permRadio('edit', perm),
356 _permRadio('read', perm),
357 _permRadio('hidden', perm),
358 ],
359 ),
360 );
361 }
362
363 Widget _permRadio(String value, String current) {
364 final selected = value == current;
365 final color = switch (value) {
366 'edit' => Colors.green,
367 'read' => Colors.orange,
368 'hidden' => Colors.red,
369 _ => Colors.grey,
370 };
371 return Padding(
372 padding: const EdgeInsets.only(right: 12),
373 child: InkWell(
374 onTap: () {},
375 child: Row(
376 mainAxisSize: MainAxisSize.min,
377 children: [
378 Container(
379 width: 14,
380 height: 14,
381 decoration: BoxDecoration(
382 shape: BoxShape.circle,
383 border: Border.all(
384 color: selected ? color : Colors.white24,
385 width: 2,
386 ),
387 color: selected ? color.withOpacity(0.3) : Colors.transparent,
388 ),
389 child: selected
390 ? Center(
391 child: Container(
392 width: 6,
393 height: 6,
394 decoration: BoxDecoration(
395 shape: BoxShape.circle,
396 color: color,
397 ),
398 ),
399 )
400 : null,
401 ),
402 const SizedBox(width: 4),
403 Text(
404 value,
405 style: TextStyle(
406 fontSize: 11,
407 color: selected ? color : Colors.white38,
408 ),
409 ),
410 ],
411 ),
412 ),
413 );
414 }
415}
416
417// ---------------------------------------------------------------------------
418// Connect Screen
419// ---------------------------------------------------------------------------
420
421class ConnectScreen extends StatefulWidget {
422 const ConnectScreen({super.key});
423
424 @override
425 State<ConnectScreen> createState() => _ConnectScreenState();
426}
427
428class _ConnectScreenState extends State<ConnectScreen> {
429 final _objUrlController = TextEditingController();
430 final _platUrlController = TextEditingController();
431 final _tokenController = TextEditingController();
432 final _emailController = TextEditingController();
433 final _passwordController = TextEditingController();
434 bool _usePasswordLogin = false;
435 bool _connecting = false;
436 String? _error;
437 String? _status;
438
439 @override
440 void initState() {
441 super.initState();
442 _tryAutoConnect();
443 }
444
445 Future<void> _tryAutoConnect() async {
446 final api = ScrollAPI();
447 await api.loadSavedConnection();
448 if (api.isConnected && mounted) {
449 Navigator.of(
450 context,
451 ).pushReplacement(MaterialPageRoute(builder: (_) => const MainShell()));
452 return;
453 }
454 // Dev mode: load connection defaults from .env (see .env.example)
455 try {
456 final envFile = File('.env');
457 if (await envFile.exists()) {
458 final lines = await envFile.readAsLines();
459 for (final line in lines) {
460 if (line.startsWith('OBJECT_SERVER_URL=')) {
461 final url = line.substring('OBJECT_SERVER_URL='.length).trim();
462 if (url.isNotEmpty) _objUrlController.text = url;
463 } else if (line.startsWith('PLATFORM_URL=')) {
464 final url = line.substring('PLATFORM_URL='.length).trim();
465 if (url.isNotEmpty) _platUrlController.text = url;
466 } else if (line.startsWith('DBBASIC_ADMIN_TOKEN=')) {
467 final token = line.substring('DBBASIC_ADMIN_TOKEN='.length).trim();
468 if (token.isNotEmpty) _tokenController.text = token;
469 } else if (line.startsWith('ASKROBOTS_TOKEN=')) {
470 final token = line.substring('ASKROBOTS_TOKEN='.length).trim();
471 if (token.isNotEmpty) _tokenController.text = token;
472 }
473 // Dev convenience: auto-import OpenAI key from .env if user hasn't set one yet
474 if (line.startsWith('OPENAI_API_KEY=')) {
475 final existing = await ScrollAPI().getOpenAIKey();
476 if (existing == null || existing.isEmpty) {
477 final key = line.substring('OPENAI_API_KEY='.length).trim();
478 if (key.isNotEmpty) await ScrollAPI().setOpenAIKey(key);
479 }
480 }
481 }
482 }
483 } catch (_) {}
484 }
485
486 Future<void> _connect() async {
487 setState(() {
488 _connecting = true;
489 _error = null;
490 _status = _usePasswordLogin
491 ? 'Signing in...'
492 : 'Testing object server...';
493 });
494 var token = _tokenController.text.trim();
495 if (_usePasswordLogin) {
496 final api = ScrollAPI();
497 final login = await api.loginWithPassword(
498 objectServerUrl: _objUrlController.text.trim(),
499 email: _emailController.text,
500 password: _passwordController.text,
501 label: 'scroll login',
502 );
503 if (!mounted) return;
504 final status = login['status'];
505 final sessionToken = api.sessionTokenFromLogin(login);
506 if (status is! int || status < 200 || status >= 300) {
507 final body = login['body'];
508 final detail = body is Map && body['error'] != null
509 ? body['error'].toString()
510 : (login['error']?.toString() ?? 'HTTP $status');
511 setState(() {
512 _connecting = false;
513 // 429 is the login lockout — the server message says it all.
514 _error = status == 429 ? detail : 'Sign-in failed: $detail';
515 _status = null;
516 });
517 return;
518 }
519 if (sessionToken == null) {
520 setState(() {
521 _connecting = false;
522 _error = 'Sign-in succeeded but no session token was returned.';
523 _status = null;
524 });
525 return;
526 }
527 token = sessionToken;
528 await api.setSessionUser(api.sessionUserIdFromLogin(login));
529 setState(() => _status = 'Signed in — connecting session...');
530 } else {
531 // Deployment-token connection: no user identity behind the token.
532 await ScrollAPI().setSessionUser(null);
533 }
534 final success = await ScrollAPI().connect(
535 objectServerUrl: _objUrlController.text.trim(),
536 token: token,
537 platformUrl: _platUrlController.text.trim().isEmpty
538 ? null
539 : _platUrlController.text.trim(),
540 );
541 if (!mounted) return;
542 if (success) {
543 final api = ScrollAPI();
544 setState(() {
545 _status =
546 'Connected! Object server${api.hasPlatform ? " + platform" : ""}';
547 });
548 await Future.delayed(const Duration(milliseconds: 500));
549 if (!mounted) return;
550 Navigator.of(
551 context,
552 ).pushReplacement(MaterialPageRoute(builder: (_) => const MainShell()));
553 } else {
554 setState(() {
555 _connecting = false;
556 _error = 'Could not connect. Check object server URL.';
557 _status = null;
558 });
559 }
560 }
561
562 @override
563 Widget build(BuildContext context) {
564 return Scaffold(
565 body: Center(
566 child: SingleChildScrollView(
567 padding: const EdgeInsets.symmetric(vertical: 24),
568 child: Container(
569 width: 460,
570 padding: const EdgeInsets.all(32),
571 child: Column(
572 mainAxisSize: MainAxisSize.min,
573 children: [
574 Icon(
575 Icons.auto_stories,
576 size: 64,
577 color: Theme.of(context).colorScheme.primary,
578 ),
579 const SizedBox(height: 16),
580 Text(
581 'DBBasic Scroll',
582 style: Theme.of(context).textTheme.headlineMedium,
583 ),
584 const SizedBox(height: 4),
585 Text(
586 'Connect to your object server',
587 style: Theme.of(
588 context,
589 ).textTheme.bodyMedium?.copyWith(color: Colors.white54),
590 ),
591 const SizedBox(height: 32),
592 TextField(
593 controller: _objUrlController,
594 decoration: const InputDecoration(
595 labelText: 'Object Server URL (required)',
596 prefixIcon: Icon(Icons.dns_outlined),
597 border: OutlineInputBorder(),
598 hintText: 'https://object.example.com',
599 ),
600 enabled: !_connecting,
601 ),
602 const SizedBox(height: 12),
603 TextField(
604 controller: _platUrlController,
605 decoration: InputDecoration(
606 labelText: 'Platform URL (optional)',
607 prefixIcon: Icon(Icons.cloud_outlined),
608 border: OutlineInputBorder(),
609 hintText: 'https://askrobots.com',
610 helperText:
611 'Adds collections: contacts, tasks, invoices, etc.',
612 helperStyle: TextStyle(fontSize: 11, color: Colors.white24),
613 ),
614 enabled: !_connecting,
615 ),
616 const SizedBox(height: 12),
617 SizedBox(
618 width: double.infinity,
619 child: SegmentedButton<bool>(
620 segments: const [
621 ButtonSegment(
622 value: false,
623 label: Text('Admin Token'),
624 icon: Icon(Icons.key_outlined, size: 16),
625 ),
626 ButtonSegment(
627 value: true,
628 label: Text('Email + Password'),
629 icon: Icon(Icons.person_outline, size: 16),
630 ),
631 ],
632 selected: {_usePasswordLogin},
633 onSelectionChanged: _connecting
634 ? null
635 : (selection) => setState(
636 () => _usePasswordLogin = selection.first,
637 ),
638 ),
639 ),
640 const SizedBox(height: 12),
641 if (_usePasswordLogin) ...[
642 TextField(
643 controller: _emailController,
644 decoration: const InputDecoration(
645 labelText: 'Email',
646 prefixIcon: Icon(Icons.alternate_email_outlined),
647 border: OutlineInputBorder(),
648 ),
649 enabled: !_connecting,
650 ),
651 const SizedBox(height: 12),
652 TextField(
653 controller: _passwordController,
654 obscureText: true,
655 decoration: InputDecoration(
656 labelText: 'Password',
657 prefixIcon: const Icon(Icons.password_outlined),
658 border: const OutlineInputBorder(),
659 helperText:
660 'Signs in through POST /identity/session and uses the returned session token. Admin screens stay locked unless the server enables session admin gates.',
661 helperMaxLines: 3,
662 helperStyle: TextStyle(
663 fontSize: 11,
664 color: Colors.white24,
665 ),
666 ),
667 enabled: !_connecting,
668 onSubmitted: (_) => _connect(),
669 ),
670 ] else
671 TextField(
672 controller: _tokenController,
673 obscureText: true,
674 decoration: InputDecoration(
675 labelText: 'Bearer Token',
676 prefixIcon: const Icon(Icons.key_outlined),
677 border: const OutlineInputBorder(),
678 helperText:
679 'Use an admin token on staging; admin-role session tokens are only accepted when the server enables session admin gates.',
680 helperStyle: TextStyle(
681 fontSize: 11,
682 color: Colors.white24,
683 ),
684 ),
685 enabled: !_connecting,
686 onSubmitted: (_) => _connect(),
687 ),
688 if (_error != null) ...[
689 const SizedBox(height: 12),
690 Text(
691 _error!,
692 style: TextStyle(color: Colors.red[300], fontSize: 13),
693 ),
694 ],
695 if (_status != null) ...[
696 const SizedBox(height: 12),
697 Text(
698 _status!,
699 style: TextStyle(color: Colors.green, fontSize: 13),
700 ),
701 ],
702 const SizedBox(height: 24),
703 SizedBox(
704 width: double.infinity,
705 child: FilledButton.icon(
706 onPressed: _connecting ? null : _connect,
707 icon: _connecting
708 ? const SizedBox(
709 width: 16,
710 height: 16,
711 child: CircularProgressIndicator(
712 strokeWidth: 2,
713 color: Colors.white,
714 ),
715 )
716 : const Icon(Icons.login),
717 label: Text(
718 _connecting
719 ? 'Connecting...'
720 : _usePasswordLogin
721 ? 'Sign In'
722 : 'Connect',
723 ),
724 ),
725 ),
726 const SizedBox(height: 12),
727 TextButton(
728 onPressed: () {},
729 child: const Text('Saved Connections'),
730 ),
731 ],
732 ),
733 ),
734 ),
735 ),
736 );
737 }
738}
739
740// ---------------------------------------------------------------------------
741// Main Shell
742// ---------------------------------------------------------------------------
743
744class MainShell extends StatefulWidget {
745 const MainShell({super.key});
746
747 @override
748 State<MainShell> createState() => _MainShellState();
749}
750
751class _MainShellState extends State<MainShell> {
752 final List<_Screen> _history = [];
753 late _Screen _current;
754 bool _adminMode = false;
755 int _adminNav = -1; // -1 = no admin nav selected (show user content)
756
757 final _adminNavItems = [
758 _NavItem('Home', Icons.home_outlined),
759 _NavItem('Search', Icons.search_outlined),
760 _NavItem('Chat', Icons.forum_outlined),
761 _NavItem('Collections', Icons.storage_outlined),
762 _NavItem('Objects', Icons.code_outlined),
763 _NavItem('Stations', Icons.dns_outlined),
764 _NavItem('Users', Icons.manage_accounts_outlined),
765 _NavItem('Permissions', Icons.security_outlined),
766 _NavItem('API', Icons.api_outlined),
767 _NavItem('SQL', Icons.terminal_outlined),
768 _NavItem('Daemon', Icons.hub_outlined),
769 _NavItem('Changes', Icons.manage_history_outlined),
770 _NavItem('Ops', Icons.monitor_heart_outlined),
771 _NavItem('Files', Icons.folder_outlined),
772 _NavItem('Schema', Icons.schema_outlined),
773 _NavItem('Diagram', Icons.account_tree_outlined),
774 _NavItem('Packages', Icons.extension_outlined),
775 _NavItem('Backup', Icons.backup_outlined),
776 ];
777
778 @override
779 void initState() {
780 super.initState();
781 _current = _Screen('Home', const SwitchboardView(), Icons.home);
782 ScrollAPI().authRejected.addListener(_onAuthRejected);
783 _loadData();
784 }
785
786 @override
787 void dispose() {
788 ScrollAPI().authRejected.removeListener(_onAuthRejected);
789 super.dispose();
790 }
791
792 bool _authDialogShowing = false;
793
794 void _onAuthRejected() {
795 if (!mounted || !ScrollAPI().authRejected.value || _authDialogShowing) {
796 return;
797 }
798 _authDialogShowing = true;
799 showDialog<void>(
800 context: context,
801 builder: (dialogContext) {
802 return AlertDialog(
803 title: const Text('Session expired'),
804 content: const Text(
805 'The server rejected the saved credential (HTTP 401). '
806 'Session tokens expire after their TTL — sign in again to '
807 'continue. Screens will show stale or missing data until then.',
808 ),
809 actions: [
810 TextButton(
811 onPressed: () => Navigator.of(dialogContext).pop(),
812 child: const Text('Not Now'),
813 ),
814 FilledButton.icon(
815 onPressed: () async {
816 Navigator.of(dialogContext).pop();
817 ScrollRealtime().shutdown();
818 await ScrollAPI().disconnect();
819 ScrollData().clear();
820 if (!mounted) return;
821 Navigator.of(context).pushAndRemoveUntil(
822 MaterialPageRoute(builder: (_) => const ConnectScreen()),
823 (route) => false,
824 );
825 },
826 icon: const Icon(Icons.login, size: 16),
827 label: const Text('Sign In Again'),
828 ),
829 ],
830 );
831 },
832 ).then((_) => _authDialogShowing = false);
833 }
834
835 Future<void> _loadData() async {
836 await ScrollData().loadAll();
837 if (mounted) setState(() {});
838 }
839
840 void _navigate(
841 String title,
842 Widget view, [
843 IconData icon = Icons.arrow_forward,
844 ]) {
845 setState(() {
846 _history.add(_current);
847 _current = _Screen(title, view, icon);
848 _adminNav = -1;
849 });
850 }
851
852 void _goBack() {
853 if (_history.isNotEmpty) {
854 setState(() {
855 _current = _history.removeLast();
856 _adminNav = -1;
857 });
858 }
859 }
860
861 void _goHome() {
862 setState(() {
863 _history.clear();
864 _current = _Screen('Home', const SwitchboardView(), Icons.home);
865 _adminNav = -1;
866 });
867 }
868
869 void _selectAdminNav(int index) {
870 setState(() => _adminNav = index);
871 }
872
873 Widget _getAdminView() {
874 return switch (_adminNav) {
875 0 => SwitchboardView(onNavigate: _navigate),
876 1 => const GlobalSearchView(),
877 2 => const AIChatView(),
878 3 => const CollectionBrowser(),
879 4 => ObjectWorkspace(onNavigate: _navigate),
880 5 => StationMonitor(onNavigate: _navigate),
881 6 => const IdentityRegistryView(),
882 7 => const PermissionsView(),
883 8 => const APIExplorerView(),
884 9 => const SQLQueryView(),
885 10 => const DaemonStatusView(),
886 11 => const ChangesView(),
887 12 => const OpsEventsView(),
888 13 => const FileManagerView(),
889 14 => const SchemaEditorView(),
890 15 => const DiagramView(),
891 16 => const PackageManagerView(),
892 17 => const BackupView(),
893 _ => SwitchboardView(onNavigate: _navigate),
894 };
895 }
896
897 @override
898 Widget build(BuildContext context) {
899 Widget currentView = _current.view;
900 if (currentView is SwitchboardView) {
901 currentView = SwitchboardView(onNavigate: _navigate);
902 }
903
904 // When admin nav is active, show that view instead
905 final showAdminNav = _adminMode && _adminNav >= 0;
906 final displayView = showAdminNav ? _getAdminView() : currentView;
907 final displayTitle = showAdminNav
908 ? _adminNavItems[_adminNav].label
909 : _current.title;
910
911 return AdminState(
912 adminMode: _adminMode,
913 onToggle: () => setState(() {
914 _adminMode = !_adminMode;
915 if (!_adminMode) _adminNav = -1;
916 }),
917 child: Scaffold(
918 body: Column(
919 children: [
920 _AppBar(
921 title: displayTitle,
922 canGoBack: _history.isNotEmpty && !showAdminNav,
923 adminMode: _adminMode,
924 onBack: _goBack,
925 onHome: _goHome,
926 onAdminToggle: () => setState(() {
927 _adminMode = !_adminMode;
928 if (!_adminMode) _adminNav = -1;
929 }),
930 onNavigate: _navigate,
931 ),
932 // Admin editing banner when viewing user content in admin mode
933 if (_adminMode && _adminNav < 0 && _current.title != 'Home')
934 Container(
935 height: 32,
936 padding: const EdgeInsets.symmetric(horizontal: 16),
937 color: Colors.amber.withOpacity(0.08),
938 child: Row(
939 children: [
940 Icon(Icons.edit, size: 14, color: Colors.amber),
941 const SizedBox(width: 6),
942 Text(
943 'Admin Edit Mode — click any field to configure it',
944 style: TextStyle(fontSize: 12, color: Colors.amber),
945 ),
946 const Spacer(),
947 TextButton.icon(
948 onPressed: () {},
949 icon: Icon(Icons.add, size: 14),
950 label: Text('Add Field', style: TextStyle(fontSize: 12)),
951 style: TextButton.styleFrom(
952 foregroundColor: Colors.amber,
953 visualDensity: VisualDensity.compact,
954 ),
955 ),
956 TextButton.icon(
957 onPressed: () {},
958 icon: Icon(Icons.save, size: 14),
959 label: Text(
960 'Save Layout',
961 style: TextStyle(fontSize: 12),
962 ),
963 style: TextButton.styleFrom(
964 foregroundColor: Colors.amber,
965 visualDensity: VisualDensity.compact,
966 ),
967 ),
968 ],
969 ),
970 ),
971 Expanded(
972 child: Row(
973 children: [
974 if (_adminMode) _buildAdminNavRail(context),
975 if (_adminMode) Container(width: 1, color: Colors.white10),
976 Expanded(child: displayView),
977 ],
978 ),
979 ),
980 ],
981 ),
982 bottomNavigationBar: _StatusBar(adminMode: _adminMode),
983 ),
984 );
985 }
986
987 Widget _buildAdminNavRail(BuildContext context) {
988 return Container(
989 width: 76,
990 color: Theme.of(context).colorScheme.surface,
991 child: Column(
992 children: [
993 const SizedBox(height: 4),
994 Expanded(
995 child: ListView(
996 padding: EdgeInsets.zero,
997 children: List.generate(_adminNavItems.length, (i) {
998 final item = _adminNavItems[i];
999 final selected = _adminNav == i;
1000 return InkWell(
1001 onTap: () => _selectAdminNav(i),
1002 child: Container(
1003 width: 76,
1004 padding: const EdgeInsets.symmetric(vertical: 6),
1005 decoration: BoxDecoration(
1006 color: selected
1007 ? Theme.of(
1008 context,
1009 ).colorScheme.primaryContainer.withOpacity(0.3)
1010 : null,
1011 border: selected
1012 ? Border(
1013 left: BorderSide(
1014 color: Theme.of(context).colorScheme.primary,
1015 width: 3,
1016 ),
1017 )
1018 : null,
1019 ),
1020 child: Column(
1021 mainAxisSize: MainAxisSize.min,
1022 children: [
1023 Icon(
1024 item.icon,
1025 size: 18,
1026 color: selected
1027 ? Theme.of(context).colorScheme.primary
1028 : Colors.white38,
1029 ),
1030 const SizedBox(height: 2),
1031 Text(
1032 item.label,
1033 style: TextStyle(
1034 fontSize: 10,
1035 fontWeight: selected
1036 ? FontWeight.bold
1037 : FontWeight.normal,
1038 color: selected
1039 ? Theme.of(context).colorScheme.primary
1040 : Colors.white54,
1041 ),
1042 textAlign: TextAlign.center,
1043 overflow: TextOverflow.ellipsis,
1044 ),
1045 ],
1046 ),
1047 ),
1048 );
1049 }),
1050 ),
1051 ),
1052 const Divider(indent: 12, endIndent: 12, height: 1),
1053 Row(
1054 mainAxisAlignment: MainAxisAlignment.spaceEvenly,
1055 children: [
1056 IconButton(
1057 onPressed: () {},
1058 icon: const Icon(
1059 Icons.auto_awesome,
1060 size: 16,
1061 color: Colors.amber,
1062 ),
1063 tooltip: 'AI Assistant',
1064 visualDensity: VisualDensity.compact,
1065 padding: EdgeInsets.zero,
1066 constraints: const BoxConstraints(minWidth: 28, minHeight: 28),
1067 ),
1068 IconButton(
1069 onPressed: () =>
1070 _navigate('Settings', const SettingsView(), Icons.settings),
1071 icon: const Icon(
1072 Icons.settings_outlined,
1073 size: 16,
1074 color: Colors.white38,
1075 ),
1076 tooltip: 'Settings',
1077 visualDensity: VisualDensity.compact,
1078 padding: EdgeInsets.zero,
1079 constraints: const BoxConstraints(minWidth: 28, minHeight: 28),
1080 ),
1081 ],
1082 ),
1083 const SizedBox(height: 4),
1084 ],
1085 ),
1086 );
1087 }
1088}
1089
1090class _NavItem {
1091 final String label;
1092 final IconData icon;
1093 _NavItem(this.label, this.icon);
1094}
1095
1096class _Screen {
1097 final String title;
1098 final Widget view;
1099 final IconData icon;
1100 _Screen(this.title, this.view, this.icon);
1101}
1102
1103// ---------------------------------------------------------------------------
1104// App Bar
1105// ---------------------------------------------------------------------------
1106
1107class _AppBar extends StatelessWidget {
1108 final String title;
1109 final bool canGoBack;
1110 final bool adminMode;
1111 final VoidCallback onBack;
1112 final VoidCallback onHome;
1113 final VoidCallback onAdminToggle;
1114 final void Function(String, Widget, [IconData]) onNavigate;
1115
1116 const _AppBar({
1117 required this.title,
1118 required this.canGoBack,
1119 required this.adminMode,
1120 required this.onBack,
1121 required this.onHome,
1122 required this.onAdminToggle,
1123 required this.onNavigate,
1124 });
1125
1126 @override
1127 Widget build(BuildContext context) {
1128 return Container(
1129 height: 52,
1130 padding: const EdgeInsets.symmetric(horizontal: 12),
1131 decoration: BoxDecoration(
1132 color: Theme.of(context).colorScheme.surfaceContainerLow,
1133 border: Border(bottom: BorderSide(color: Colors.white10)),
1134 ),
1135 child: Row(
1136 children: [
1137 if (canGoBack)
1138 IconButton(
1139 onPressed: onBack,
1140 icon: const Icon(Icons.arrow_back, size: 20),
1141 tooltip: 'Back',
1142 ),
1143 if (canGoBack) const SizedBox(width: 4),
1144 InkWell(
1145 onTap: onHome,
1146 borderRadius: BorderRadius.circular(6),
1147 child: Row(
1148 mainAxisSize: MainAxisSize.min,
1149 children: [
1150 Icon(
1151 Icons.auto_stories,
1152 color: Theme.of(context).colorScheme.primary,
1153 size: 22,
1154 ),
1155 const SizedBox(width: 10),
1156 Text(
1157 title == 'Home' ? 'DBBasic Scroll' : title,
1158 style: Theme.of(context).textTheme.titleMedium,
1159 ),
1160 ],
1161 ),
1162 ),
1163 const Spacer(),
1164 // AI bar
1165 SizedBox(
1166 width: 340,
1167 height: 36,
1168 child: TextField(
1169 decoration: InputDecoration(
1170 hintText: 'Search... "deals" "invoices" "contact name"',
1171 hintStyle: const TextStyle(fontSize: 12, color: Colors.white24),
1172 prefixIcon: const Icon(
1173 Icons.search,
1174 size: 16,
1175 color: Colors.amber,
1176 ),
1177 suffixIcon: const Icon(
1178 Icons.mic_outlined,
1179 size: 16,
1180 color: Colors.white24,
1181 ),
1182 isDense: true,
1183 contentPadding: const EdgeInsets.symmetric(vertical: 8),
1184 border: OutlineInputBorder(
1185 borderRadius: BorderRadius.circular(20),
1186 borderSide: BorderSide(color: Colors.white12),
1187 ),
1188 enabledBorder: OutlineInputBorder(
1189 borderRadius: BorderRadius.circular(20),
1190 borderSide: BorderSide(color: Colors.white12),
1191 ),
1192 ),
1193 style: const TextStyle(fontSize: 13),
1194 onSubmitted: (query) {
1195 if (query.trim().isNotEmpty) {
1196 onNavigate(
1197 'Search: $query',
1198 SearchResultsView(query: query, onNavigate: onNavigate),
1199 Icons.search,
1200 );
1201 }
1202 },
1203 ),
1204 ),
1205 const SizedBox(width: 8),
1206 // Notification bell — mirrors the web app-shell bell over the
1207 // notifications collection.
1208 const _NotificationBell(),
1209 const SizedBox(width: 8),
1210 // Admin toggle
1211 _AdminToggle(active: adminMode, onTap: onAdminToggle),
1212 ],
1213 ),
1214 );
1215 }
1216}
1217
1218/// App-bar notification bell reading the caller's `notifications` collection
1219/// (per-user rows with is_read). Polls on a timer today; when the server
1220/// ships websocket push it subscribes to the same stream instead.
1221class _NotificationBell extends StatefulWidget {
1222 const _NotificationBell();
1223
1224 @override
1225 State<_NotificationBell> createState() => _NotificationBellState();
1226}
1227
1228class _NotificationBellState extends State<_NotificationBell> {
1229 List<Map<String, dynamic>> _notifications = [];
1230 Timer? _poll;
1231 VoidCallback? _rtDispose;
1232 bool _loading = false;
1233
1234 @override
1235 void initState() {
1236 super.initState();
1237 _load();
1238 // Live push when the websocket is up; a slow poll covers reconnect gaps.
1239 _rtDispose = ScrollRealtime().bind('notifications', _load);
1240 _poll = Timer.periodic(const Duration(seconds: 120), (_) => _load());
1241 }
1242
1243 @override
1244 void dispose() {
1245 _poll?.cancel();
1246 _rtDispose?.call();
1247 super.dispose();
1248 }
1249
1250 Future<void> _load() async {
1251 if (_loading || !ScrollAPI().isConnected) return;
1252 _loading = true;
1253 final result = await ScrollAPI().listUserCollectionRecords(
1254 'notifications',
1255 limit: 50,
1256 );
1257 _loading = false;
1258 if (!mounted) return;
1259 final body = result['body'];
1260 final rows = body is Map && body['records'] is List
1261 ? body['records'] as List
1262 : const [];
1263 final parsed = [
1264 for (final row in rows)
1265 if (row is Map)
1266 Map<String, dynamic>.from(
1267 row.map((k, v) => MapEntry(k.toString(), v)),
1268 ),
1269 ]..sort((a, b) => '${b['created_at']}'.compareTo('${a['created_at']}'));
1270 setState(() => _notifications = parsed);
1271 }
1272
1273 int get _unread =>
1274 _notifications.where((n) => !schemaBoolIsTrue(n['is_read'])).length;
1275
1276 String _text(Map<String, dynamic> n) {
1277 for (final key in const ['message', 'title', 'body', 'text', 'summary']) {
1278 final value = n[key];
1279 if (value != null && value.toString().trim().isNotEmpty) {
1280 return value.toString();
1281 }
1282 }
1283 return n['id']?.toString() ?? 'notification';
1284 }
1285
1286 Future<void> _markRead(Map<String, dynamic> n) async {
1287 final id = n['id']?.toString();
1288 if (id == null || id.isEmpty || schemaBoolIsTrue(n['is_read'])) return;
1289 setState(() => n['is_read'] = 'true');
1290 await ScrollAPI().putUserCollectionRecord('notifications', id, {
1291 'is_read': 'true',
1292 });
1293 }
1294
1295 Future<void> _markAllRead() async {
1296 final unread = _notifications
1297 .where((n) => !schemaBoolIsTrue(n['is_read']))
1298 .toList();
1299 setState(() {
1300 for (final n in unread) {
1301 n['is_read'] = 'true';
1302 }
1303 });
1304 for (final n in unread) {
1305 final id = n['id']?.toString();
1306 if (id != null && id.isNotEmpty) {
1307 await ScrollAPI().putUserCollectionRecord('notifications', id, {
1308 'is_read': 'true',
1309 });
1310 }
1311 }
1312 }
1313
1314 @override
1315 Widget build(BuildContext context) {
1316 final unread = _unread;
1317 return PopupMenuButton<void>(
1318 tooltip: 'Notifications',
1319 offset: const Offset(0, 44),
1320 constraints: const BoxConstraints(minWidth: 320, maxWidth: 380),
1321 onOpened: _load,
1322 icon: Stack(
1323 clipBehavior: Clip.none,
1324 children: [
1325 Icon(
1326 unread > 0
1327 ? Icons.notifications
1328 : Icons.notifications_none_outlined,
1329 size: 20,
1330 color: unread > 0 ? Colors.amber : Colors.white54,
1331 ),
1332 if (unread > 0)
1333 Positioned(
1334 right: -4,
1335 top: -4,
1336 child: Container(
1337 padding: const EdgeInsets.all(2),
1338 constraints: const BoxConstraints(minWidth: 14, minHeight: 14),
1339 decoration: BoxDecoration(
1340 color: Colors.red,
1341 borderRadius: BorderRadius.circular(7),
1342 ),
1343 child: Text(
1344 unread > 9 ? '9+' : '$unread',
1345 textAlign: TextAlign.center,
1346 style: const TextStyle(
1347 fontSize: 9,
1348 color: Colors.white,
1349 fontWeight: FontWeight.bold,
1350 ),
1351 ),
1352 ),
1353 ),
1354 ],
1355 ),
1356 itemBuilder: (context) {
1357 if (_notifications.isEmpty) {
1358 return [
1359 const PopupMenuItem<void>(
1360 enabled: false,
1361 child: Text(
1362 'No notifications',
1363 style: TextStyle(fontSize: 12, color: Colors.white38),
1364 ),
1365 ),
1366 ];
1367 }
1368 return [
1369 PopupMenuItem<void>(
1370 enabled: false,
1371 height: 32,
1372 child: Row(
1373 children: [
1374 Text(
1375 'Notifications',
1376 style: TextStyle(
1377 fontSize: 11,
1378 fontWeight: FontWeight.bold,
1379 color: Colors.white54,
1380 letterSpacing: 1,
1381 ),
1382 ),
1383 const Spacer(),
1384 if (unread > 0)
1385 InkWell(
1386 onTap: () {
1387 Navigator.of(context).pop();
1388 _markAllRead();
1389 },
1390 child: Text(
1391 'Mark all read',
1392 style: TextStyle(
1393 fontSize: 11,
1394 color: Theme.of(context).colorScheme.primary,
1395 ),
1396 ),
1397 ),
1398 ],
1399 ),
1400 ),
1401 for (final n in _notifications.take(15))
1402 PopupMenuItem<void>(
1403 onTap: () => _markRead(n),
1404 child: Row(
1405 crossAxisAlignment: CrossAxisAlignment.start,
1406 children: [
1407 Container(
1408 width: 7,
1409 height: 7,
1410 margin: const EdgeInsets.only(top: 5, right: 8),
1411 decoration: BoxDecoration(
1412 color: schemaBoolIsTrue(n['is_read'])
1413 ? Colors.transparent
1414 : Colors.amber,
1415 shape: BoxShape.circle,
1416 ),
1417 ),
1418 Expanded(
1419 child: Text(
1420 _text(n),
1421 style: TextStyle(
1422 fontSize: 12,
1423 color: schemaBoolIsTrue(n['is_read'])
1424 ? Colors.white54
1425 : Colors.white,
1426 ),
1427 ),
1428 ),
1429 ],
1430 ),
1431 ),
1432 ];
1433 },
1434 );
1435 }
1436}
1437
1438class _AdminToggle extends StatelessWidget {
1439 final bool active;
1440 final VoidCallback onTap;
1441 const _AdminToggle({required this.active, required this.onTap});
1442
1443 @override
1444 Widget build(BuildContext context) {
1445 return Tooltip(
1446 message: active ? 'Hide Admin Tools' : 'Show Admin Tools',
1447 child: InkWell(
1448 borderRadius: BorderRadius.circular(6),
1449 onTap: onTap,
1450 child: Container(
1451 padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
1452 decoration: BoxDecoration(
1453 color: active ? Colors.amber.withOpacity(0.15) : Colors.transparent,
1454 borderRadius: BorderRadius.circular(6),
1455 border: Border.all(
1456 color: active ? Colors.amber.withOpacity(0.4) : Colors.white12,
1457 ),
1458 ),
1459 child: Row(
1460 mainAxisSize: MainAxisSize.min,
1461 children: [
1462 Icon(
1463 Icons.admin_panel_settings,
1464 size: 16,
1465 color: active ? Colors.amber : Colors.white38,
1466 ),
1467 const SizedBox(width: 4),
1468 Text(
1469 'Admin',
1470 style: TextStyle(
1471 fontSize: 12,
1472 color: active ? Colors.amber : Colors.white38,
1473 ),
1474 ),
1475 ],
1476 ),
1477 ),
1478 ),
1479 );
1480 }
1481}
1482
1483// (Admin nav rail is now built into MainShell)
1484
1485// ---------------------------------------------------------------------------
1486// Status Bar
1487// ---------------------------------------------------------------------------
1488
1489class _StatusBar extends StatelessWidget {
1490 final bool adminMode;
1491 const _StatusBar({required this.adminMode});
1492
1493 @override
1494 Widget build(BuildContext context) {
1495 return Container(
1496 height: 24,
1497 padding: const EdgeInsets.symmetric(horizontal: 12),
1498 decoration: BoxDecoration(
1499 color: Theme.of(context).colorScheme.surfaceContainerHighest,
1500 border: Border(top: BorderSide(color: Colors.white10)),
1501 ),
1502 child: Builder(
1503 builder: (context) {
1504 final d = ScrollData();
1505 final api = ScrollAPI();
1506 final authDead = api.authRejected.value;
1507 return Row(
1508 children: [
1509 Container(
1510 width: 8,
1511 height: 8,
1512 decoration: BoxDecoration(
1513 color: authDead ? Colors.amber : Colors.green,
1514 shape: BoxShape.circle,
1515 ),
1516 ),
1517 const SizedBox(width: 6),
1518 Text(
1519 authDead ? 'Session expired — sign in again' : 'Connected',
1520 style: TextStyle(
1521 fontSize: 11,
1522 color: authDead ? Colors.amber : Colors.white54,
1523 ),
1524 ),
1525 const SizedBox(width: 12),
1526 Text(
1527 api.objectServerUrl ?? '',
1528 style: TextStyle(fontSize: 11, color: Colors.white38),
1529 ),
1530 if (api.hasPlatform) ...[
1531 const SizedBox(width: 8),
1532 Text(
1533 '+ platform',
1534 style: TextStyle(fontSize: 11, color: Colors.white24),
1535 ),
1536 ],
1537 const SizedBox(width: 12),
1538 Text(
1539 d.stationSummary,
1540 style: TextStyle(fontSize: 11, color: Colors.green),
1541 ),
1542 const Spacer(),
1543 if (adminMode)
1544 const Text(
1545 'Admin Mode',
1546 style: TextStyle(
1547 fontSize: 11,
1548 color: Colors.amber,
1549 fontWeight: FontWeight.w500,
1550 ),
1551 ),
1552 if (adminMode) const SizedBox(width: 12),
1553 if (d.hasAdminStatus) ...[
1554 Text(
1555 '${d.inventoryCount('objects') ?? d.objectCount} objects',
1556 style: TextStyle(fontSize: 11, color: Colors.white24),
1557 ),
1558 const SizedBox(width: 12),
1559 Text(
1560 d.packageSummary,
1561 style: TextStyle(fontSize: 11, color: Colors.white24),
1562 ),
1563 ] else ...[
1564 Text(
1565 '${d.requestSummary} requests',
1566 style: TextStyle(fontSize: 11, color: Colors.white24),
1567 ),
1568 const SizedBox(width: 12),
1569 Text(
1570 '${d.errors} errors',
1571 style: TextStyle(fontSize: 11, color: Colors.white24),
1572 ),
1573 ],
1574 const SizedBox(width: 12),
1575 ValueListenableBuilder<bool>(
1576 valueListenable: ScrollRealtime().connected,
1577 builder: (context, live, _) => Row(
1578 children: [
1579 Icon(
1580 live ? Icons.bolt : Icons.bolt_outlined,
1581 size: 12,
1582 color: live ? Colors.green : Colors.white24,
1583 ),
1584 const SizedBox(width: 2),
1585 Text(
1586 live ? 'Live' : 'Polling',
1587 style: TextStyle(
1588 fontSize: 11,
1589 color: live ? Colors.green : Colors.white24,
1590 ),
1591 ),
1592 ],
1593 ),
1594 ),
1595 const SizedBox(width: 12),
1596 Text(
1597 d.version.isNotEmpty ? d.version : 'v0.1.0',
1598 style: TextStyle(fontSize: 11, color: Colors.white24),
1599 ),
1600 ],
1601 );
1602 },
1603 ),
1604 );
1605 }
1606}
1607
1608// ---------------------------------------------------------------------------
1609// Switchboard — HOME
1610// ---------------------------------------------------------------------------
1611
1612class SwitchboardView extends StatelessWidget {
1613 final void Function(String, Widget, [IconData])? onNavigate;
1614 const SwitchboardView({super.key, this.onNavigate});
1615
1616 @override
1617 Widget build(BuildContext context) {
1618 final d = ScrollData();
1619 final hour = DateTime.now().hour;
1620 final greeting = hour < 12
1621 ? 'Good morning'
1622 : (hour < 17 ? 'Good afternoon' : 'Good evening');
1623
1624 return SingleChildScrollView(
1625 padding: const EdgeInsets.all(32),
1626 child: Column(
1627 crossAxisAlignment: CrossAxisAlignment.start,
1628 children: [
1629 Text(greeting, style: Theme.of(context).textTheme.headlineSmall),
1630 const SizedBox(height: 4),
1631 Text(
1632 'What would you like to do?',
1633 style: Theme.of(
1634 context,
1635 ).textTheme.bodyLarge?.copyWith(color: Colors.white54),
1636 ),
1637 const SizedBox(height: 24),
1638 _OperatorStatusPanel(data: d, onNavigate: onNavigate),
1639 const SizedBox(height: 32),
1640
1641 // Quick actions
1642 _sectionLabel('QUICK ACTIONS'),
1643 const SizedBox(height: 12),
1644 Wrap(
1645 spacing: 12,
1646 runSpacing: 12,
1647 children: [
1648 _ActionCard(
1649 icon: Icons.person_add,
1650 label: 'New Contact',
1651 color: Colors.blue,
1652 onTap: () {
1653 onNavigate?.call(
1654 'New Contact',
1655 FormView(
1656 title: 'New Contact',
1657 collection: 'contacts',
1658 fields: const [
1659 'First Name',
1660 'Last Name',
1661 'Email',
1662 'Phone',
1663 'Organization',
1664 'Job Title',
1665 'Notes',
1666 ],
1667 onNavigate: onNavigate,
1668 ),
1669 Icons.person_add,
1670 );
1671 },
1672 ),
1673 _ActionCard(
1674 icon: Icons.add_task,
1675 label: 'New Task',
1676 color: Colors.green,
1677 onTap: () {
1678 onNavigate?.call(
1679 'New Task',
1680 FormView(
1681 title: 'New Task',
1682 collection: 'tasks',
1683 fields: const [
1684 'Title',
1685 'Description',
1686 'Project',
1687 'Urgency',
1688 'Due Date',
1689 'Assigned To',
1690 ],
1691 onNavigate: onNavigate,
1692 ),
1693 Icons.add_task,
1694 );
1695 },
1696 ),
1697 _ActionCard(
1698 icon: Icons.shopping_cart,
1699 label: 'New Order',
1700 color: Colors.orange,
1701 onTap: () {
1702 onNavigate?.call(
1703 'New Order',
1704 FormView(
1705 title: 'New Order',
1706 collection: 'orders',
1707 fields: const [
1708 'Customer',
1709 'Product',
1710 'Quantity',
1711 'Unit Price',
1712 'Shipping Address',
1713 'Notes',
1714 ],
1715 onNavigate: onNavigate,
1716 ),
1717 Icons.shopping_cart,
1718 );
1719 },
1720 ),
1721 _ActionCard(
1722 icon: Icons.receipt_long,
1723 label: 'New Invoice',
1724 color: Colors.purple,
1725 onTap: () {
1726 onNavigate?.call(
1727 'New Invoice',
1728 const InvoiceFormView(),
1729 Icons.receipt_long,
1730 );
1731 },
1732 ),
1733 _ActionCard(
1734 icon: Icons.upload_file,
1735 label: 'Import Data',
1736 color: Colors.teal,
1737 onTap: () {},
1738 ),
1739 _ActionCard(
1740 icon: Icons.auto_awesome,
1741 label: 'Ask AI',
1742 color: Colors.amber,
1743 onTap: () {
1744 onNavigate?.call(
1745 'AI Create',
1746 const AICreateView(),
1747 Icons.auto_awesome,
1748 );
1749 },
1750 ),
1751 ],
1752 ),
1753
1754 const SizedBox(height: 36),
1755
1756 // Views
1757 _sectionLabel('VIEWS'),
1758 const SizedBox(height: 12),
1759 _ViewTile(
1760 icon: Icons.people,
1761 title: 'Contacts',
1762 sub: '${d.contactCount} contacts',
1763 count: '${d.contactCount}',
1764 onTap: () {
1765 onNavigate?.call(
1766 'Contacts',
1767 LiveListView(
1768 title: 'Contacts',
1769 collection: 'contacts',
1770 columns: const [
1771 'Name',
1772 'Email',
1773 'Organization',
1774 'Phone',
1775 'Status',
1776 ],
1777 fields: const [
1778 'full_name',
1779 'email',
1780 'organization',
1781 'phone_numbers.0.number',
1782 'lead_status',
1783 ],
1784 onNavigate: onNavigate,
1785 ),
1786 Icons.people,
1787 );
1788 },
1789 ),
1790 _ViewTile(
1791 icon: Icons.check_circle_outline,
1792 title: 'My Tasks',
1793 sub: '${d.taskCount} tasks',
1794 count: '${d.taskCount}',
1795 onTap: () {
1796 onNavigate?.call(
1797 'My Tasks',
1798 LiveListView(
1799 title: 'My Tasks',
1800 collection: 'tasks',
1801 columns: const ['Title', 'Status', 'Urgency', 'Created'],
1802 fields: const ['title', 'status', 'urgency', 'created_at'],
1803 onNavigate: onNavigate,
1804 ),
1805 Icons.check_circle_outline,
1806 );
1807 },
1808 ),
1809 _ViewTile(
1810 icon: Icons.shopping_cart,
1811 title: 'Recent Orders',
1812 sub: '341 total, 18 this week',
1813 count: '341',
1814 onTap: () {
1815 onNavigate?.call(
1816 'Recent Orders',
1817 ListView2(
1818 title: 'Orders',
1819 columns: const [
1820 'Order #',
1821 'Customer',
1822 'Items',
1823 'Total',
1824 'Status',
1825 ],
1826 rows: List.generate(
1827 8,
1828 (i) => [
1829 'ORD-${2041 + i}',
1830 [
1831 'Acme Corp',
1832 'TechStart',
1833 'DataFlow',
1834 'CloudNine',
1835 'NetWorks',
1836 'ByteSize',
1837 'MidTech',
1838 'CoreData',
1839 ][i],
1840 '${(i % 4) + 1} items',
1841 '\$${((i + 1) * 299).toStringAsFixed(2)}',
1842 i < 2 ? 'shipped' : (i < 5 ? 'processing' : 'pending'),
1843 ],
1844 ),
1845 onNavigate: onNavigate,
1846 ),
1847 Icons.shopping_cart,
1848 );
1849 },
1850 ),
1851 _ViewTile(
1852 icon: Icons.receipt_long,
1853 title: 'Invoices',
1854 sub: '5 unpaid, 2 overdue',
1855 count: '5',
1856 alert: true,
1857 onTap: () {
1858 onNavigate?.call(
1859 'Invoices',
1860 ListView2(
1861 title: 'Invoices',
1862 columns: const [
1863 'Invoice #',
1864 'Customer',
1865 'Amount',
1866 'Due',
1867 'Status',
1868 ],
1869 rows: [
1870 [
1871 'INV-1043',
1872 'Acme Corp',
1873 '\$2,118.45',
1874 '2026-05-08',
1875 'draft',
1876 ],
1877 [
1878 'INV-1042',
1879 'TechStart',
1880 '\$890.00',
1881 '2026-04-15',
1882 'overdue',
1883 ],
1884 [
1885 'INV-1041',
1886 'DataFlow',
1887 '\$3,450.00',
1888 '2026-04-10',
1889 'overdue',
1890 ],
1891 [
1892 'INV-1040',
1893 'CloudNine',
1894 '\$1,200.00',
1895 '2026-04-20',
1896 'sent',
1897 ],
1898 ['INV-1039', 'NetWorks', '\$675.00', '2026-04-25', 'sent'],
1899 ],
1900 onNavigate: onNavigate,
1901 ),
1902 Icons.receipt_long,
1903 );
1904 },
1905 ),
1906 _ViewTile(
1907 icon: Icons.inventory_2,
1908 title: 'Products',
1909 sub: '89 active products',
1910 count: '89',
1911 onTap: () {
1912 onNavigate?.call(
1913 'Products',
1914 ListView2(
1915 title: 'Products',
1916 columns: const ['Name', 'SKU', 'Price', 'Stock', 'Category'],
1917 rows: List.generate(
1918 8,
1919 (i) => [
1920 [
1921 'Web Hosting',
1922 'SSL Certificate',
1923 'Support Hours',
1924 'Domain Name',
1925 'Email Plan',
1926 'CDN Service',
1927 'Backup Plan',
1928 'API Access',
1929 ][i],
1930 'SKU-${1001 + i}',
1931 '\$${[299, 79, 150, 15, 49, 89, 39, 199][i]}.00',
1932 '${[999, 245, 500, 999, 350, 180, 420, 275][i]}',
1933 [
1934 'hosting',
1935 'security',
1936 'support',
1937 'domains',
1938 'email',
1939 'performance',
1940 'backup',
1941 'api',
1942 ][i],
1943 ],
1944 ),
1945 onNavigate: onNavigate,
1946 ),
1947 Icons.inventory_2,
1948 );
1949 },
1950 ),
1951 _ViewTile(
1952 icon: Icons.folder,
1953 title: 'Projects',
1954 sub: '${d.projectCount} projects',
1955 count: '${d.projectCount}',
1956 onTap: () {
1957 onNavigate?.call(
1958 'Projects',
1959 LiveListView(
1960 title: 'Projects',
1961 collection: 'projects',
1962 columns: const ['Name', 'Status', 'Created'],
1963 fields: const ['name', 'status', 'created_at'],
1964 onNavigate: onNavigate,
1965 ),
1966 Icons.folder,
1967 );
1968 },
1969 ),
1970
1971 const SizedBox(height: 36),
1972
1973 // Reports
1974 _sectionLabel('REPORTS'),
1975 const SizedBox(height: 12),
1976 Wrap(
1977 spacing: 12,
1978 runSpacing: 12,
1979 children: [
1980 _ReportCard(
1981 icon: Icons.trending_up,
1982 title: 'Monthly Sales',
1983 sub: 'By region, subtotaled',
1984 onTap: () {
1985 onNavigate?.call(
1986 'Monthly Sales Report',
1987 const ReportView(),
1988 Icons.assessment,
1989 );
1990 },
1991 ),
1992 _ReportCard(
1993 icon: Icons.people_outline,
1994 title: 'Customer List',
1995 sub: 'With contact info',
1996 onTap: () {},
1997 ),
1998 _ReportCard(
1999 icon: Icons.warning_amber,
2000 title: 'Overdue Invoices',
2001 sub: 'Grouped by customer',
2002 onTap: () {},
2003 ),
2004 _ReportCard(
2005 icon: Icons.inventory,
2006 title: 'Inventory Report',
2007 sub: 'Stock levels & reorder',
2008 onTap: () {},
2009 ),
2010 _ReportCard(
2011 icon: Icons.label_outline,
2012 title: 'Shipping Labels',
2013 sub: 'Avery 5160 format',
2014 onTap: () {},
2015 ),
2016 ],
2017 ),
2018 ],
2019 ),
2020 );
2021 }
2022
2023 Widget _sectionLabel(String text) {
2024 return Text(
2025 text,
2026 style: TextStyle(
2027 fontSize: 11,
2028 fontWeight: FontWeight.bold,
2029 color: Colors.white38,
2030 letterSpacing: 1,
2031 ),
2032 );
2033 }
2034}
2035
2036class _OperatorStatusPanel extends StatelessWidget {
2037 final ScrollData data;
2038 final void Function(String, Widget, [IconData])? onNavigate;
2039
2040 const _OperatorStatusPanel({required this.data, required this.onNavigate});
2041
2042 @override
2043 Widget build(BuildContext context) {
2044 final status = data.adminHealthStatus;
2045 final healthy = status == 'ok';
2046 final inventory = data.inventoryEntries.take(6).toList();
2047 final packages = data.adminPackages.take(4).toList();
2048 final capabilities = data.capabilityEntries.take(5).toList();
2049
2050 return Container(
2051 width: double.infinity,
2052 padding: const EdgeInsets.all(16),
2053 decoration: BoxDecoration(
2054 color: Theme.of(context).colorScheme.surfaceContainerLow,
2055 borderRadius: BorderRadius.circular(8),
2056 border: Border.all(color: Colors.white10),
2057 ),
2058 child: Column(
2059 crossAxisAlignment: CrossAxisAlignment.start,
2060 children: [
2061 Row(
2062 children: [
2063 Icon(
2064 Icons.monitor_heart_outlined,
2065 size: 20,
2066 color: healthy ? Colors.green : Colors.orange,
2067 ),
2068 const SizedBox(width: 8),
2069 Text(
2070 'Operator Status',
2071 style: Theme.of(context).textTheme.titleMedium,
2072 ),
2073 const SizedBox(width: 10),
2074 _statusChip(
2075 data.hasAdminStatus ? status.toUpperCase() : 'PUBLIC HEALTH',
2076 healthy ? Colors.green : Colors.orange,
2077 ),
2078 const Spacer(),
2079 OutlinedButton.icon(
2080 onPressed: () {
2081 onNavigate?.call(
2082 'API',
2083 const APIExplorerView(),
2084 Icons.api_outlined,
2085 );
2086 },
2087 icon: const Icon(Icons.api_outlined, size: 16),
2088 label: const Text('API'),
2089 ),
2090 ],
2091 ),
2092 const SizedBox(height: 14),
2093 Wrap(
2094 spacing: 12,
2095 runSpacing: 12,
2096 children: [
2097 _metric(
2098 Icons.inventory_2_outlined,
2099 'Objects',
2100 _countText(data.inventoryCount('objects') ?? data.objectCount),
2101 Colors.blue,
2102 ),
2103 _metric(
2104 Icons.storage_outlined,
2105 'Collections',
2106 _countText(data.inventoryCount('collections')),
2107 Colors.teal,
2108 ),
2109 _metric(
2110 Icons.schema_outlined,
2111 'Schemas',
2112 _countText(data.inventoryCount('schemas')),
2113 Colors.purple,
2114 ),
2115 _metric(
2116 Icons.extension_outlined,
2117 'Packages',
2118 _countText(data.inventoryCount('packages')),
2119 Colors.amber,
2120 ),
2121 _metric(
2122 Icons.check_circle_outline,
2123 'Package State',
2124 data.packageSummary,
2125 Colors.green,
2126 wide: true,
2127 ),
2128 ],
2129 ),
2130 if (inventory.isNotEmpty ||
2131 packages.isNotEmpty ||
2132 capabilities.isNotEmpty) ...[
2133 const SizedBox(height: 14),
2134 LayoutBuilder(
2135 builder: (context, constraints) {
2136 final narrow = constraints.maxWidth < 900;
2137 final columns = [
2138 _summaryColumn(
2139 context,
2140 'Inventory',
2141 inventory.map((entry) {
2142 return _labelValue(entry.key, entry.value.toString());
2143 }).toList(),
2144 ),
2145 _summaryColumn(
2146 context,
2147 'Packages',
2148 packages.map(_packageLine).toList(),
2149 ),
2150 _summaryColumn(
2151 context,
2152 'Capabilities',
2153 capabilities.map(_capabilityLine).toList(),
2154 ),
2155 ];
2156 if (narrow) {
2157 return Column(
2158 children: [
2159 for (final column in columns) ...[
2160 column,
2161 if (column != columns.last) const SizedBox(height: 10),
2162 ],
2163 ],
2164 );
2165 }
2166 return Row(
2167 crossAxisAlignment: CrossAxisAlignment.start,
2168 children: [
2169 for (final column in columns) ...[
2170 Expanded(child: column),
2171 if (column != columns.last) const SizedBox(width: 12),
2172 ],
2173 ],
2174 );
2175 },
2176 ),
2177 ],
2178 if (!data.hasAdminStatus) ...[
2179 const SizedBox(height: 12),
2180 Text(
2181 'Admin status is unavailable; showing the public health summary.',
2182 style: TextStyle(fontSize: 12, color: Colors.white38),
2183 ),
2184 ],
2185 ],
2186 ),
2187 );
2188 }
2189
2190 Widget _metric(
2191 IconData icon,
2192 String label,
2193 String value,
2194 Color color, {
2195 bool wide = false,
2196 }) {
2197 return Container(
2198 width: wide ? 220 : 140,
2199 padding: const EdgeInsets.all(12),
2200 decoration: BoxDecoration(
2201 color: color.withValues(alpha: 0.08),
2202 borderRadius: BorderRadius.circular(8),
2203 border: Border.all(color: color.withValues(alpha: 0.2)),
2204 ),
2205 child: Row(
2206 children: [
2207 Icon(icon, size: 18, color: color),
2208 const SizedBox(width: 8),
2209 Expanded(
2210 child: Column(
2211 crossAxisAlignment: CrossAxisAlignment.start,
2212 children: [
2213 Text(
2214 label,
2215 overflow: TextOverflow.ellipsis,
2216 style: TextStyle(fontSize: 11, color: Colors.white38),
2217 ),
2218 Text(
2219 value,
2220 overflow: TextOverflow.ellipsis,
2221 style: TextStyle(
2222 fontSize: 14,
2223 color: Colors.white70,
2224 fontWeight: FontWeight.w600,
2225 ),
2226 ),
2227 ],
2228 ),
2229 ),
2230 ],
2231 ),
2232 );
2233 }
2234
2235 Widget _summaryColumn(
2236 BuildContext context,
2237 String title,
2238 List<Widget> children,
2239 ) {
2240 return Container(
2241 padding: const EdgeInsets.all(12),
2242 decoration: BoxDecoration(
2243 color: Theme.of(context).colorScheme.surface.withValues(alpha: 0.45),
2244 borderRadius: BorderRadius.circular(8),
2245 border: Border.all(color: Colors.white10),
2246 ),
2247 child: Column(
2248 crossAxisAlignment: CrossAxisAlignment.start,
2249 children: [
2250 Text(
2251 title,
2252 style: TextStyle(
2253 fontSize: 11,
2254 fontWeight: FontWeight.bold,
2255 color: Colors.white54,
2256 ),
2257 ),
2258 const SizedBox(height: 8),
2259 if (children.isEmpty)
2260 Text(
2261 'Not reported',
2262 style: TextStyle(fontSize: 12, color: Colors.white30),
2263 )
2264 else
2265 ...children,
2266 ],
2267 ),
2268 );
2269 }
2270
2271 Widget _packageLine(Map<String, dynamic> package) {
2272 final name =
2273 package['name']?.toString() ??
2274 package['id']?.toString() ??
2275 package['package']?.toString() ??
2276 'package';
2277 final status =
2278 package['status']?.toString() ??
2279 package['state']?.toString() ??
2280 package['value']?.toString() ??
2281 (package['installed'] == true ? 'installed' : 'available');
2282 return _labelValue(name, status);
2283 }
2284
2285 Widget _capabilityLine(MapEntry<String, dynamic> entry) {
2286 final value = entry.value;
2287 String status;
2288 String detail = '';
2289 if (value is Map) {
2290 final enabled = value['enabled'];
2291 if (enabled is bool) {
2292 status = enabled ? 'on' : 'off';
2293 } else {
2294 status = _valueLabel(enabled ?? value['status'] ?? value['value']);
2295 }
2296 final env = value['env']?.toString();
2297 if (env != null && env.isNotEmpty) detail = env;
2298 } else {
2299 status = _valueLabel(value);
2300 }
2301 return _labelValue(
2302 entry.key,
2303 detail.isEmpty ? status : '$status · $detail',
2304 );
2305 }
2306
2307 Widget _labelValue(String label, String value) {
2308 return Padding(
2309 padding: const EdgeInsets.only(bottom: 5),
2310 child: Row(
2311 crossAxisAlignment: CrossAxisAlignment.start,
2312 children: [
2313 Expanded(
2314 flex: 5,
2315 child: Text(
2316 _titleCase(label),
2317 overflow: TextOverflow.ellipsis,
2318 style: TextStyle(fontSize: 12, color: Colors.white54),
2319 ),
2320 ),
2321 const SizedBox(width: 8),
2322 Expanded(
2323 flex: 6,
2324 child: Text(
2325 value,
2326 maxLines: 2,
2327 overflow: TextOverflow.ellipsis,
2328 textAlign: TextAlign.right,
2329 style: TextStyle(
2330 fontSize: 12,
2331 color: _valueColor(value),
2332 fontWeight: FontWeight.w600,
2333 ),
2334 ),
2335 ),
2336 ],
2337 ),
2338 );
2339 }
2340
2341 Widget _statusChip(String text, Color color) {
2342 return Container(
2343 padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
2344 decoration: BoxDecoration(
2345 color: color.withValues(alpha: 0.1),
2346 borderRadius: BorderRadius.circular(4),
2347 border: Border.all(color: color.withValues(alpha: 0.18)),
2348 ),
2349 child: Text(
2350 text,
2351 style: TextStyle(
2352 fontSize: 10,
2353 color: color,
2354 fontWeight: FontWeight.bold,
2355 ),
2356 ),
2357 );
2358 }
2359
2360 String _countText(int? value) => value == null ? '?' : value.toString();
2361
2362 String _valueLabel(dynamic value) {
2363 if (value is bool) return value ? 'on' : 'off';
2364 if (value == null) return '?';
2365 return value.toString();
2366 }
2367
2368 String _titleCase(String value) {
2369 return value
2370 .replaceAll('_', ' ')
2371 .replaceAll('-', ' ')
2372 .split(' ')
2373 .where((part) => part.isNotEmpty)
2374 .map((part) => '${part[0].toUpperCase()}${part.substring(1)}')
2375 .join(' ');
2376 }
2377
2378 Color _valueColor(String value) {
2379 final normalized = value.toLowerCase();
2380 if (normalized == 'installed' ||
2381 normalized == 'on' ||
2382 normalized == 'true' ||
2383 normalized == 'ok') {
2384 return Colors.green;
2385 }
2386 if (normalized == 'off' ||
2387 normalized == 'false' ||
2388 normalized == 'disabled') {
2389 return Colors.orange;
2390 }
2391 return Colors.white70;
2392 }
2393}
2394
2395class _ActionCard extends StatelessWidget {
2396 final IconData icon;
2397 final String label;
2398 final Color color;
2399 final VoidCallback onTap;
2400 const _ActionCard({
2401 required this.icon,
2402 required this.label,
2403 required this.color,
2404 required this.onTap,
2405 });
2406
2407 @override
2408 Widget build(BuildContext context) {
2409 return InkWell(
2410 onTap: onTap,
2411 borderRadius: BorderRadius.circular(12),
2412 child: Container(
2413 width: 140,
2414 height: 90,
2415 decoration: BoxDecoration(
2416 color: color.withOpacity(0.08),
2417 borderRadius: BorderRadius.circular(12),
2418 border: Border.all(color: color.withOpacity(0.2)),
2419 ),
2420 child: Column(
2421 mainAxisAlignment: MainAxisAlignment.center,
2422 children: [
2423 Icon(icon, color: color, size: 28),
2424 const SizedBox(height: 8),
2425 Text(label, style: TextStyle(fontSize: 13, color: color)),
2426 ],
2427 ),
2428 ),
2429 );
2430 }
2431}
2432
2433class _ViewTile extends StatelessWidget {
2434 final IconData icon;
2435 final String title;
2436 final String sub;
2437 final String count;
2438 final bool alert;
2439 final VoidCallback onTap;
2440 const _ViewTile({
2441 required this.icon,
2442 required this.title,
2443 required this.sub,
2444 required this.count,
2445 this.alert = false,
2446 required this.onTap,
2447 });
2448
2449 @override
2450 Widget build(BuildContext context) {
2451 return Padding(
2452 padding: const EdgeInsets.only(bottom: 2),
2453 child: ListTile(
2454 shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
2455 leading: Icon(icon, color: alert ? Colors.red[300] : Colors.white54),
2456 title: Text(title, style: const TextStyle(fontSize: 14)),
2457 subtitle: Text(
2458 sub,
2459 style: TextStyle(fontSize: 12, color: Colors.white38),
2460 ),
2461 trailing: Container(
2462 padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
2463 decoration: BoxDecoration(
2464 color: alert
2465 ? Colors.red.withOpacity(0.15)
2466 : Colors.white.withOpacity(0.05),
2467 borderRadius: BorderRadius.circular(12),
2468 ),
2469 child: Text(
2470 count,
2471 style: TextStyle(
2472 fontSize: 13,
2473 fontWeight: FontWeight.bold,
2474 color: alert ? Colors.red[300] : Colors.white54,
2475 ),
2476 ),
2477 ),
2478 onTap: onTap,
2479 ),
2480 );
2481 }
2482}
2483
2484class _ReportCard extends StatelessWidget {
2485 final IconData icon;
2486 final String title;
2487 final String sub;
2488 final VoidCallback onTap;
2489 const _ReportCard({
2490 required this.icon,
2491 required this.title,
2492 required this.sub,
2493 required this.onTap,
2494 });
2495
2496 @override
2497 Widget build(BuildContext context) {
2498 return InkWell(
2499 onTap: onTap,
2500 borderRadius: BorderRadius.circular(12),
2501 child: Container(
2502 width: 200,
2503 padding: const EdgeInsets.all(16),
2504 decoration: BoxDecoration(
2505 color: Theme.of(context).colorScheme.surfaceContainerLow,
2506 borderRadius: BorderRadius.circular(12),
2507 border: Border.all(color: Colors.white10),
2508 ),
2509 child: Row(
2510 children: [
2511 Icon(icon, size: 24, color: Colors.white38),
2512 const SizedBox(width: 12),
2513 Expanded(
2514 child: Column(
2515 crossAxisAlignment: CrossAxisAlignment.start,
2516 children: [
2517 Text(
2518 title,
2519 style: const TextStyle(
2520 fontSize: 13,
2521 fontWeight: FontWeight.w500,
2522 ),
2523 ),
2524 Text(
2525 sub,
2526 style: TextStyle(fontSize: 11, color: Colors.white38),
2527 ),
2528 ],
2529 ),
2530 ),
2531 ],
2532 ),
2533 ),
2534 );
2535 }
2536}
2537
2538// ---------------------------------------------------------------------------
2539// Form View — single record editing (the dBASE EDIT mode)
2540// ---------------------------------------------------------------------------
2541
2542class FormView extends StatefulWidget {
2543 final String title;
2544 final List<String> fields;
2545 final String? collection; // API collection name for saving
2546 final void Function(String, Widget, [IconData])? onNavigate;
2547 const FormView({
2548 super.key,
2549 required this.title,
2550 required this.fields,
2551 this.collection,
2552 this.onNavigate,
2553 });
2554
2555 @override
2556 State<FormView> createState() => _FormViewState();
2557}
2558
2559class _FormViewState extends State<FormView> {
2560 final Map<String, TextEditingController> _controllers = {};
2561 bool _saving = false;
2562 String? _saveResult;
2563
2564 @override
2565 void initState() {
2566 super.initState();
2567 for (final field in widget.fields) {
2568 _controllers[field] = TextEditingController();
2569 }
2570 }
2571
2572 @override
2573 void dispose() {
2574 for (final c in _controllers.values) {
2575 c.dispose();
2576 }
2577 super.dispose();
2578 }
2579
2580 /// Map display field name -> API field name
2581 String _apiFieldName(String displayName) {
2582 return displayName.toLowerCase().replaceAll(' ', '_');
2583 }
2584
2585 Future<void> _save() async {
2586 if (widget.collection == null) {
2587 setState(() => _saveResult = 'No collection configured');
2588 return;
2589 }
2590 setState(() {
2591 _saving = true;
2592 _saveResult = null;
2593 });
2594 final data = <String, dynamic>{};
2595 for (final entry in _controllers.entries) {
2596 final val = entry.value.text.trim();
2597 if (val.isEmpty) continue;
2598
2599 final field = entry.key;
2600 final apiField = _apiFieldName(field);
2601
2602 // Special handling for phone fields on contacts
2603 // Valid phone_type values: mobile, home, work, fax (not "primary")
2604 if (widget.collection == 'contacts' && field == 'Phone') {
2605 // Normalize unicode dashes to ASCII hyphen
2606 final cleaned = val.replaceAll(RegExp(r'[\u2010-\u2015\u2212]'), '-');
2607 data['phone_numbers'] = [
2608 {'phone_type': 'mobile', 'number': cleaned},
2609 ];
2610 } else {
2611 data[apiField] = val;
2612 }
2613 }
2614 final result = await ScrollAPI().create(widget.collection!, data);
2615 if (mounted) {
2616 setState(() {
2617 _saving = false;
2618 if (result != null) {
2619 _saveResult = 'Saved!';
2620 } else {
2621 final err = ScrollAPI().lastError ?? 'Unknown error';
2622 _saveResult = err.length > 80
2623 ? 'Failed: ${err.substring(0, 80)}...'
2624 : 'Failed: $err';
2625 }
2626 });
2627 }
2628 }
2629
2630 @override
2631 Widget build(BuildContext context) {
2632 final title = widget.title;
2633 final fields = widget.fields;
2634 return SingleChildScrollView(
2635 padding: const EdgeInsets.all(32),
2636 child: Center(
2637 child: Container(
2638 constraints: const BoxConstraints(maxWidth: 600),
2639 child: Column(
2640 crossAxisAlignment: CrossAxisAlignment.start,
2641 children: [
2642 // Form header
2643 Row(
2644 children: [
2645 Expanded(
2646 child: Column(
2647 crossAxisAlignment: CrossAxisAlignment.start,
2648 children: [
2649 Text(
2650 title,
2651 style: Theme.of(context).textTheme.titleLarge,
2652 ),
2653 const SizedBox(height: 4),
2654 Text(
2655 'Fill in the details below',
2656 style: TextStyle(fontSize: 13, color: Colors.white38),
2657 ),
2658 ],
2659 ),
2660 ),
2661 // Record navigation
2662 Row(
2663 children: [
2664 IconButton(
2665 onPressed: () {},
2666 icon: const Icon(Icons.chevron_left, size: 20),
2667 tooltip: 'Previous Record',
2668 visualDensity: VisualDensity.compact,
2669 ),
2670 const Text(
2671 'New',
2672 style: TextStyle(fontSize: 12, color: Colors.white38),
2673 ),
2674 IconButton(
2675 onPressed: () {},
2676 icon: const Icon(Icons.chevron_right, size: 20),
2677 tooltip: 'Next Record',
2678 visualDensity: VisualDensity.compact,
2679 ),
2680 ],
2681 ),
2682 ],
2683 ),
2684 const SizedBox(height: 24),
2685
2686 // Form fields
2687 ...fields.map(
2688 (field) => Padding(
2689 padding: const EdgeInsets.only(bottom: 16),
2690 child: _buildField(context, field),
2691 ),
2692 ),
2693
2694 const SizedBox(height: 8),
2695
2696 // Ownership info
2697 Container(
2698 padding: const EdgeInsets.all(12),
2699 decoration: BoxDecoration(
2700 color: Colors.white.withOpacity(0.03),
2701 borderRadius: BorderRadius.circular(8),
2702 border: Border.all(color: Colors.white10),
2703 ),
2704 child: Row(
2705 children: [
2706 Icon(Icons.person_outline, size: 16, color: Colors.white38),
2707 const SizedBox(width: 8),
2708 Text(
2709 'Owner: you',
2710 style: TextStyle(fontSize: 12, color: Colors.white38),
2711 ),
2712 const Spacer(),
2713 Text(
2714 'Access: REGISTERED',
2715 style: TextStyle(fontSize: 12, color: Colors.blue),
2716 ),
2717 ],
2718 ),
2719 ),
2720
2721 const SizedBox(height: 24),
2722
2723 // Actions
2724 Row(
2725 children: [
2726 FilledButton.icon(
2727 onPressed: _saving ? null : _save,
2728 icon: _saving
2729 ? const SizedBox(
2730 width: 16,
2731 height: 16,
2732 child: CircularProgressIndicator(
2733 strokeWidth: 2,
2734 color: Colors.white,
2735 ),
2736 )
2737 : const Icon(Icons.save, size: 18),
2738 label: Text(_saving ? 'Saving...' : 'Save'),
2739 ),
2740 if (_saveResult != null) ...[
2741 const SizedBox(width: 12),
2742 Text(
2743 _saveResult!,
2744 style: TextStyle(
2745 color: _saveResult == 'Saved!'
2746 ? Colors.green
2747 : Colors.red[300],
2748 fontSize: 13,
2749 ),
2750 ),
2751 ],
2752 const Spacer(),
2753 TextButton.icon(
2754 onPressed: _saving ? null : _aiFill,
2755 icon: const Icon(
2756 Icons.auto_awesome,
2757 size: 16,
2758 color: Colors.amber,
2759 ),
2760 label: const Text(
2761 'AI Fill',
2762 style: TextStyle(color: Colors.amber),
2763 ),
2764 ),
2765 ],
2766 ),
2767 ],
2768 ),
2769 ),
2770 ),
2771 );
2772 }
2773
2774 Future<void> _aiFill() async {
2775 final key = await ScrollAPI().getOpenAIKey();
2776 if (key == null || key.isEmpty) {
2777 if (!mounted) return;
2778 ScaffoldMessenger.of(context).showSnackBar(
2779 const SnackBar(
2780 content: Text('Add your OpenAI API key in Settings first'),
2781 ),
2782 );
2783 return;
2784 }
2785
2786 final controller = TextEditingController();
2787 final text = await showDialog<String>(
2788 context: context,
2789 builder: (ctx) => AlertDialog(
2790 title: const Text('AI Fill'),
2791 content: SizedBox(
2792 width: 500,
2793 child: Column(
2794 mainAxisSize: MainAxisSize.min,
2795 children: [
2796 const Text(
2797 'Paste email, scanned text, business card, or any text and AI will extract the fields.',
2798 style: TextStyle(fontSize: 13),
2799 ),
2800 const SizedBox(height: 12),
2801 TextField(
2802 controller: controller,
2803 maxLines: 8,
2804 autofocus: true,
2805 decoration: const InputDecoration(
2806 hintText: 'Paste text here...',
2807 border: OutlineInputBorder(),
2808 ),
2809 ),
2810 ],
2811 ),
2812 ),
2813 actions: [
2814 TextButton(
2815 onPressed: () => Navigator.pop(ctx),
2816 child: const Text('Cancel'),
2817 ),
2818 FilledButton(
2819 onPressed: () => Navigator.pop(ctx, controller.text),
2820 child: const Text('Extract'),
2821 ),
2822 ],
2823 ),
2824 );
2825
2826 if (text == null || text.trim().isEmpty) return;
2827
2828 if (mounted)
2829 setState(() {
2830 _saving = true;
2831 _saveResult = 'Extracting...';
2832 });
2833
2834 final fieldsList = widget.fields.join(', ');
2835 final result = await ScrollAPI().aiExtract(
2836 prompt:
2837 'Extract these fields from the input text into a JSON object. '
2838 'Field names should match exactly (lowercase with underscores): '
2839 '${widget.fields.map(_apiFieldName).join(', ')}. '
2840 'Original field labels: $fieldsList. '
2841 'Return JSON with these keys, using empty string for missing fields.',
2842 userText: text,
2843 );
2844
2845 if (!mounted) return;
2846 if (result == null) {
2847 setState(() {
2848 _saving = false;
2849 _saveResult = 'AI extraction failed';
2850 });
2851 return;
2852 }
2853
2854 // Fill controllers with extracted values
2855 for (final field in widget.fields) {
2856 final apiKey = _apiFieldName(field);
2857 final val = result[apiKey];
2858 if (val != null && val.toString().isNotEmpty) {
2859 _controllers[field]?.text = val.toString();
2860 }
2861 }
2862 setState(() {
2863 _saving = false;
2864 _saveResult = 'AI filled ${result.length} fields';
2865 });
2866 }
2867
2868 Widget _buildField(BuildContext context, String label) {
2869 final controller = _controllers[label];
2870 if (label == 'Notes' || label == 'Description') {
2871 return TextField(
2872 controller: controller,
2873 maxLines: 3,
2874 decoration: InputDecoration(
2875 labelText: label,
2876 border: const OutlineInputBorder(),
2877 alignLabelWithHint: true,
2878 ),
2879 );
2880 }
2881 if (label == 'Urgency') {
2882 return DropdownButtonFormField<String>(
2883 decoration: InputDecoration(
2884 labelText: label,
2885 border: const OutlineInputBorder(),
2886 ),
2887 items: [
2888 'low',
2889 'normal',
2890 'high',
2891 'critical',
2892 ].map((v) => DropdownMenuItem(value: v, child: Text(v))).toList(),
2893 onChanged: (v) {
2894 if (v != null) controller?.text = v;
2895 },
2896 );
2897 }
2898 if (label.contains('Date')) {
2899 return TextField(
2900 controller: controller,
2901 decoration: InputDecoration(
2902 labelText: label,
2903 border: const OutlineInputBorder(),
2904 suffixIcon: const Icon(Icons.calendar_today, size: 18),
2905 ),
2906 );
2907 }
2908 return TextField(
2909 controller: controller,
2910 decoration: InputDecoration(
2911 labelText: label,
2912 border: const OutlineInputBorder(),
2913 ),
2914 );
2915 }
2916}
2917
2918// ---------------------------------------------------------------------------
2919// List View — data grid accessed from switchboard
2920// ---------------------------------------------------------------------------
2921
2922class ListView2 extends StatefulWidget {
2923 final String title;
2924 final List<String> columns;
2925 final List<List<String>> rows;
2926 final void Function(String, Widget, [IconData])? onNavigate;
2927 const ListView2({
2928 super.key,
2929 required this.title,
2930 required this.columns,
2931 required this.rows,
2932 this.onNavigate,
2933 });
2934
2935 @override
2936 State<ListView2> createState() => _ListView2State();
2937}
2938
2939class _ListView2State extends State<ListView2> {
2940 int? _selectedRow;
2941
2942 @override
2943 Widget build(BuildContext context) {
2944 return Column(
2945 children: [
2946 // Toolbar
2947 Container(
2948 height: 44,
2949 padding: const EdgeInsets.symmetric(horizontal: 16),
2950 decoration: BoxDecoration(
2951 border: Border(bottom: BorderSide(color: Colors.white10)),
2952 ),
2953 child: Row(
2954 children: [
2955 Text(
2956 '${widget.rows.length} records',
2957 style: TextStyle(fontSize: 13, color: Colors.white38),
2958 ),
2959 const Spacer(),
2960 SizedBox(
2961 width: 200,
2962 height: 32,
2963 child: TextField(
2964 decoration: InputDecoration(
2965 hintText: 'Search ${widget.title.toLowerCase()}...',
2966 hintStyle: const TextStyle(fontSize: 12),
2967 prefixIcon: const Icon(Icons.search, size: 16),
2968 isDense: true,
2969 contentPadding: const EdgeInsets.symmetric(vertical: 6),
2970 border: OutlineInputBorder(
2971 borderRadius: BorderRadius.circular(8),
2972 ),
2973 ),
2974 style: const TextStyle(fontSize: 12),
2975 ),
2976 ),
2977 const SizedBox(width: 8),
2978 IconButton(
2979 onPressed: () {},
2980 icon: const Icon(Icons.filter_list, size: 18),
2981 tooltip: 'Filter',
2982 visualDensity: VisualDensity.compact,
2983 ),
2984 IconButton(
2985 onPressed: () {},
2986 icon: const Icon(Icons.sort, size: 18),
2987 tooltip: 'Sort',
2988 visualDensity: VisualDensity.compact,
2989 ),
2990 const SizedBox(width: 8),
2991 SegmentedButton<String>(
2992 segments: const [
2993 ButtonSegment(
2994 value: 'grid',
2995 icon: Icon(Icons.view_list, size: 16),
2996 ),
2997 ButtonSegment(
2998 value: 'form',
2999 icon: Icon(Icons.dynamic_form, size: 16),
3000 ),
3001 ],
3002 selected: const {'grid'},
3003 onSelectionChanged: (_) {},
3004 style: ButtonStyle(
3005 visualDensity: VisualDensity.compact,
3006 tapTargetSize: MaterialTapTargetSize.shrinkWrap,
3007 ),
3008 ),
3009 const SizedBox(width: 8),
3010 FilledButton.icon(
3011 onPressed: () {},
3012 icon: const Icon(Icons.add, size: 16),
3013 label: const Text('New', style: TextStyle(fontSize: 12)),
3014 style: FilledButton.styleFrom(
3015 padding: const EdgeInsets.symmetric(horizontal: 12),
3016 visualDensity: VisualDensity.compact,
3017 ),
3018 ),
3019 ],
3020 ),
3021 ),
3022 // Grid
3023 Expanded(
3024 child: SingleChildScrollView(
3025 child: SingleChildScrollView(
3026 scrollDirection: Axis.horizontal,
3027 child: DataTable(
3028 headingRowHeight: 36,
3029 dataRowMinHeight: 36,
3030 dataRowMaxHeight: 36,
3031 columnSpacing: 32,
3032 headingTextStyle: TextStyle(
3033 fontSize: 12,
3034 fontWeight: FontWeight.bold,
3035 color: Colors.white54,
3036 ),
3037 dataTextStyle: const TextStyle(fontSize: 13),
3038 columns: widget.columns
3039 .map((c) => DataColumn(label: Text(c)))
3040 .toList(),
3041 rows: widget.rows.asMap().entries.map((entry) {
3042 final i = entry.key;
3043 final row = entry.value;
3044 return DataRow(
3045 selected: _selectedRow == i,
3046 onSelectChanged: (_) {
3047 if (_selectedRow == i && widget.onNavigate != null) {
3048 // Double-click / re-click opens detail
3049 final record = Map.fromIterables(widget.columns, row);
3050 widget.onNavigate!(
3051 '${row[0]}',
3052 RecordDetailView(
3053 title: row.length > 1 ? row[0] : 'Record',
3054 collection: widget.title,
3055 fields: record,
3056 onNavigate: widget.onNavigate,
3057 ),
3058 Icons.article,
3059 );
3060 }
3061 setState(() => _selectedRow = i);
3062 },
3063 cells: row.map((cell) {
3064 if ([
3065 'hot',
3066 'warm',
3067 'cold',
3068 'customer',
3069 'high',
3070 'critical',
3071 'low',
3072 'normal',
3073 'open',
3074 'in_progress',
3075 'active',
3076 'draft',
3077 ].contains(cell)) {
3078 return DataCell(_chip(cell));
3079 }
3080 if (cell == 'today') {
3081 return DataCell(
3082 Text(
3083 cell,
3084 style: TextStyle(
3085 color: Colors.red[300],
3086 fontWeight: FontWeight.bold,
3087 fontSize: 13,
3088 ),
3089 ),
3090 );
3091 }
3092 return DataCell(Text(cell));
3093 }).toList(),
3094 );
3095 }).toList(),
3096 ),
3097 ),
3098 ),
3099 ),
3100 // Pagination
3101 Container(
3102 height: 36,
3103 padding: const EdgeInsets.symmetric(horizontal: 16),
3104 decoration: BoxDecoration(
3105 border: Border(top: BorderSide(color: Colors.white10)),
3106 ),
3107 child: Row(
3108 children: [
3109 Text(
3110 'Page 1 of 1',
3111 style: TextStyle(fontSize: 12, color: Colors.white38),
3112 ),
3113 const Spacer(),
3114 Text(
3115 'Showing 1-${widget.rows.length} of ${widget.rows.length}',
3116 style: TextStyle(fontSize: 12, color: Colors.white38),
3117 ),
3118 ],
3119 ),
3120 ),
3121 ],
3122 );
3123 }
3124
3125 Widget _chip(String value) {
3126 final color = switch (value) {
3127 'hot' || 'critical' || 'overdue' => Colors.red,
3128 'warm' || 'high' || 'in_progress' => Colors.orange,
3129 'customer' || 'active' => Colors.green,
3130 'cold' || 'low' || 'draft' => Colors.grey,
3131 'open' || 'normal' => Colors.blue,
3132 _ => Colors.white54,
3133 };
3134 return Container(
3135 padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
3136 decoration: BoxDecoration(
3137 color: color.withOpacity(0.12),
3138 borderRadius: BorderRadius.circular(4),
3139 ),
3140 child: Text(value, style: TextStyle(fontSize: 11, color: color)),
3141 );
3142 }
3143}
3144
3145// ---------------------------------------------------------------------------
3146// Report View
3147// ---------------------------------------------------------------------------
3148
3149// ---------------------------------------------------------------------------
3150// Record Detail View — click a row to see full record
3151// ---------------------------------------------------------------------------
3152
3153// ---------------------------------------------------------------------------
3154// LiveListView — loads real data from API
3155// ---------------------------------------------------------------------------
3156
3157class LiveListView extends StatefulWidget {
3158 final String title;
3159 final String collection; // API collection name
3160 final List<String> columns; // display column headers
3161 final List<String> fields; // API field names matching columns
3162 final void Function(String, Widget, [IconData])? onNavigate;
3163
3164 const LiveListView({
3165 super.key,
3166 required this.title,
3167 required this.collection,
3168 required this.columns,
3169 required this.fields,
3170 this.onNavigate,
3171 });
3172
3173 @override
3174 State<LiveListView> createState() => _LiveListViewState();
3175}
3176
3177class _LiveListViewState extends State<LiveListView> {
3178 List<List<String>> _rows = [];
3179 List<Map<String, dynamic>> _rawData = [];
3180 bool _loading = true;
3181 int? _selectedRow;
3182
3183 @override
3184 void initState() {
3185 super.initState();
3186 _loadData();
3187 }
3188
3189 Future<void> _loadData() async {
3190 setState(() => _loading = true);
3191 final api = ScrollAPI();
3192 List<dynamic> results;
3193 switch (widget.collection) {
3194 case 'contacts':
3195 results = await api.listContacts(limit: 100);
3196 break;
3197 case 'tasks':
3198 results = await api.listTasks(limit: 100);
3199 break;
3200 case 'projects':
3201 results = await api.listProjects(limit: 100);
3202 break;
3203 case 'files':
3204 results = await api.listFiles(limit: 100);
3205 break;
3206 case 'articles':
3207 results = await api.listArticles(limit: 100);
3208 break;
3209 default:
3210 results = [];
3211 }
3212 _rawData = results.cast<Map<String, dynamic>>();
3213 _rows = _rawData.map((record) {
3214 return widget.fields.map((field) {
3215 if (field.contains('.')) {
3216 // Nested field like phone_numbers.0.number
3217 final parts = field.split('.');
3218 dynamic val = record;
3219 for (final p in parts) {
3220 if (val is Map)
3221 val = val[p];
3222 else if (val is List)
3223 val = val.isNotEmpty ? val[int.tryParse(p) ?? 0] : null;
3224 else
3225 break;
3226 }
3227 return val?.toString() ?? '';
3228 }
3229 final val = record[field];
3230 if (val is List) return val.isNotEmpty ? val.first.toString() : '';
3231 return val?.toString() ?? '';
3232 }).toList();
3233 }).toList();
3234 if (mounted) setState(() => _loading = false);
3235 }
3236
3237 void _openDetail(int index) {
3238 if (index >= _rawData.length || widget.onNavigate == null) return;
3239 final record = _rawData[index];
3240 final title =
3241 (record['full_name'] ??
3242 record['title'] ??
3243 record['name'] ??
3244 record['id'] ??
3245 'Record')
3246 .toString();
3247 final stringFields = <String, String>{};
3248 record.forEach((k, v) {
3249 if (v == null) return;
3250 if (v is List || v is Map) {
3251 stringFields[k] = const JsonEncoder.withIndent(' ').convert(v);
3252 } else {
3253 stringFields[k] = v.toString();
3254 }
3255 });
3256 widget.onNavigate!(
3257 title,
3258 RecordDetailView(
3259 title: title,
3260 collection: widget.collection,
3261 fields: stringFields,
3262 onNavigate: widget.onNavigate,
3263 ),
3264 Icons.article,
3265 );
3266 }
3267
3268 @override
3269 Widget build(BuildContext context) {
3270 if (_loading) {
3271 return const Center(child: CircularProgressIndicator());
3272 }
3273 if (_rows.isEmpty) {
3274 return Center(
3275 child: Column(
3276 mainAxisSize: MainAxisSize.min,
3277 children: [
3278 Icon(Icons.inbox_outlined, size: 48, color: Colors.white24),
3279 const SizedBox(height: 12),
3280 Text(
3281 'No ${widget.collection} yet',
3282 style: TextStyle(color: Colors.white54),
3283 ),
3284 ],
3285 ),
3286 );
3287 }
3288 return ListView2Plus(
3289 title: widget.title,
3290 columns: widget.columns,
3291 rows: _rows,
3292 onRowTap: _openDetail,
3293 onRefresh: _loadData,
3294 );
3295 }
3296}
3297
3298// ---------------------------------------------------------------------------
3299// ListView2Plus — grid view with row-tap callback (passes index, not just record)
3300// ---------------------------------------------------------------------------
3301
3302class ListView2Plus extends StatefulWidget {
3303 final String title;
3304 final List<String> columns;
3305 final List<List<String>> rows;
3306 final void Function(int) onRowTap;
3307 final VoidCallback? onRefresh;
3308 const ListView2Plus({
3309 super.key,
3310 required this.title,
3311 required this.columns,
3312 required this.rows,
3313 required this.onRowTap,
3314 this.onRefresh,
3315 });
3316
3317 @override
3318 State<ListView2Plus> createState() => _ListView2PlusState();
3319}
3320
3321class _ListView2PlusState extends State<ListView2Plus> {
3322 int? _selectedRow;
3323 String _search = '';
3324
3325 @override
3326 Widget build(BuildContext context) {
3327 final filtered = _search.isEmpty
3328 ? widget.rows
3329 : widget.rows
3330 .where(
3331 (r) => r.any(
3332 (c) => c.toLowerCase().contains(_search.toLowerCase()),
3333 ),
3334 )
3335 .toList();
3336
3337 return Column(
3338 children: [
3339 Container(
3340 height: 44,
3341 padding: const EdgeInsets.symmetric(horizontal: 16),
3342 decoration: BoxDecoration(
3343 border: Border(bottom: BorderSide(color: Colors.white10)),
3344 ),
3345 child: Row(
3346 children: [
3347 Text(
3348 '${filtered.length} records',
3349 style: TextStyle(fontSize: 13, color: Colors.white38),
3350 ),
3351 const SizedBox(width: 8),
3352 if (widget.onRefresh != null)
3353 IconButton(
3354 onPressed: widget.onRefresh,
3355 icon: const Icon(Icons.refresh, size: 18),
3356 tooltip: 'Refresh',
3357 visualDensity: VisualDensity.compact,
3358 ),
3359 const Spacer(),
3360 SizedBox(
3361 width: 240,
3362 height: 32,
3363 child: TextField(
3364 onChanged: (v) => setState(() => _search = v),
3365 decoration: InputDecoration(
3366 hintText: 'Filter ${widget.title.toLowerCase()}...',
3367 hintStyle: const TextStyle(fontSize: 12),
3368 prefixIcon: const Icon(Icons.search, size: 16),
3369 isDense: true,
3370 contentPadding: const EdgeInsets.symmetric(vertical: 6),
3371 border: OutlineInputBorder(
3372 borderRadius: BorderRadius.circular(8),
3373 ),
3374 ),
3375 style: const TextStyle(fontSize: 12),
3376 ),
3377 ),
3378 ],
3379 ),
3380 ),
3381 Expanded(
3382 child: SingleChildScrollView(
3383 child: SingleChildScrollView(
3384 scrollDirection: Axis.horizontal,
3385 child: DataTable(
3386 headingRowHeight: 36,
3387 dataRowMinHeight: 36,
3388 dataRowMaxHeight: 36,
3389 columnSpacing: 32,
3390 headingTextStyle: TextStyle(
3391 fontSize: 12,
3392 fontWeight: FontWeight.bold,
3393 color: Colors.white54,
3394 ),
3395 dataTextStyle: const TextStyle(fontSize: 13),
3396 columns: widget.columns
3397 .map((c) => DataColumn(label: Text(c)))
3398 .toList(),
3399 rows: filtered.asMap().entries.map((entry) {
3400 final i = entry.key;
3401 final row = entry.value;
3402 return DataRow(
3403 selected: _selectedRow == i,
3404 onSelectChanged: (_) {
3405 final realIndex = widget.rows.indexOf(row);
3406 if (_selectedRow == i) {
3407 widget.onRowTap(realIndex);
3408 }
3409 setState(() => _selectedRow = i);
3410 },
3411 cells: row.map((cell) {
3412 if ([
3413 'hot',
3414 'warm',
3415 'cold',
3416 'customer',
3417 'high',
3418 'critical',
3419 'low',
3420 'normal',
3421 'open',
3422 'in_progress',
3423 'active',
3424 'draft',
3425 'completed',
3426 'closed',
3427 ].contains(cell)) {
3428 return DataCell(_chip(cell));
3429 }
3430 return DataCell(
3431 Text(
3432 cell.length > 50
3433 ? '${cell.substring(0, 50)}...'
3434 : cell,
3435 ),
3436 );
3437 }).toList(),
3438 );
3439 }).toList(),
3440 ),
3441 ),
3442 ),
3443 ),
3444 ],
3445 );
3446 }
3447
3448 Widget _chip(String value) {
3449 final color = switch (value) {
3450 'hot' || 'critical' || 'overdue' => Colors.red,
3451 'warm' || 'high' || 'in_progress' => Colors.orange,
3452 'customer' || 'active' || 'completed' => Colors.green,
3453 'cold' || 'low' || 'draft' || 'closed' => Colors.grey,
3454 'open' || 'normal' => Colors.blue,
3455 _ => Colors.white54,
3456 };
3457 return Container(
3458 padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
3459 decoration: BoxDecoration(
3460 color: color.withOpacity(0.12),
3461 borderRadius: BorderRadius.circular(4),
3462 ),
3463 child: Text(value, style: TextStyle(fontSize: 11, color: color)),
3464 );
3465 }
3466}
3467
3468// ---------------------------------------------------------------------------
3469// Record Detail View
3470// ---------------------------------------------------------------------------
3471
3472class RecordDetailView extends StatefulWidget {
3473 final String title;
3474 final String collection;
3475 final Map<String, String> fields;
3476 final void Function(String, Widget, [IconData])? onNavigate;
3477
3478 const RecordDetailView({
3479 super.key,
3480 required this.title,
3481 required this.collection,
3482 required this.fields,
3483 this.onNavigate,
3484 });
3485
3486 @override
3487 State<RecordDetailView> createState() => _RecordDetailViewState();
3488}
3489
3490class _RecordDetailViewState extends State<RecordDetailView> {
3491 final Map<String, TextEditingController> _controllers = {};
3492 final Set<String> _modified = {};
3493 bool _saving = false;
3494 bool _deleting = false;
3495 String? _message;
3496
3497 // Fields that shouldn't be edited
3498 static const _readonlyFields = {
3499 'id',
3500 'created_at',
3501 'updated_at',
3502 'user',
3503 'full_name',
3504 };
3505
3506 @override
3507 void initState() {
3508 super.initState();
3509 for (final entry in widget.fields.entries) {
3510 final controller = TextEditingController(text: entry.value);
3511 controller.addListener(() => _modified.add(entry.key));
3512 _controllers[entry.key] = controller;
3513 }
3514 }
3515
3516 @override
3517 void dispose() {
3518 for (final c in _controllers.values) {
3519 c.dispose();
3520 }
3521 super.dispose();
3522 }
3523
3524 String get _recordId => widget.fields['id'] ?? '';
3525
3526 Future<void> _save() async {
3527 if (_recordId.isEmpty) {
3528 setState(() => _message = 'No record ID to update');
3529 return;
3530 }
3531 setState(() {
3532 _saving = true;
3533 _message = null;
3534 });
3535 final data = <String, dynamic>{};
3536 for (final key in _modified) {
3537 if (_readonlyFields.contains(key)) continue;
3538 final val = _controllers[key]?.text ?? '';
3539
3540 // Special handling for complex fields
3541 if (key == 'phone_numbers' && widget.collection == 'contacts') {
3542 // Handle as list — try to parse as JSON, fall back to single phone string
3543 if (val.trim().isEmpty) {
3544 data[key] = [];
3545 } else if (val.trim().startsWith('[')) {
3546 // Looks like JSON, try to parse
3547 try {
3548 data[key] = jsonDecode(val);
3549 } catch (_) {
3550 // Fall back to single phone
3551 data[key] = [
3552 {'phone_type': 'mobile', 'number': val.trim()},
3553 ];
3554 }
3555 } else {
3556 // Plain phone string — wrap it
3557 data[key] = [
3558 {'phone_type': 'mobile', 'number': val.trim()},
3559 ];
3560 }
3561 } else if (key == 'tags' || key.endsWith('_ids')) {
3562 // List fields — try JSON parse
3563 try {
3564 data[key] = jsonDecode(val);
3565 } catch (_) {
3566 data[key] = [];
3567 }
3568 } else {
3569 data[key] = val;
3570 }
3571 }
3572 if (data.isEmpty) {
3573 setState(() {
3574 _saving = false;
3575 _message = 'No changes to save';
3576 });
3577 return;
3578 }
3579 final result = await ScrollAPI().update(widget.collection, _recordId, data);
3580 if (mounted) {
3581 setState(() {
3582 _saving = false;
3583 _message = result != null ? 'Saved!' : 'Failed to save';
3584 if (result != null) _modified.clear();
3585 });
3586 }
3587 }
3588
3589 Future<void> _delete() async {
3590 if (_recordId.isEmpty) return;
3591 final confirmed = await showDialog<bool>(
3592 context: context,
3593 builder: (ctx) => AlertDialog(
3594 title: const Text('Delete record?'),
3595 content: Text('This cannot be undone. Delete ${widget.title}?'),
3596 actions: [
3597 TextButton(
3598 onPressed: () => Navigator.pop(ctx, false),
3599 child: const Text('Cancel'),
3600 ),
3601 FilledButton(
3602 onPressed: () => Navigator.pop(ctx, true),
3603 style: FilledButton.styleFrom(backgroundColor: Colors.red),
3604 child: const Text('Delete'),
3605 ),
3606 ],
3607 ),
3608 );
3609 if (confirmed != true) return;
3610
3611 setState(() {
3612 _deleting = true;
3613 _message = null;
3614 });
3615 final success = await ScrollAPI().delete(widget.collection, _recordId);
3616 if (mounted) {
3617 if (success) {
3618 Navigator.of(context).pop();
3619 } else {
3620 setState(() {
3621 _deleting = false;
3622 _message = 'Failed to delete';
3623 });
3624 }
3625 }
3626 }
3627
3628 @override
3629 Widget build(BuildContext context) {
3630 final title = widget.title;
3631 final collection = widget.collection;
3632 final fields = widget.fields;
3633 return SingleChildScrollView(
3634 padding: const EdgeInsets.all(32),
3635 child: Center(
3636 child: Container(
3637 constraints: const BoxConstraints(maxWidth: 700),
3638 child: Column(
3639 crossAxisAlignment: CrossAxisAlignment.start,
3640 children: [
3641 // Header
3642 Row(
3643 children: [
3644 Expanded(
3645 child: Column(
3646 crossAxisAlignment: CrossAxisAlignment.start,
3647 children: [
3648 Text(
3649 title,
3650 style: Theme.of(context).textTheme.titleLarge,
3651 ),
3652 Text(
3653 collection,
3654 style: TextStyle(fontSize: 13, color: Colors.white38),
3655 ),
3656 ],
3657 ),
3658 ),
3659 IconButton(
3660 onPressed: () {},
3661 icon: const Icon(Icons.chevron_left, size: 20),
3662 tooltip: 'Previous',
3663 visualDensity: VisualDensity.compact,
3664 ),
3665 IconButton(
3666 onPressed: () {},
3667 icon: const Icon(Icons.chevron_right, size: 20),
3668 tooltip: 'Next',
3669 visualDensity: VisualDensity.compact,
3670 ),
3671 ],
3672 ),
3673 const SizedBox(height: 20),
3674
3675 // Record fields
3676 ...fields.entries.map(
3677 (entry) => Padding(
3678 padding: const EdgeInsets.only(bottom: 12),
3679 child: AdminFieldOverlay(
3680 fieldName: entry.key,
3681 fieldType: _guessType(entry.key, entry.value),
3682 child: _buildFieldDisplay(context, entry.key, entry.value),
3683 ),
3684 ),
3685 ),
3686
3687 const SizedBox(height: 16),
3688
3689 // Related data
3690 Container(
3691 padding: const EdgeInsets.all(16),
3692 decoration: BoxDecoration(
3693 color: Theme.of(context).colorScheme.surfaceContainerLow,
3694 borderRadius: BorderRadius.circular(12),
3695 border: Border.all(color: Colors.white10),
3696 ),
3697 child: Column(
3698 crossAxisAlignment: CrossAxisAlignment.start,
3699 children: [
3700 Text(
3701 'RELATED DATA',
3702 style: TextStyle(
3703 fontSize: 10,
3704 fontWeight: FontWeight.bold,
3705 color: Colors.white38,
3706 letterSpacing: 1,
3707 ),
3708 ),
3709 const SizedBox(height: 12),
3710 if (collection == 'Contacts') ...[
3711 _relatedTile(
3712 Icons.receipt_long,
3713 'Invoices',
3714 '3 invoices (\$4,200 total)',
3715 ),
3716 _relatedTile(
3717 Icons.shopping_cart,
3718 'Orders',
3719 '7 orders this year',
3720 ),
3721 _relatedTile(Icons.note, 'Notes', '2 notes'),
3722 _relatedTile(Icons.attach_file, 'Files', '1 attachment'),
3723 ] else if (collection == 'Orders') ...[
3724 _relatedTile(
3725 Icons.person,
3726 'Customer',
3727 'Acme Corp — Alice Chen',
3728 ),
3729 _relatedTile(Icons.inventory_2, 'Items', '3 line items'),
3730 _relatedTile(
3731 Icons.receipt_long,
3732 'Invoice',
3733 'INV-1043 (draft)',
3734 ),
3735 ] else ...[
3736 _relatedTile(
3737 Icons.link,
3738 'Related Records',
3739 'Click to load related data',
3740 ),
3741 ],
3742 ],
3743 ),
3744 ),
3745 const SizedBox(height: 16),
3746
3747 // Ownership
3748 Container(
3749 padding: const EdgeInsets.all(12),
3750 decoration: BoxDecoration(
3751 color: Colors.white.withOpacity(0.03),
3752 borderRadius: BorderRadius.circular(8),
3753 border: Border.all(color: Colors.white10),
3754 ),
3755 child: Row(
3756 children: [
3757 Icon(Icons.person_outline, size: 16, color: Colors.white38),
3758 const SizedBox(width: 8),
3759 Text(
3760 'Owner: admin',
3761 style: TextStyle(fontSize: 12, color: Colors.white38),
3762 ),
3763 const SizedBox(width: 16),
3764 Text(
3765 'Created: 2026-04-05',
3766 style: TextStyle(fontSize: 12, color: Colors.white24),
3767 ),
3768 const SizedBox(width: 16),
3769 Text(
3770 'Modified: 2026-04-08',
3771 style: TextStyle(fontSize: 12, color: Colors.white24),
3772 ),
3773 const Spacer(),
3774 Text(
3775 'ROLE-BASED',
3776 style: TextStyle(fontSize: 12, color: Colors.orange),
3777 ),
3778 ],
3779 ),
3780 ),
3781 const SizedBox(height: 20),
3782
3783 // Actions
3784 Row(
3785 children: [
3786 FilledButton.icon(
3787 onPressed: (_saving || _deleting) ? null : _save,
3788 icon: _saving
3789 ? const SizedBox(
3790 width: 14,
3791 height: 14,
3792 child: CircularProgressIndicator(
3793 strokeWidth: 2,
3794 color: Colors.white,
3795 ),
3796 )
3797 : const Icon(Icons.save, size: 16),
3798 label: Text(_saving ? 'Saving...' : 'Save'),
3799 ),
3800 if (_message != null) ...[
3801 const SizedBox(width: 12),
3802 Text(
3803 _message!,
3804 style: TextStyle(
3805 color: _message == 'Saved!'
3806 ? Colors.green
3807 : Colors.red[300],
3808 fontSize: 13,
3809 ),
3810 ),
3811 ],
3812 const Spacer(),
3813 TextButton.icon(
3814 onPressed: (_saving || _deleting) ? null : _delete,
3815 icon: _deleting
3816 ? const SizedBox(
3817 width: 14,
3818 height: 14,
3819 child: CircularProgressIndicator(
3820 strokeWidth: 2,
3821 color: Colors.red,
3822 ),
3823 )
3824 : Icon(
3825 Icons.delete_outline,
3826 size: 16,
3827 color: Colors.red[300],
3828 ),
3829 label: Text(
3830 _deleting ? 'Deleting...' : 'Delete',
3831 style: TextStyle(color: Colors.red[300]),
3832 ),
3833 ),
3834 ],
3835 ),
3836 ],
3837 ),
3838 ),
3839 ),
3840 );
3841 }
3842
3843 Widget _buildFieldDisplay(BuildContext context, String label, String value) {
3844 final isStatus = [
3845 'hot',
3846 'warm',
3847 'cold',
3848 'customer',
3849 'active',
3850 'draft',
3851 'open',
3852 'in_progress',
3853 'shipped',
3854 'processing',
3855 'pending',
3856 'sent',
3857 'paid',
3858 'overdue',
3859 'cancelled',
3860 ].contains(value);
3861
3862 if (isStatus) {
3863 final color = switch (value) {
3864 'hot' || 'overdue' || 'cancelled' => Colors.red,
3865 'warm' || 'processing' || 'in_progress' => Colors.orange,
3866 'customer' || 'active' || 'paid' || 'shipped' => Colors.green,
3867 'cold' || 'draft' || 'pending' => Colors.grey,
3868 'open' || 'sent' => Colors.blue,
3869 _ => Colors.white54,
3870 };
3871 return InputDecorator(
3872 decoration: InputDecoration(
3873 labelText: label,
3874 border: const OutlineInputBorder(),
3875 ),
3876 child: Container(
3877 padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
3878 decoration: BoxDecoration(
3879 color: color.withOpacity(0.12),
3880 borderRadius: BorderRadius.circular(4),
3881 ),
3882 child: Text(value, style: TextStyle(fontSize: 13, color: color)),
3883 ),
3884 );
3885 }
3886
3887 final isReadonly = _readonlyFields.contains(label);
3888 final isMulti =
3889 value.length > 80 || label == 'notes' || label == 'description';
3890
3891 return TextField(
3892 controller: _controllers[label],
3893 readOnly: isReadonly,
3894 maxLines: isMulti ? null : 1,
3895 decoration: InputDecoration(
3896 labelText: label,
3897 border: const OutlineInputBorder(),
3898 suffixIcon: isReadonly
3899 ? Icon(Icons.lock, size: 14, color: Colors.white24)
3900 : null,
3901 filled: isReadonly,
3902 fillColor: isReadonly ? Colors.white.withOpacity(0.02) : null,
3903 ),
3904 );
3905 }
3906
3907 String _guessType(String key, String value) {
3908 if (key.contains('email')) return 'email';
3909 if (key.contains('phone')) return 'phone';
3910 if (key.contains('date') ||
3911 key.contains('Date') ||
3912 key.contains('Updated') ||
3913 key.contains('Created'))
3914 return 'date';
3915 if (key.contains('price') ||
3916 key.contains('Total') ||
3917 key.contains('Amount') ||
3918 value.startsWith('\$'))
3919 return 'currency';
3920 if (key.contains('status') || key.contains('Status')) return 'enum';
3921 return 'text';
3922 }
3923
3924 Widget _relatedTile(IconData icon, String label, String detail) {
3925 return Padding(
3926 padding: const EdgeInsets.symmetric(vertical: 4),
3927 child: InkWell(
3928 onTap: () {},
3929 borderRadius: BorderRadius.circular(6),
3930 child: Padding(
3931 padding: const EdgeInsets.symmetric(vertical: 4, horizontal: 4),
3932 child: Row(
3933 children: [
3934 Icon(icon, size: 16, color: Colors.white38),
3935 const SizedBox(width: 10),
3936 Text(
3937 label,
3938 style: TextStyle(fontSize: 13, fontWeight: FontWeight.w500),
3939 ),
3940 const SizedBox(width: 8),
3941 Text(
3942 detail,
3943 style: TextStyle(fontSize: 12, color: Colors.white38),
3944 ),
3945 const Spacer(),
3946 Icon(Icons.chevron_right, size: 16, color: Colors.white24),
3947 ],
3948 ),
3949 ),
3950 ),
3951 );
3952 }
3953}
3954
3955// ---------------------------------------------------------------------------
3956// Report View
3957// ---------------------------------------------------------------------------
3958
3959class ReportView extends StatelessWidget {
3960 const ReportView({super.key});
3961
3962 @override
3963 Widget build(BuildContext context) {
3964 return SingleChildScrollView(
3965 padding: const EdgeInsets.all(32),
3966 child: Center(
3967 child: Container(
3968 constraints: const BoxConstraints(maxWidth: 800),
3969 child: Column(
3970 crossAxisAlignment: CrossAxisAlignment.start,
3971 children: [
3972 // Report header
3973 Row(
3974 children: [
3975 Expanded(
3976 child: Column(
3977 crossAxisAlignment: CrossAxisAlignment.start,
3978 children: [
3979 Text(
3980 'Monthly Sales Report',
3981 style: Theme.of(context).textTheme.titleLarge,
3982 ),
3983 Text(
3984 'April 2026 — Grouped by Region',
3985 style: TextStyle(fontSize: 13, color: Colors.white38),
3986 ),
3987 ],
3988 ),
3989 ),
3990 OutlinedButton.icon(
3991 onPressed: () {},
3992 icon: const Icon(Icons.picture_as_pdf, size: 16),
3993 label: const Text('Export PDF'),
3994 ),
3995 const SizedBox(width: 8),
3996 OutlinedButton.icon(
3997 onPressed: () {},
3998 icon: const Icon(Icons.print, size: 16),
3999 label: const Text('Print'),
4000 ),
4001 ],
4002 ),
4003 const SizedBox(height: 24),
4004
4005 // Report groups
4006 _reportGroup(context, 'West Region', [
4007 ['Acme Corp', '42', '\$12,600'],
4008 ['TechStart', '28', '\$8,400'],
4009 ['CloudNine', '15', '\$4,500'],
4010 ], '\$25,500'),
4011
4012 _reportGroup(context, 'East Region', [
4013 ['DataFlow', '38', '\$11,400'],
4014 ['NetWorks', '22', '\$6,600'],
4015 ['ByteSize', '19', '\$5,700'],
4016 ], '\$23,700'),
4017
4018 _reportGroup(context, 'Central Region', [
4019 ['MidTech', '31', '\$9,300'],
4020 ['CoreData', '17', '\$5,100'],
4021 ], '\$14,400'),
4022
4023 const SizedBox(height: 8),
4024 const Divider(thickness: 2),
4025 Padding(
4026 padding: const EdgeInsets.symmetric(vertical: 8),
4027 child: Row(
4028 children: [
4029 Text(
4030 'GRAND TOTAL',
4031 style: TextStyle(
4032 fontSize: 14,
4033 fontWeight: FontWeight.bold,
4034 color: Colors.white,
4035 ),
4036 ),
4037 const Spacer(),
4038 Text(
4039 '\$63,600',
4040 style: TextStyle(
4041 fontSize: 18,
4042 fontWeight: FontWeight.bold,
4043 color: Colors.green[300],
4044 ),
4045 ),
4046 ],
4047 ),
4048 ),
4049 ],
4050 ),
4051 ),
4052 ),
4053 );
4054 }
4055
4056 Widget _reportGroup(
4057 BuildContext context,
4058 String region,
4059 List<List<String>> rows,
4060 String subtotal,
4061 ) {
4062 return Column(
4063 crossAxisAlignment: CrossAxisAlignment.start,
4064 children: [
4065 Container(
4066 width: double.infinity,
4067 padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
4068 decoration: BoxDecoration(
4069 color: Theme.of(
4070 context,
4071 ).colorScheme.primaryContainer.withOpacity(0.15),
4072 borderRadius: BorderRadius.circular(6),
4073 ),
4074 child: Text(
4075 region,
4076 style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 14),
4077 ),
4078 ),
4079 const SizedBox(height: 4),
4080 ...rows.map(
4081 (row) => Padding(
4082 padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
4083 child: Row(
4084 children: [
4085 Expanded(
4086 flex: 3,
4087 child: Text(row[0], style: const TextStyle(fontSize: 13)),
4088 ),
4089 Expanded(
4090 child: Text(
4091 '${row[1]} units',
4092 style: TextStyle(fontSize: 13, color: Colors.white54),
4093 ),
4094 ),
4095 SizedBox(
4096 width: 100,
4097 child: Text(
4098 row[2],
4099 textAlign: TextAlign.right,
4100 style: const TextStyle(fontSize: 13),
4101 ),
4102 ),
4103 ],
4104 ),
4105 ),
4106 ),
4107 Padding(
4108 padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
4109 child: Row(
4110 children: [
4111 const Spacer(),
4112 Text(
4113 'Subtotal: $subtotal',
4114 style: TextStyle(
4115 fontSize: 13,
4116 fontWeight: FontWeight.bold,
4117 color: Colors.white70,
4118 ),
4119 ),
4120 ],
4121 ),
4122 ),
4123 const Divider(),
4124 const SizedBox(height: 8),
4125 ],
4126 );
4127 }
4128}
4129
4130// ---------------------------------------------------------------------------
4131// Station Monitor (admin)
4132// ---------------------------------------------------------------------------
4133
4134/// Polyline sparklines for the Stations trend tiles. All series in one
4135/// paint share a vertical scale so p50/p95 (or cpu/mem) compare honestly.
4136class _SparklinePainter extends CustomPainter {
4137 _SparklinePainter({required this.series});
4138
4139 final List<(List<double>, Color)> series;
4140
4141 @override
4142 void paint(Canvas canvas, Size size) {
4143 var min = double.infinity;
4144 var max = double.negativeInfinity;
4145 for (final (values, _) in series) {
4146 for (final value in values) {
4147 if (value < min) min = value;
4148 if (value > max) max = value;
4149 }
4150 }
4151 if (!min.isFinite || !max.isFinite) return;
4152 final span = (max - min) == 0 ? 1.0 : (max - min);
4153
4154 for (final (values, color) in series) {
4155 if (values.length < 2) continue;
4156 final paint = Paint()
4157 ..color = color
4158 ..strokeWidth = 1.5
4159 ..style = PaintingStyle.stroke
4160 ..strokeJoin = StrokeJoin.round;
4161 final path = Path();
4162 for (var i = 0; i < values.length; i++) {
4163 final x = i / (values.length - 1) * size.width;
4164 final y = size.height - ((values[i] - min) / span * size.height);
4165 if (i == 0) {
4166 path.moveTo(x, y);
4167 } else {
4168 path.lineTo(x, y);
4169 }
4170 }
4171 canvas.drawPath(path, paint);
4172 }
4173 }
4174
4175 @override
4176 bool shouldRepaint(_SparklinePainter oldDelegate) =>
4177 oldDelegate.series != series;
4178}
4179
4180class StationMonitor extends StatefulWidget {
4181 final void Function(String, Widget, [IconData])? onNavigate;
4182 const StationMonitor({super.key, this.onNavigate});
4183
4184 @override
4185 State<StationMonitor> createState() => _StationMonitorState();
4186}
4187
4188class _StationMonitorState extends State<StationMonitor> {
4189 String? _selectedStation;
4190 bool _refreshing = false;
4191 String? _refreshError;
4192 List<Map<String, dynamic>> _history = [];
4193
4194 @override
4195 void initState() {
4196 super.initState();
4197 _refresh();
4198 }
4199
4200 Future<void> _refresh() async {
4201 if (_refreshing) return;
4202 setState(() {
4203 _refreshing = true;
4204 _refreshError = null;
4205 });
4206 try {
4207 await ScrollData().loadAll();
4208 // Metrics history snapshots (~1/min while traffic flows, survives
4209 // restarts) — feeds the trend sparklines.
4210 final health = await ScrollAPI().getHealth(metrics: true, history: true);
4211 final rows = health?['history'];
4212 _history = [
4213 if (rows is List)
4214 for (final row in rows)
4215 if (row is Map)
4216 Map<String, dynamic>.from(
4217 row.map((k, v) => MapEntry(k.toString(), v)),
4218 ),
4219 ];
4220 } catch (e) {
4221 _refreshError = e.toString();
4222 }
4223 if (mounted) {
4224 setState(() => _refreshing = false);
4225 }
4226 }
4227
4228 List<double> _series(String key) => [
4229 for (final row in _history)
4230 if (row[key] is num) (row[key] as num).toDouble(),
4231 ];
4232
4233 Widget _trendTile(
4234 BuildContext context,
4235 String title, {
4236 required Map<String, (List<double>, Color)> series,
4237 }) {
4238 final present = {
4239 for (final entry in series.entries)
4240 if (entry.value.$1.length >= 2) entry.key: entry.value,
4241 };
4242 return Expanded(
4243 child: Container(
4244 padding: const EdgeInsets.all(12),
4245 decoration: BoxDecoration(
4246 color: Theme.of(context).colorScheme.surfaceContainerLow,
4247 borderRadius: BorderRadius.circular(12),
4248 border: Border.all(color: Colors.white10),
4249 ),
4250 child: Column(
4251 crossAxisAlignment: CrossAxisAlignment.start,
4252 children: [
4253 Row(
4254 children: [
4255 Expanded(
4256 child: Text(
4257 title,
4258 overflow: TextOverflow.ellipsis,
4259 style: const TextStyle(fontSize: 11, color: Colors.white54),
4260 ),
4261 ),
4262 for (final entry in present.entries)
4263 Padding(
4264 padding: const EdgeInsets.only(left: 8),
4265 child: Text(
4266 '${entry.key} '
4267 '${entry.value.$1.last.toStringAsFixed(1)}',
4268 style: TextStyle(
4269 fontSize: 10,
4270 fontFamily: 'monospace',
4271 color: entry.value.$2,
4272 ),
4273 ),
4274 ),
4275 ],
4276 ),
4277 const SizedBox(height: 8),
4278 SizedBox(
4279 height: 40,
4280 width: double.infinity,
4281 child: present.isEmpty
4282 ? const Center(
4283 child: Text('—', style: TextStyle(color: Colors.white24)),
4284 )
4285 : CustomPaint(
4286 painter: _SparklinePainter(
4287 series: [
4288 for (final entry in present.values)
4289 (entry.$1, entry.$2),
4290 ],
4291 ),
4292 ),
4293 ),
4294 ],
4295 ),
4296 ),
4297 );
4298 }
4299
4300 @override
4301 Widget build(BuildContext context) {
4302 if (_selectedStation != null) {
4303 return _buildStationDetail(context);
4304 }
4305 return _buildOverview(context);
4306 }
4307
4308 Widget _buildOverview(BuildContext context) {
4309 final d = ScrollData();
4310 final h = d.health ?? {};
4311 final rt = d.responseTime ?? {};
4312 final status = h['status']?.toString() ?? '?';
4313 final requests = h.containsKey('requests') ? d.requestSummary : '?';
4314 final errorRate = h.containsKey('error_rate') ? '${d.errorRate}%' : '?';
4315 final threads = h['threads']?.toString() ?? '?';
4316 // Scale response times for bar height (max 40px)
4317 final rtAvg = (rt['avg'] as num?)?.toDouble() ?? 0;
4318 final rtP50 = (rt['p50'] as num?)?.toDouble() ?? 0;
4319 final rtP95 = (rt['p95'] as num?)?.toDouble() ?? 0;
4320 final rtP99 = (rt['p99'] as num?)?.toDouble() ?? 0;
4321 final rtMax = [
4322 rtAvg,
4323 rtP50,
4324 rtP95,
4325 rtP99,
4326 1.0,
4327 ].reduce((a, b) => a > b ? a : b);
4328
4329 return SingleChildScrollView(
4330 padding: const EdgeInsets.all(24),
4331 child: Column(
4332 crossAxisAlignment: CrossAxisAlignment.start,
4333 children: [
4334 Row(
4335 children: [
4336 Text(
4337 'Server Health',
4338 style: Theme.of(context).textTheme.titleLarge,
4339 ),
4340 const Spacer(),
4341 IconButton(
4342 onPressed: _refreshing ? null : _refresh,
4343 icon: _refreshing
4344 ? const SizedBox(
4345 width: 16,
4346 height: 16,
4347 child: CircularProgressIndicator(strokeWidth: 2),
4348 )
4349 : const Icon(Icons.refresh, size: 18),
4350 tooltip: 'Refresh health',
4351 visualDensity: VisualDensity.compact,
4352 ),
4353 ],
4354 ),
4355 if (_refreshError != null) ...[
4356 const SizedBox(height: 8),
4357 Text(
4358 'Refresh failed: $_refreshError',
4359 style: TextStyle(fontSize: 12, color: Colors.red[300]),
4360 ),
4361 ],
4362 const SizedBox(height: 16),
4363 Row(
4364 children: [
4365 _statBox(
4366 context,
4367 'Status',
4368 status,
4369 status == 'ok' ? Colors.green : Colors.orange,
4370 ),
4371 const SizedBox(width: 12),
4372 _statBox(
4373 context,
4374 'Uptime',
4375 d.uptime.isEmpty ? '?' : d.uptime,
4376 Colors.green,
4377 ),
4378 const SizedBox(width: 12),
4379 _statBox(context, 'Requests', requests, Colors.blue),
4380 const SizedBox(width: 12),
4381 _statBox(context, 'Threads', threads, Colors.white54),
4382 const SizedBox(width: 12),
4383 _statBox(
4384 context,
4385 'Error Rate',
4386 errorRate,
4387 errorRate == '0.0%' || errorRate == '0%'
4388 ? Colors.green
4389 : Colors.red,
4390 ),
4391 ],
4392 ),
4393 const SizedBox(height: 24),
4394
4395 Text(
4396 'Response Time (ms)',
4397 style: Theme.of(context).textTheme.titleMedium,
4398 ),
4399 const SizedBox(height: 12),
4400 if (rt.isEmpty)
4401 Container(
4402 width: double.infinity,
4403 padding: const EdgeInsets.all(16),
4404 decoration: BoxDecoration(
4405 color: Theme.of(context).colorScheme.surfaceContainerLow,
4406 borderRadius: BorderRadius.circular(12),
4407 border: Border.all(color: Colors.white10),
4408 ),
4409 child: Text(
4410 'Response-time metrics are not exposed by this /health response.',
4411 style: TextStyle(fontSize: 12, color: Colors.white38),
4412 ),
4413 )
4414 else
4415 Container(
4416 height: 112,
4417 padding: const EdgeInsets.all(16),
4418 decoration: BoxDecoration(
4419 color: Theme.of(context).colorScheme.surfaceContainerLow,
4420 borderRadius: BorderRadius.circular(12),
4421 border: Border.all(color: Colors.white10),
4422 ),
4423 child: Row(
4424 mainAxisAlignment: MainAxisAlignment.spaceAround,
4425 crossAxisAlignment: CrossAxisAlignment.end,
4426 children: [
4427 _responseBar(
4428 context,
4429 'avg\n${rtAvg.toStringAsFixed(0)}ms',
4430 (rtAvg / rtMax * 40).clamp(4, 40),
4431 Colors.orange,
4432 ),
4433 _responseBar(
4434 context,
4435 'p50\n${rtP50.toStringAsFixed(0)}ms',
4436 (rtP50 / rtMax * 40).clamp(4, 40),
4437 Colors.red,
4438 ),
4439 _responseBar(
4440 context,
4441 'p95\n${rtP95.toStringAsFixed(0)}ms',
4442 (rtP95 / rtMax * 40).clamp(4, 40),
4443 Colors.red,
4444 ),
4445 _responseBar(
4446 context,
4447 'p99\n${rtP99.toStringAsFixed(0)}ms',
4448 (rtP99 / rtMax * 40).clamp(4, 40),
4449 Colors.red,
4450 ),
4451 ],
4452 ),
4453 ),
4454
4455 if (_history.length >= 2) ...[
4456 const SizedBox(height: 24),
4457 Text(
4458 'Trends (metrics history)',
4459 style: Theme.of(context).textTheme.titleMedium,
4460 ),
4461 const SizedBox(height: 4),
4462 Text(
4463 '${_history.length} snapshots, ~1/min while traffic flows — '
4464 'survives restarts.',
4465 style: TextStyle(fontSize: 12, color: Colors.white38),
4466 ),
4467 const SizedBox(height: 12),
4468 Row(
4469 children: [
4470 _trendTile(
4471 context,
4472 'Response (ms)',
4473 series: {
4474 'p50': (_series('p50_ms'), Colors.orange),
4475 'p95': (_series('p95_ms'), Colors.red),
4476 },
4477 ),
4478 const SizedBox(width: 12),
4479 _trendTile(
4480 context,
4481 'Requests/sec',
4482 series: {'rps': (_series('rps'), Colors.blue)},
4483 ),
4484 const SizedBox(width: 12),
4485 _trendTile(
4486 context,
4487 'CPU / Memory %',
4488 series: {
4489 'cpu': (_series('cpu_percent'), Colors.orange),
4490 'mem': (_series('memory_used_percent'), Colors.purple),
4491 },
4492 ),
4493 ],
4494 ),
4495 ],
4496
4497 const SizedBox(height: 24),
4498 Text(
4499 d.usingHealthFallback ? 'Server Node' : 'Cluster Stations (legacy)',
4500 style: Theme.of(context).textTheme.titleMedium,
4501 ),
4502 const SizedBox(height: 4),
4503 Text(
4504 d.usingHealthFallback
4505 ? 'Cluster routes are not exposed by this object server. Showing the connected server from /health.'
4506 : 'Legacy cluster route data. This surface is optional for the OSS object server.',
4507 style: TextStyle(fontSize: 12, color: Colors.white38),
4508 ),
4509 const SizedBox(height: 12),
4510 Row(
4511 crossAxisAlignment: CrossAxisAlignment.start,
4512 children: d.stations.isEmpty
4513 ? [
4514 Expanded(
4515 child: Text(
4516 'No station data',
4517 style: TextStyle(color: Colors.white24),
4518 ),
4519 ),
4520 ]
4521 : d.stations.map((s) {
4522 final m = s['metrics'] as Map<String, dynamic>? ?? {};
4523 final memTotal =
4524 (m['memory_total_mb'] as num?)?.toDouble() ?? 0;
4525 final diskUsed = (m['disk_used_gb'] as num?)?.toDouble();
4526 final diskTotal = (m['disk_total_gb'] as num?)?.toDouble();
4527 final objectCount = (m['object_count'] as num?)?.toInt();
4528 return Expanded(
4529 child: Padding(
4530 padding: EdgeInsets.only(
4531 right: s != d.stations.last ? 12 : 0,
4532 ),
4533 child: _stationCard(
4534 context,
4535 s['station_id']?.toString() ?? '?',
4536 s['is_active'] == true,
4537 cpu: (m['cpu_percent'] as num?)?.toInt() ?? -1,
4538 mem: (m['memory_percent'] as num?)?.toInt() ?? -1,
4539 disk: (m['disk_percent'] as num?)?.toInt() ?? -1,
4540 cores: (m['cpu_count'] as num?)?.toInt() ?? 0,
4541 ram: memTotal > 0
4542 ? '${(memTotal / 1024).toStringAsFixed(1)}GB'
4543 : '?',
4544 diskInfo: diskTotal != null && diskTotal > 0
4545 ? '${diskUsed?.toStringAsFixed(0) ?? '?'}/${diskTotal.toStringAsFixed(0)}GB'
4546 : '?',
4547 objects: objectCount?.toString() ?? '?',
4548 version: s['version']?.toString() ?? '?',
4549 ),
4550 ),
4551 );
4552 }).toList(),
4553 ),
4554 ],
4555 ),
4556 );
4557 }
4558
4559 Widget _buildStationDetail(BuildContext context) {
4560 final d = ScrollData();
4561 // Find the selected station's data
4562 final stationData = d.stations.firstWhere(
4563 (s) => s['station_id'] == _selectedStation,
4564 orElse: () => <String, dynamic>{},
4565 );
4566 final m = stationData['metrics'] as Map<String, dynamic>? ?? {};
4567 final h = d.health ?? {};
4568 final cpu = (m['cpu_percent'] as num?)?.toInt() ?? -1;
4569 final mem = (m['memory_percent'] as num?)?.toInt() ?? -1;
4570 final disk = (m['disk_percent'] as num?)?.toInt() ?? -1;
4571 final cores = (m['cpu_count'] as num?)?.toInt() ?? 0;
4572 final ramMb = (m['memory_total_mb'] as num?)?.toDouble() ?? 0;
4573 final objCount = (m['object_count'] as num?)?.toInt();
4574 final version = stationData['version']?.toString() ?? '?';
4575 final source = stationData['source']?.toString() ?? 'cluster';
4576 final ramLabel = ramMb > 0 ? '${(ramMb / 1024).toStringAsFixed(1)}GB' : '?';
4577 final coresLabel = cores > 0 ? '$cores' : '?';
4578 final objectLabel = objCount?.toString() ?? '?';
4579
4580 return Column(
4581 children: [
4582 Container(
4583 height: 44,
4584 padding: const EdgeInsets.symmetric(horizontal: 16),
4585 decoration: BoxDecoration(
4586 border: Border(bottom: BorderSide(color: Colors.white10)),
4587 ),
4588 child: Row(
4589 children: [
4590 IconButton(
4591 onPressed: () => setState(() => _selectedStation = null),
4592 icon: const Icon(Icons.arrow_back, size: 18),
4593 visualDensity: VisualDensity.compact,
4594 ),
4595 Container(
4596 width: 10,
4597 height: 10,
4598 decoration: BoxDecoration(
4599 color: stationData['is_active'] == true
4600 ? Colors.green
4601 : Colors.red,
4602 shape: BoxShape.circle,
4603 ),
4604 ),
4605 const SizedBox(width: 8),
4606 Text(
4607 _selectedStation!,
4608 style: const TextStyle(
4609 fontWeight: FontWeight.bold,
4610 fontSize: 15,
4611 ),
4612 ),
4613 const SizedBox(width: 12),
4614 Text(
4615 version,
4616 style: TextStyle(fontSize: 12, color: Colors.white38),
4617 ),
4618 const Spacer(),
4619 Text(
4620 '$coresLabel cores | $ramLabel RAM | $objectLabel objects',
4621 style: TextStyle(fontSize: 12, color: Colors.white38),
4622 ),
4623 ],
4624 ),
4625 ),
4626 Expanded(
4627 child: Row(
4628 children: [
4629 Expanded(
4630 flex: 1,
4631 child: SingleChildScrollView(
4632 padding: const EdgeInsets.all(16),
4633 child: Column(
4634 crossAxisAlignment: CrossAxisAlignment.start,
4635 children: [
4636 Text(
4637 'RESOURCES',
4638 style: TextStyle(
4639 fontSize: 10,
4640 fontWeight: FontWeight.bold,
4641 color: Colors.white38,
4642 letterSpacing: 1,
4643 ),
4644 ),
4645 const SizedBox(height: 12),
4646 _meter('CPU', cpu, cpu > 80 ? Colors.red : Colors.green),
4647 const SizedBox(height: 12),
4648 _meter('MEM', mem, mem > 80 ? Colors.red : Colors.blue),
4649 const SizedBox(height: 12),
4650 _meter(
4651 'DISK',
4652 disk,
4653 disk > 80
4654 ? Colors.red
4655 : (disk > 70 ? Colors.orange : Colors.green),
4656 ),
4657 const SizedBox(height: 24),
4658 Text(
4659 'SERVER',
4660 style: TextStyle(
4661 fontSize: 10,
4662 fontWeight: FontWeight.bold,
4663 color: Colors.white38,
4664 letterSpacing: 1,
4665 ),
4666 ),
4667 const SizedBox(height: 12),
4668 _detailRow('Requests/sec', '${d.rps}'),
4669 _detailRow('Total Requests', '${d.requests}'),
4670 _detailRow('Errors', '${d.errors}'),
4671 _detailRow('Error Rate', '${d.errorRate}%'),
4672 _detailRow(
4673 'Source',
4674 source == 'health' ? '/health' : '/cluster/stations',
4675 ),
4676 const SizedBox(height: 24),
4677 Text(
4678 'PROCESS',
4679 style: TextStyle(
4680 fontSize: 10,
4681 fontWeight: FontWeight.bold,
4682 color: Colors.white38,
4683 letterSpacing: 1,
4684 ),
4685 ),
4686 const SizedBox(height: 12),
4687 _detailRow('PID', '${h['pid'] ?? '?'}'),
4688 _detailRow('Threads', '${h['threads'] ?? '?'}'),
4689 _detailRow('Uptime', d.uptime),
4690 _detailRow('Version', version),
4691 _detailRow(
4692 'Host',
4693 stationData['host']?.toString() ?? '?',
4694 ),
4695 _detailRow('Port', '${stationData['port'] ?? '?'}'),
4696 ],
4697 ),
4698 ),
4699 ),
4700 Container(width: 1, color: Colors.white10),
4701 // Right: health payload
4702 Expanded(
4703 flex: 2,
4704 child: Column(
4705 crossAxisAlignment: CrossAxisAlignment.start,
4706 children: [
4707 Container(
4708 height: 36,
4709 padding: const EdgeInsets.symmetric(horizontal: 16),
4710 decoration: BoxDecoration(
4711 border: Border(
4712 bottom: BorderSide(color: Colors.white10),
4713 ),
4714 ),
4715 child: Row(
4716 children: [
4717 Text(
4718 'HEALTH PAYLOAD',
4719 style: TextStyle(
4720 fontSize: 10,
4721 fontWeight: FontWeight.bold,
4722 color: Colors.white38,
4723 letterSpacing: 1,
4724 ),
4725 ),
4726 const Spacer(),
4727 Text(
4728 source == 'health'
4729 ? 'Cluster API unavailable'
4730 : 'Cluster data',
4731 style: TextStyle(
4732 fontSize: 11,
4733 color: Colors.white24,
4734 ),
4735 ),
4736 const SizedBox(width: 4),
4737 Container(
4738 width: 6,
4739 height: 6,
4740 decoration: BoxDecoration(
4741 color: source == 'health'
4742 ? Colors.orange
4743 : Colors.green,
4744 shape: BoxShape.circle,
4745 ),
4746 ),
4747 ],
4748 ),
4749 ),
4750 Expanded(
4751 child: Container(
4752 color: Colors.black26,
4753 padding: const EdgeInsets.all(12),
4754 child: SelectableText(
4755 const JsonEncoder.withIndent(
4756 ' ',
4757 ).convert({'station': stationData, 'health': h}),
4758 style: TextStyle(
4759 fontFamily: 'monospace',
4760 fontSize: 12,
4761 color: Colors.white70,
4762 ),
4763 ),
4764 ),
4765 ),
4766 ],
4767 ),
4768 ),
4769 ],
4770 ),
4771 ),
4772 ],
4773 );
4774 }
4775
4776 Widget _responseBar(
4777 BuildContext context,
4778 String label,
4779 double pct,
4780 Color color,
4781 ) {
4782 return Expanded(
4783 child: Column(
4784 mainAxisAlignment: MainAxisAlignment.end,
4785 children: [
4786 Container(
4787 width: 28,
4788 height: pct.clamp(4, 40),
4789 decoration: BoxDecoration(
4790 color: color.withOpacity(0.6),
4791 borderRadius: BorderRadius.circular(3),
4792 ),
4793 ),
4794 const SizedBox(height: 4),
4795 Text(label, style: TextStyle(fontSize: 10, color: Colors.white38)),
4796 ],
4797 ),
4798 );
4799 }
4800
4801 Widget _statBox(
4802 BuildContext context,
4803 String label,
4804 String value,
4805 Color color,
4806 ) {
4807 return Expanded(
4808 child: Container(
4809 padding: const EdgeInsets.all(16),
4810 decoration: BoxDecoration(
4811 color: Theme.of(context).colorScheme.surfaceContainerLow,
4812 borderRadius: BorderRadius.circular(12),
4813 border: Border.all(color: Colors.white10),
4814 ),
4815 child: Column(
4816 crossAxisAlignment: CrossAxisAlignment.start,
4817 children: [
4818 Text(label, style: TextStyle(fontSize: 12, color: Colors.white38)),
4819 const SizedBox(height: 4),
4820 Text(
4821 value,
4822 style: TextStyle(
4823 fontSize: 22,
4824 fontWeight: FontWeight.bold,
4825 color: color,
4826 ),
4827 ),
4828 ],
4829 ),
4830 ),
4831 );
4832 }
4833
4834 Widget _stationCard(
4835 BuildContext context,
4836 String name,
4837 bool healthy, {
4838 required int cpu,
4839 required int mem,
4840 required int disk,
4841 required int cores,
4842 required String ram,
4843 required String diskInfo,
4844 required String objects,
4845 required String version,
4846 }) {
4847 return InkWell(
4848 onTap: () => setState(() => _selectedStation = name),
4849 borderRadius: BorderRadius.circular(12),
4850 child: Container(
4851 padding: const EdgeInsets.all(16),
4852 decoration: BoxDecoration(
4853 color: Theme.of(context).colorScheme.surfaceContainerLow,
4854 borderRadius: BorderRadius.circular(12),
4855 border: Border.all(color: Colors.white10),
4856 ),
4857 child: Column(
4858 crossAxisAlignment: CrossAxisAlignment.start,
4859 children: [
4860 Row(
4861 children: [
4862 Container(
4863 width: 10,
4864 height: 10,
4865 decoration: BoxDecoration(
4866 color: healthy ? Colors.green : Colors.red,
4867 shape: BoxShape.circle,
4868 ),
4869 ),
4870 const SizedBox(width: 8),
4871 Text(
4872 name,
4873 style: const TextStyle(
4874 fontWeight: FontWeight.bold,
4875 fontSize: 15,
4876 ),
4877 ),
4878 const Spacer(),
4879 Text(
4880 version,
4881 style: TextStyle(fontSize: 12, color: Colors.white38),
4882 ),
4883 ],
4884 ),
4885 const SizedBox(height: 16),
4886 _meter('CPU', cpu, Colors.green),
4887 const SizedBox(height: 8),
4888 _meter('MEM', mem, Colors.blue),
4889 const SizedBox(height: 8),
4890 _meter('DISK', disk, disk > 70 ? Colors.orange : Colors.green),
4891 const SizedBox(height: 12),
4892 Row(
4893 children: [
4894 Expanded(
4895 child: Text(
4896 '$cores cores | $ram RAM | $diskInfo disk | $objects objects',
4897 style: TextStyle(fontSize: 11, color: Colors.white38),
4898 ),
4899 ),
4900 Icon(Icons.chevron_right, size: 16, color: Colors.white24),
4901 ],
4902 ),
4903 ],
4904 ),
4905 ),
4906 );
4907 }
4908
4909 Widget _meter(String label, int percent, Color color) {
4910 // Negative percent means the server did not report this metric.
4911 final reported = percent >= 0;
4912 return Row(
4913 children: [
4914 SizedBox(
4915 width: 40,
4916 child: Text(
4917 label,
4918 style: TextStyle(fontSize: 12, color: Colors.white54),
4919 ),
4920 ),
4921 Expanded(
4922 child: ClipRRect(
4923 borderRadius: BorderRadius.circular(3),
4924 child: LinearProgressIndicator(
4925 value: reported ? percent / 100 : 0,
4926 backgroundColor: Colors.white10,
4927 color: color,
4928 minHeight: 8,
4929 ),
4930 ),
4931 ),
4932 SizedBox(
4933 width: 45,
4934 child: Text(
4935 reported ? '$percent%' : '—',
4936 textAlign: TextAlign.right,
4937 style: TextStyle(fontSize: 12, color: Colors.white54),
4938 ),
4939 ),
4940 ],
4941 );
4942 }
4943
4944 Widget _detailRow(String label, String value) {
4945 return Padding(
4946 padding: const EdgeInsets.symmetric(vertical: 3),
4947 child: Row(
4948 children: [
4949 SizedBox(
4950 width: 130,
4951 child: Text(
4952 label,
4953 style: TextStyle(fontSize: 12, color: Colors.white38),
4954 ),
4955 ),
4956 Text(value, style: const TextStyle(fontSize: 13)),
4957 ],
4958 ),
4959 );
4960 }
4961}
4962
4963// ---------------------------------------------------------------------------
4964// Daemon Status View (admin — jobs, queue, events)
4965// ---------------------------------------------------------------------------
4966
4967class DaemonStatusView extends StatefulWidget {
4968 const DaemonStatusView({super.key});
4969
4970 @override
4971 State<DaemonStatusView> createState() => _DaemonStatusViewState();
4972}
4973
4974enum _DaemonListKind { scheduler, queue }
4975
4976class _DaemonStatusViewState extends State<DaemonStatusView> {
4977 bool _refreshing = false;
4978 String _taskStatusFilter = 'all';
4979 String _messageStatusFilter = 'all';
4980 String _deliveryModeFilter = 'all';
4981 String _deliveryEventTypeFilter = 'all';
4982
4983 @override
4984 Widget build(BuildContext context) {
4985 final data = ScrollData();
4986 final status = data.daemonStatus;
4987 final healthy = data.daemonHealthStatus == 'ok';
4988 final scheduler = data.daemonSection('scheduler');
4989 final queue = data.daemonSection('queue');
4990 final events = data.daemonSection('events');
4991 final subscriptions = data.daemonSection('subscriptions');
4992 final retention = data.daemonSection('retention');
4993 final rateLimit = data.daemonSection('rate_limit');
4994 final schedulerTasks = data.daemonSchedulerTasks;
4995 final queueMessages = data.daemonQueueMessages;
4996 final eventDeliveries = data.eventDeliveries;
4997 final schedulerTaskCount =
4998 data.daemonSchedulerTaskCount ??
4999 _firstCount(scheduler, const ['task_count', 'tasks', 'total_tasks']);
5000 final queueMessageCount =
5001 data.daemonQueueMessageCount ??
5002 _firstCount(queue, const [
5003 'message_count',
5004 'messages',
5005 'total_messages',
5006 ]);
5007 final eventDeliveryCount =
5008 data.eventDeliveryCount ??
5009 _firstCount(subscriptions, const [
5010 'subscription_count',
5011 'subscriptions',
5012 'total_subscriptions',
5013 'count',
5014 ]);
5015
5016 return SingleChildScrollView(
5017 padding: const EdgeInsets.all(24),
5018 child: Column(
5019 crossAxisAlignment: CrossAxisAlignment.start,
5020 children: [
5021 Row(
5022 children: [
5023 Icon(
5024 Icons.hub_outlined,
5025 color: healthy ? Colors.green : Colors.orange,
5026 size: 22,
5027 ),
5028 const SizedBox(width: 10),
5029 Text(
5030 'Daemon Status',
5031 style: Theme.of(context).textTheme.titleLarge,
5032 ),
5033 const SizedBox(width: 10),
5034 _statusChip(
5035 data.hasDaemonStatus
5036 ? data.daemonHealthStatus.toUpperCase()
5037 : 'AUTH REQUIRED',
5038 healthy ? Colors.green : Colors.orange,
5039 ),
5040 const SizedBox(width: 12),
5041 Text(
5042 'GET /daemon/status',
5043 style: TextStyle(
5044 fontSize: 12,
5045 color: Colors.white38,
5046 fontFamily: 'monospace',
5047 ),
5048 ),
5049 const Spacer(),
5050 IconButton(
5051 onPressed: _refreshing ? null : _refreshDaemonStatus,
5052 icon: _refreshing
5053 ? const SizedBox(
5054 width: 16,
5055 height: 16,
5056 child: CircularProgressIndicator(strokeWidth: 2),
5057 )
5058 : const Icon(Icons.refresh, size: 18),
5059 tooltip: 'Refresh daemon status',
5060 ),
5061 ],
5062 ),
5063 const SizedBox(height: 18),
5064 if (status == null)
5065 _emptyDaemonStatus(context)
5066 else ...[
5067 _lockedControlBar(context),
5068 const SizedBox(height: 16),
5069 Wrap(
5070 spacing: 12,
5071 runSpacing: 12,
5072 children: [
5073 _metric(
5074 Icons.schedule_outlined,
5075 'Tasks',
5076 _countText(schedulerTaskCount),
5077 Colors.blue,
5078 ),
5079 _metric(
5080 Icons.queue_outlined,
5081 'Messages',
5082 _countText(queueMessageCount),
5083 Colors.teal,
5084 ),
5085 _metric(
5086 Icons.event_outlined,
5087 'Events',
5088 _countText(
5089 _firstCount(events, const [
5090 'event_count',
5091 'events',
5092 'total_events',
5093 ]),
5094 ),
5095 Colors.purple,
5096 ),
5097 _metric(
5098 Icons.forward_to_inbox_outlined,
5099 'Deliveries',
5100 _countText(eventDeliveryCount),
5101 Colors.indigo,
5102 ),
5103 _metric(
5104 Icons.subscriptions_outlined,
5105 'Subscriptions',
5106 _countText(
5107 _firstCount(subscriptions, const [
5108 'subscription_count',
5109 'subscriptions',
5110 'total_subscriptions',
5111 'count',
5112 ]),
5113 ),
5114 Colors.amber,
5115 ),
5116 _metric(
5117 Icons.pending_actions_outlined,
5118 'Pending',
5119 _countText(
5120 _firstCount(subscriptions, const [
5121 'pending_delivery_count',
5122 'pending_deliveries',
5123 'pending',
5124 ]),
5125 ),
5126 Colors.orange,
5127 ),
5128 ],
5129 ),
5130 const SizedBox(height: 16),
5131 LayoutBuilder(
5132 builder: (context, constraints) {
5133 final twoColumns = constraints.maxWidth >= 980;
5134 final cards = [
5135 _daemonListCard(
5136 context,
5137 title: 'Scheduler Tasks',
5138 route: 'GET /daemon/scheduler/tasks',
5139 icon: Icons.schedule_outlined,
5140 color: Colors.blue,
5141 rows: schedulerTasks,
5142 response: data.daemonSchedulerTasksResponse,
5143 filter: _taskStatusFilter,
5144 onFilterChanged: (value) {
5145 setState(() => _taskStatusFilter = value);
5146 },
5147 kind: _DaemonListKind.scheduler,
5148 ),
5149 _daemonListCard(
5150 context,
5151 title: 'Queue Messages',
5152 route: 'GET /daemon/queue/messages',
5153 icon: Icons.queue_outlined,
5154 color: Colors.teal,
5155 rows: queueMessages,
5156 response: data.daemonQueueMessagesResponse,
5157 filter: _messageStatusFilter,
5158 onFilterChanged: (value) {
5159 setState(() => _messageStatusFilter = value);
5160 },
5161 kind: _DaemonListKind.queue,
5162 ),
5163 ];
5164 if (!twoColumns) {
5165 return Column(
5166 children: [
5167 for (final card in cards) ...[
5168 card,
5169 if (card != cards.last) const SizedBox(height: 12),
5170 ],
5171 ],
5172 );
5173 }
5174 return Row(
5175 crossAxisAlignment: CrossAxisAlignment.start,
5176 children: [
5177 Expanded(child: cards.first),
5178 const SizedBox(width: 12),
5179 Expanded(child: cards.last),
5180 ],
5181 );
5182 },
5183 ),
5184 const SizedBox(height: 16),
5185 _eventDeliveriesCard(
5186 context,
5187 rows: eventDeliveries,
5188 response: data.eventDeliveriesResponse,
5189 ),
5190 const SizedBox(height: 16),
5191 LayoutBuilder(
5192 builder: (context, constraints) {
5193 final twoColumns = constraints.maxWidth >= 900;
5194 final cards = [
5195 _sectionCard(
5196 context,
5197 'Scheduler',
5198 Icons.schedule_outlined,
5199 Colors.blue,
5200 scheduler,
5201 preferredKeys: const [
5202 'trigger_source_present',
5203 'task_count',
5204 'due_count',
5205 'future_count',
5206 'missing_next_run_count',
5207 ],
5208 ),
5209 _sectionCard(
5210 context,
5211 'Queue',
5212 Icons.queue_outlined,
5213 Colors.teal,
5214 queue,
5215 preferredKeys: const [
5216 'trigger_source_present',
5217 'message_count',
5218 'visible_pending_count',
5219 'delayed_pending_count',
5220 'expired_pending_count',
5221 ],
5222 ),
5223 _sectionCard(
5224 context,
5225 'Events',
5226 Icons.event_outlined,
5227 Colors.purple,
5228 events,
5229 preferredKeys: const [
5230 'state_present',
5231 'event_count',
5232 'event_counts_by_type',
5233 'latest_event',
5234 ],
5235 ),
5236 _sectionCard(
5237 context,
5238 'Subscriptions',
5239 Icons.subscriptions_outlined,
5240 Colors.amber,
5241 subscriptions,
5242 preferredKeys: const [
5243 'subscription_count',
5244 'delivery_status',
5245 'pending_delivery_count',
5246 ],
5247 ),
5248 _sectionCard(
5249 context,
5250 'Retention',
5251 Icons.history_toggle_off_outlined,
5252 Colors.green,
5253 retention,
5254 preferredKeys: const ['keep_count', 'keep_seconds'],
5255 ),
5256 _sectionCard(
5257 context,
5258 'Rate Limit',
5259 Icons.speed_outlined,
5260 Colors.orange,
5261 rateLimit,
5262 ),
5263 ];
5264 if (!twoColumns) {
5265 return Column(
5266 children: [
5267 for (final card in cards) ...[
5268 card,
5269 if (card != cards.last) const SizedBox(height: 12),
5270 ],
5271 ],
5272 );
5273 }
5274 return Wrap(
5275 spacing: 12,
5276 runSpacing: 12,
5277 children: cards
5278 .map(
5279 (card) => SizedBox(
5280 width: (constraints.maxWidth - 12) / 2,
5281 child: card,
5282 ),
5283 )
5284 .toList(),
5285 );
5286 },
5287 ),
5288 const SizedBox(height: 16),
5289 _rawStatusPanel(status),
5290 ],
5291 ],
5292 ),
5293 );
5294 }
5295
5296 Future<void> _refreshDaemonStatus() async {
5297 setState(() => _refreshing = true);
5298 await ScrollData().loadAll();
5299 if (mounted) setState(() => _refreshing = false);
5300 }
5301
5302 Widget _lockedControlBar(BuildContext context) {
5303 return Container(
5304 width: double.infinity,
5305 padding: const EdgeInsets.all(12),
5306 decoration: BoxDecoration(
5307 color: Theme.of(context).colorScheme.surfaceContainerLow,
5308 borderRadius: BorderRadius.circular(8),
5309 border: Border.all(color: Colors.white10),
5310 ),
5311 child: Column(
5312 crossAxisAlignment: CrossAxisAlignment.start,
5313 children: [
5314 Wrap(
5315 spacing: 8,
5316 runSpacing: 8,
5317 children: [
5318 _lockedAction(
5319 Icons.add_alarm_outlined,
5320 'Schedule Task',
5321 'POST /daemon/scheduler/tasks',
5322 ),
5323 _lockedAction(
5324 Icons.playlist_add_outlined,
5325 'Enqueue Message',
5326 'POST /daemon/queue/messages',
5327 ),
5328 _lockedAction(
5329 Icons.replay_outlined,
5330 'Retry Failed',
5331 'PATCH /daemon/queue/messages/{message_id}',
5332 ),
5333 _lockedAction(
5334 Icons.delete_outline,
5335 'Cancel',
5336 'DELETE /daemon/scheduler/tasks/{task_id}',
5337 ),
5338 ],
5339 ),
5340 const SizedBox(height: 8),
5341 Text(
5342 'Write controls staged, locked in Scroll',
5343 style: TextStyle(fontSize: 11, color: Colors.white38),
5344 ),
5345 ],
5346 ),
5347 );
5348 }
5349
5350 Widget _lockedAction(IconData icon, String label, String route) {
5351 return Tooltip(
5352 message: '$route requires an explicit confirmation flow before enabling',
5353 child: OutlinedButton.icon(
5354 onPressed: null,
5355 icon: Icon(icon, size: 15),
5356 label: Text(label),
5357 ),
5358 );
5359 }
5360
5361 Widget _emptyDaemonStatus(BuildContext context) {
5362 return Container(
5363 width: double.infinity,
5364 padding: const EdgeInsets.all(28),
5365 decoration: BoxDecoration(
5366 color: Theme.of(context).colorScheme.surfaceContainerLow,
5367 borderRadius: BorderRadius.circular(8),
5368 border: Border.all(color: Colors.white10),
5369 ),
5370 child: Column(
5371 children: [
5372 Icon(Icons.lock_outline, size: 36, color: Colors.white38),
5373 const SizedBox(height: 10),
5374 const Text(
5375 'Daemon status unavailable',
5376 style: TextStyle(fontWeight: FontWeight.w600),
5377 ),
5378 const SizedBox(height: 4),
5379 Text(
5380 'Connect with an admin Bearer token so Scroll can read scheduler, queue, event, subscription, retention, and rate-limit state.',
5381 textAlign: TextAlign.center,
5382 style: TextStyle(fontSize: 12, color: Colors.white38),
5383 ),
5384 ],
5385 ),
5386 );
5387 }
5388
5389 Widget _metric(IconData icon, String label, String value, Color color) {
5390 return Container(
5391 width: 150,
5392 padding: const EdgeInsets.all(12),
5393 decoration: BoxDecoration(
5394 color: color.withValues(alpha: 0.08),
5395 borderRadius: BorderRadius.circular(8),
5396 border: Border.all(color: color.withValues(alpha: 0.2)),
5397 ),
5398 child: Row(
5399 children: [
5400 Icon(icon, size: 18, color: color),
5401 const SizedBox(width: 8),
5402 Expanded(
5403 child: Column(
5404 crossAxisAlignment: CrossAxisAlignment.start,
5405 children: [
5406 Text(
5407 label,
5408 overflow: TextOverflow.ellipsis,
5409 style: TextStyle(fontSize: 11, color: Colors.white38),
5410 ),
5411 Text(
5412 value,
5413 overflow: TextOverflow.ellipsis,
5414 style: const TextStyle(
5415 fontSize: 15,
5416 fontWeight: FontWeight.w600,
5417 ),
5418 ),
5419 ],
5420 ),
5421 ),
5422 ],
5423 ),
5424 );
5425 }
5426
5427 Widget _eventDeliveriesCard(
5428 BuildContext context, {
5429 required List<Map<String, dynamic>> rows,
5430 required Map<String, dynamic>? response,
5431 }) {
5432 final eventTypes = _deliveryEventTypes(rows);
5433 final activeEventType =
5434 _deliveryEventTypeFilter == 'all' ||
5435 eventTypes.contains(_deliveryEventTypeFilter)
5436 ? _deliveryEventTypeFilter
5437 : 'all';
5438 final orderedRows = [...rows]
5439 ..sort((a, b) => _deliveryPriority(a).compareTo(_deliveryPriority(b)));
5440 final visibleRows = orderedRows.where((row) {
5441 if (!_deliveryMatchesMode(row, _deliveryModeFilter)) return false;
5442 if (activeEventType == 'all') return true;
5443 return _normalizedStatus(_deliveryEventType(row)) == activeEventType;
5444 }).toList();
5445
5446 return Container(
5447 width: double.infinity,
5448 padding: const EdgeInsets.all(14),
5449 decoration: BoxDecoration(
5450 color: Theme.of(context).colorScheme.surfaceContainerLow,
5451 borderRadius: BorderRadius.circular(8),
5452 border: Border.all(color: Colors.white10),
5453 ),
5454 child: Column(
5455 crossAxisAlignment: CrossAxisAlignment.start,
5456 children: [
5457 Row(
5458 children: [
5459 Icon(
5460 Icons.forward_to_inbox_outlined,
5461 size: 18,
5462 color: Colors.indigo,
5463 ),
5464 const SizedBox(width: 8),
5465 Expanded(
5466 child: Column(
5467 crossAxisAlignment: CrossAxisAlignment.start,
5468 children: [
5469 const Text(
5470 'Event Deliveries',
5471 overflow: TextOverflow.ellipsis,
5472 style: TextStyle(
5473 fontSize: 13,
5474 fontWeight: FontWeight.w700,
5475 ),
5476 ),
5477 const SizedBox(height: 2),
5478 Text(
5479 'GET /events/deliveries',
5480 overflow: TextOverflow.ellipsis,
5481 style: TextStyle(
5482 fontSize: 11,
5483 color: Colors.white38,
5484 fontFamily: 'monospace',
5485 ),
5486 ),
5487 ],
5488 ),
5489 ),
5490 const SizedBox(width: 8),
5491 _statusChip(
5492 _listCountLabel(response, visibleRows.length, rows.length),
5493 Colors.indigo,
5494 ),
5495 const SizedBox(width: 4),
5496 IconButton(
5497 onPressed: _refreshing ? null : _refreshDaemonStatus,
5498 icon: const Icon(Icons.refresh, size: 16),
5499 tooltip: 'Refresh',
5500 visualDensity: VisualDensity.compact,
5501 ),
5502 ],
5503 ),
5504 const SizedBox(height: 12),
5505 Wrap(
5506 spacing: 6,
5507 runSpacing: 6,
5508 crossAxisAlignment: WrapCrossAlignment.center,
5509 children: [
5510 _filterChip(
5511 'All',
5512 'all',
5513 _deliveryModeFilter,
5514 (value) => setState(() => _deliveryModeFilter = value),
5515 Colors.indigo,
5516 ),
5517 _filterChip(
5518 'Failed',
5519 'failed',
5520 _deliveryModeFilter,
5521 (value) => setState(() => _deliveryModeFilter = value),
5522 Colors.red,
5523 ),
5524 _filterChip(
5525 'Pending',
5526 'pending',
5527 _deliveryModeFilter,
5528 (value) => setState(() => _deliveryModeFilter = value),
5529 Colors.orange,
5530 ),
5531 _eventTypeMenu(eventTypes, activeEventType),
5532 ],
5533 ),
5534 const SizedBox(height: 12),
5535 if (response == null)
5536 _daemonEmptyState(
5537 context,
5538 Icons.forward_to_inbox_outlined,
5539 'Event deliveries unavailable',
5540 'The endpoint did not return data for this session.',
5541 )
5542 else if (rows.isEmpty)
5543 _daemonEmptyState(
5544 context,
5545 Icons.forward_to_inbox_outlined,
5546 'No deliveries reported',
5547 'The object server returned an empty list.',
5548 )
5549 else if (visibleRows.isEmpty)
5550 _daemonEmptyState(
5551 context,
5552 Icons.filter_alt_off_outlined,
5553 'No deliveries match the filters',
5554 'No matching rows in the current response.',
5555 )
5556 else
5557 Column(
5558 children: [
5559 for (var i = 0; i < visibleRows.length; i++)
5560 _deliveryRow(context, visibleRows[i], i),
5561 ],
5562 ),
5563 if (response != null) ...[
5564 const SizedBox(height: 8),
5565 _rawJsonPanel(
5566 'Raw Event Deliveries response',
5567 _redactedMap(response),
5568 ),
5569 ],
5570 ],
5571 ),
5572 );
5573 }
5574
5575 Widget _eventTypeMenu(List<String> eventTypes, String activeEventType) {
5576 return Container(
5577 height: 32,
5578 padding: const EdgeInsets.symmetric(horizontal: 10),
5579 decoration: BoxDecoration(
5580 color: Colors.white.withValues(alpha: 0.04),
5581 borderRadius: BorderRadius.circular(8),
5582 border: Border.all(color: Colors.white12),
5583 ),
5584 child: DropdownButtonHideUnderline(
5585 child: DropdownButton<String>(
5586 value: activeEventType,
5587 isDense: true,
5588 icon: const Icon(Icons.expand_more, size: 16),
5589 style: const TextStyle(fontSize: 11, color: Colors.white70),
5590 dropdownColor: Theme.of(context).colorScheme.surfaceContainerHigh,
5591 onChanged: (value) {
5592 if (value != null) {
5593 setState(() => _deliveryEventTypeFilter = value);
5594 }
5595 },
5596 items: [
5597 const DropdownMenuItem(
5598 value: 'all',
5599 child: Text('All event types'),
5600 ),
5601 for (final eventType in eventTypes)
5602 DropdownMenuItem(
5603 value: eventType,
5604 child: Text(_titleCase(eventType)),
5605 ),
5606 ],
5607 ),
5608 ),
5609 );
5610 }
5611
5612 Widget _deliveryRow(
5613 BuildContext context,
5614 Map<String, dynamic> row,
5615 int index,
5616 ) {
5617 final subscriber =
5618 _firstString(row, const ['subscriber_id', 'subscription_id', 'id']) ??
5619 'subscription ${index + 1}';
5620 final eventType = _deliveryEventType(row);
5621 final status = _deliveryStatus(row);
5622 final pendingCount = _deliveryPendingCount(row);
5623 final pending = _deliveryPending(row);
5624 final attemptLine = _deliveryAttemptLine(row);
5625 final eventLine = _deliveryEventLine(row);
5626
5627 return LayoutBuilder(
5628 builder: (context, constraints) {
5629 final compact = constraints.maxWidth < 740;
5630 final statusChips = Wrap(
5631 spacing: 6,
5632 runSpacing: 6,
5633 children: [
5634 _statusChip(_titleCase(status), _statusTone(status)),
5635 _statusChip(
5636 pending ? 'PENDING ${pendingCount ?? ''}'.trim() : 'PENDING 0',
5637 pending ? Colors.orange : Colors.white38,
5638 ),
5639 _callbackChip(row),
5640 ],
5641 );
5642 final rowBody = compact
5643 ? Column(
5644 crossAxisAlignment: CrossAxisAlignment.start,
5645 children: [
5646 _daemonIdBlock(subscriber, 'Event: ${_titleCase(eventType)}'),
5647 const SizedBox(height: 8),
5648 statusChips,
5649 if (attemptLine.isNotEmpty || eventLine.isNotEmpty) ...[
5650 const SizedBox(height: 8),
5651 Text(
5652 [
5653 attemptLine,
5654 eventLine,
5655 ].where((part) => part.isNotEmpty).join(' | '),
5656 maxLines: 3,
5657 overflow: TextOverflow.ellipsis,
5658 style: TextStyle(fontSize: 12, color: Colors.white54),
5659 ),
5660 ],
5661 ],
5662 )
5663 : Row(
5664 children: [
5665 Expanded(
5666 flex: 4,
5667 child: _daemonIdBlock(
5668 subscriber,
5669 'Event: ${_titleCase(eventType)}',
5670 ),
5671 ),
5672 const SizedBox(width: 12),
5673 Expanded(flex: 3, child: statusChips),
5674 const SizedBox(width: 12),
5675 Expanded(
5676 flex: 5,
5677 child: Text(
5678 [
5679 attemptLine,
5680 eventLine,
5681 ].where((part) => part.isNotEmpty).join(' | '),
5682 maxLines: 3,
5683 overflow: TextOverflow.ellipsis,
5684 style: TextStyle(fontSize: 12, color: Colors.white54),
5685 ),
5686 ),
5687 ],
5688 );
5689
5690 return Container(
5691 width: double.infinity,
5692 margin: EdgeInsets.only(bottom: compact ? 10 : 8),
5693 padding: const EdgeInsets.all(10),
5694 decoration: BoxDecoration(
5695 color: Theme.of(
5696 context,
5697 ).colorScheme.surface.withValues(alpha: 0.36),
5698 borderRadius: BorderRadius.circular(8),
5699 border: Border.all(color: Colors.white10),
5700 ),
5701 child: rowBody,
5702 );
5703 },
5704 );
5705 }
5706
5707 Widget _daemonListCard(
5708 BuildContext context, {
5709 required String title,
5710 required String route,
5711 required IconData icon,
5712 required Color color,
5713 required List<Map<String, dynamic>> rows,
5714 required Map<String, dynamic>? response,
5715 required String filter,
5716 required ValueChanged<String> onFilterChanged,
5717 required _DaemonListKind kind,
5718 }) {
5719 final statuses = _statusValues(rows);
5720 final activeFilter = filter == 'all' || statuses.contains(filter)
5721 ? filter
5722 : 'all';
5723 final visibleRows = activeFilter == 'all'
5724 ? rows
5725 : rows.where((row) {
5726 return _normalizedStatus(_rowStatus(row)) == activeFilter;
5727 }).toList();
5728
5729 return Container(
5730 padding: const EdgeInsets.all(14),
5731 decoration: BoxDecoration(
5732 color: Theme.of(context).colorScheme.surfaceContainerLow,
5733 borderRadius: BorderRadius.circular(8),
5734 border: Border.all(color: Colors.white10),
5735 ),
5736 child: Column(
5737 crossAxisAlignment: CrossAxisAlignment.start,
5738 children: [
5739 Row(
5740 children: [
5741 Icon(icon, size: 18, color: color),
5742 const SizedBox(width: 8),
5743 Expanded(
5744 child: Column(
5745 crossAxisAlignment: CrossAxisAlignment.start,
5746 children: [
5747 Text(
5748 title,
5749 overflow: TextOverflow.ellipsis,
5750 style: const TextStyle(
5751 fontSize: 13,
5752 fontWeight: FontWeight.w700,
5753 ),
5754 ),
5755 const SizedBox(height: 2),
5756 Text(
5757 route,
5758 overflow: TextOverflow.ellipsis,
5759 style: TextStyle(
5760 fontSize: 11,
5761 color: Colors.white38,
5762 fontFamily: 'monospace',
5763 ),
5764 ),
5765 ],
5766 ),
5767 ),
5768 const SizedBox(width: 8),
5769 _statusChip(
5770 _listCountLabel(response, visibleRows.length, rows.length),
5771 color,
5772 ),
5773 const SizedBox(width: 4),
5774 IconButton(
5775 onPressed: _refreshing ? null : _refreshDaemonStatus,
5776 icon: const Icon(Icons.refresh, size: 16),
5777 tooltip: 'Refresh',
5778 visualDensity: VisualDensity.compact,
5779 ),
5780 ],
5781 ),
5782 const SizedBox(height: 12),
5783 Wrap(
5784 spacing: 6,
5785 runSpacing: 6,
5786 children: [
5787 _filterChip('All', 'all', activeFilter, onFilterChanged, color),
5788 for (final status in statuses)
5789 _filterChip(
5790 _titleCase(status),
5791 status,
5792 activeFilter,
5793 onFilterChanged,
5794 color,
5795 ),
5796 ],
5797 ),
5798 const SizedBox(height: 12),
5799 if (response == null)
5800 _daemonEmptyState(
5801 context,
5802 icon,
5803 '$title unavailable',
5804 'The endpoint did not return data for this session.',
5805 )
5806 else if (rows.isEmpty)
5807 _daemonEmptyState(
5808 context,
5809 icon,
5810 'No ${kind == _DaemonListKind.scheduler ? 'tasks' : 'messages'} reported',
5811 'The object server returned an empty list.',
5812 )
5813 else if (visibleRows.isEmpty)
5814 _daemonEmptyState(
5815 context,
5816 Icons.filter_alt_off_outlined,
5817 'No rows match ${_titleCase(activeFilter)}',
5818 'No matching rows in the current response.',
5819 )
5820 else
5821 Column(
5822 children: [
5823 for (var i = 0; i < visibleRows.length; i++)
5824 _daemonRow(context, visibleRows[i], i, kind),
5825 ],
5826 ),
5827 if (response != null) ...[
5828 const SizedBox(height: 8),
5829 _rawJsonPanel('Raw $title response', response),
5830 ],
5831 ],
5832 ),
5833 );
5834 }
5835
5836 Widget _filterChip(
5837 String label,
5838 String value,
5839 String activeFilter,
5840 ValueChanged<String> onFilterChanged,
5841 Color color,
5842 ) {
5843 final selected = value == activeFilter;
5844 return FilterChip(
5845 visualDensity: VisualDensity.compact,
5846 materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
5847 label: Text(label),
5848 selected: selected,
5849 showCheckmark: false,
5850 onSelected: (_) => onFilterChanged(value),
5851 backgroundColor: Colors.white.withValues(alpha: 0.04),
5852 selectedColor: color.withValues(alpha: 0.16),
5853 side: BorderSide(
5854 color: selected ? color.withValues(alpha: 0.4) : Colors.white12,
5855 ),
5856 labelStyle: TextStyle(
5857 fontSize: 11,
5858 color: selected ? color : Colors.white54,
5859 fontWeight: selected ? FontWeight.w700 : FontWeight.w500,
5860 ),
5861 );
5862 }
5863
5864 Widget _daemonEmptyState(
5865 BuildContext context,
5866 IconData icon,
5867 String title,
5868 String detail,
5869 ) {
5870 return Container(
5871 width: double.infinity,
5872 padding: const EdgeInsets.all(18),
5873 decoration: BoxDecoration(
5874 color: Theme.of(context).colorScheme.surface.withValues(alpha: 0.45),
5875 borderRadius: BorderRadius.circular(8),
5876 border: Border.all(color: Colors.white10),
5877 ),
5878 child: Column(
5879 children: [
5880 Icon(icon, size: 26, color: Colors.white38),
5881 const SizedBox(height: 8),
5882 Text(title, style: const TextStyle(fontWeight: FontWeight.w600)),
5883 const SizedBox(height: 4),
5884 Text(
5885 detail,
5886 textAlign: TextAlign.center,
5887 style: TextStyle(fontSize: 12, color: Colors.white38),
5888 ),
5889 ],
5890 ),
5891 );
5892 }
5893
5894 Widget _daemonRow(
5895 BuildContext context,
5896 Map<String, dynamic> row,
5897 int index,
5898 _DaemonListKind kind,
5899 ) {
5900 final id =
5901 _firstString(
5902 row,
5903 kind == _DaemonListKind.scheduler
5904 ? const ['task_id', 'id', 'name', 'key']
5905 : const ['message_id', 'id', 'key'],
5906 ) ??
5907 '${kind == _DaemonListKind.scheduler ? 'task' : 'message'} ${index + 1}';
5908 final status = _rowStatus(row);
5909 final detail = _daemonDetailLine(row, kind);
5910 final contextValue = _daemonContextValue(row, kind);
5911
5912 return LayoutBuilder(
5913 builder: (context, constraints) {
5914 final compact = constraints.maxWidth < 620;
5915 final rowBody = compact
5916 ? Column(
5917 crossAxisAlignment: CrossAxisAlignment.start,
5918 children: [
5919 Row(
5920 children: [
5921 Expanded(child: _daemonIdBlock(id, detail)),
5922 const SizedBox(width: 8),
5923 _statusChip(_titleCase(status), _statusTone(status)),
5924 ],
5925 ),
5926 const SizedBox(height: 8),
5927 Row(
5928 children: [
5929 Expanded(
5930 child: Text(
5931 contextValue,
5932 overflow: TextOverflow.ellipsis,
5933 style: TextStyle(fontSize: 12, color: Colors.white54),
5934 ),
5935 ),
5936 const SizedBox(width: 8),
5937 _payloadChip(row),
5938 ],
5939 ),
5940 ],
5941 )
5942 : Row(
5943 children: [
5944 Expanded(flex: 5, child: _daemonIdBlock(id, detail)),
5945 const SizedBox(width: 12),
5946 Expanded(
5947 flex: 2,
5948 child: Align(
5949 alignment: Alignment.centerLeft,
5950 child: _statusChip(
5951 _titleCase(status),
5952 _statusTone(status),
5953 ),
5954 ),
5955 ),
5956 const SizedBox(width: 12),
5957 Expanded(
5958 flex: 3,
5959 child: Text(
5960 contextValue,
5961 overflow: TextOverflow.ellipsis,
5962 style: TextStyle(fontSize: 12, color: Colors.white54),
5963 ),
5964 ),
5965 const SizedBox(width: 12),
5966 SizedBox(width: 92, child: Align(child: _payloadChip(row))),
5967 ],
5968 );
5969
5970 return Container(
5971 width: double.infinity,
5972 margin: EdgeInsets.only(bottom: compact ? 10 : 8),
5973 padding: const EdgeInsets.all(10),
5974 decoration: BoxDecoration(
5975 color: Theme.of(
5976 context,
5977 ).colorScheme.surface.withValues(alpha: 0.36),
5978 borderRadius: BorderRadius.circular(8),
5979 border: Border.all(color: Colors.white10),
5980 ),
5981 child: rowBody,
5982 );
5983 },
5984 );
5985 }
5986
5987 Widget _daemonIdBlock(String id, String detail) {
5988 return Column(
5989 crossAxisAlignment: CrossAxisAlignment.start,
5990 children: [
5991 Text(
5992 id,
5993 maxLines: 1,
5994 overflow: TextOverflow.ellipsis,
5995 style: const TextStyle(
5996 fontSize: 12,
5997 fontFamily: 'monospace',
5998 fontWeight: FontWeight.w700,
5999 ),
6000 ),
6001 if (detail.isNotEmpty) ...[
6002 const SizedBox(height: 4),
6003 Text(
6004 detail,
6005 maxLines: 2,
6006 overflow: TextOverflow.ellipsis,
6007 style: TextStyle(fontSize: 11, color: Colors.white38),
6008 ),
6009 ],
6010 ],
6011 );
6012 }
6013
6014 Widget _payloadChip(Map<String, dynamic> row) {
6015 final present = _payloadPresent(row);
6016 if (present == true) return _statusChip('PAYLOAD', Colors.amber);
6017 if (present == false) return _statusChip('NO PAYLOAD', Colors.white38);
6018 return _statusChip('PAYLOAD ?', Colors.white38);
6019 }
6020
6021 Widget _callbackChip(Map<String, dynamic> row) {
6022 final present = _callbackPresent(row);
6023 if (present == true) return _statusChip('CALLBACK', Colors.indigo);
6024 if (present == false) return _statusChip('NO CALLBACK', Colors.white38);
6025 return _statusChip('CALLBACK ?', Colors.white38);
6026 }
6027
6028 List<String> _deliveryEventTypes(List<Map<String, dynamic>> rows) {
6029 final values = <String>{};
6030 for (final row in rows) {
6031 final eventType = _normalizedStatus(_deliveryEventType(row));
6032 if (eventType.isNotEmpty && eventType != 'unknown') values.add(eventType);
6033 }
6034 final sorted = values.toList()..sort();
6035 return sorted;
6036 }
6037
6038 String _deliveryEventType(Map<String, dynamic> row) {
6039 return _firstString(row, const ['event_type', 'eventType', 'type']) ??
6040 'unknown';
6041 }
6042
6043 String _deliveryStatus(Map<String, dynamic> row) {
6044 final delivery = _mapValue(row['delivery']);
6045 return _firstString(delivery, const ['status', 'state']) ??
6046 _firstString(row, const [
6047 'delivery_status',
6048 'deliveryStatus',
6049 'status',
6050 'state',
6051 ]) ??
6052 'idle';
6053 }
6054
6055 bool _deliveryMatchesMode(Map<String, dynamic> row, String mode) {
6056 return switch (mode) {
6057 'failed' => _normalizedStatus(_deliveryStatus(row)) == 'failed',
6058 'pending' => _deliveryPending(row),
6059 _ => true,
6060 };
6061 }
6062
6063 int _deliveryPriority(Map<String, dynamic> row) {
6064 if (_normalizedStatus(_deliveryStatus(row)) == 'failed') return 0;
6065 if (_deliveryPending(row)) return 1;
6066 return 2;
6067 }
6068
6069 bool _deliveryPending(Map<String, dynamic> row) {
6070 final pending = _boolFromValue(row['pending']);
6071 if (pending != null) return pending;
6072 return (_deliveryPendingCount(row) ?? 0) > 0;
6073 }
6074
6075 int? _deliveryPendingCount(Map<String, dynamic> row) {
6076 return _intFromValue(row['pending_count'] ?? row['pendingCount']);
6077 }
6078
6079 String _deliveryAttemptLine(Map<String, dynamic> row) {
6080 final delivery = _mapValue(row['delivery']);
6081 final values = {...row, ...delivery};
6082 final attempt = _firstString(values, const [
6083 'last_attempt_at',
6084 'lastAttemptAt',
6085 'last_attempt',
6086 'last_failure_at',
6087 'last_success_at',
6088 ]);
6089 final code = _firstString(values, const [
6090 'last_status_code',
6091 'lastStatusCode',
6092 'status_code',
6093 'http_status',
6094 ]);
6095 final error = _firstString(values, const [
6096 'last_error',
6097 'lastError',
6098 'error',
6099 ]);
6100 final parts = [
6101 if (attempt != null) 'Attempt: $attempt',
6102 if (code != null) 'Status: $code',
6103 if (error != null) 'Error: $error',
6104 ];
6105 return parts.take(3).join(' | ');
6106 }
6107
6108 String _deliveryEventLine(Map<String, dynamic> row) {
6109 final next = _eventReference(
6110 row['next_pending_event'] ?? row['next_pending_event_id'],
6111 );
6112 final latest = _eventReference(
6113 row['latest_pending_event'] ?? row['latest_pending_event_id'],
6114 );
6115 final last = _eventReference(row['last_event_id'] ?? row['last_event']);
6116 final parts = [
6117 if (next != null) 'Next: $next',
6118 if (latest != null) 'Latest: $latest',
6119 if (last != null) 'Last: $last',
6120 ];
6121 return parts.take(3).join(' | ');
6122 }
6123
6124 String? _eventReference(dynamic value) {
6125 if (value == null) return null;
6126 final map = _mapValue(value);
6127 if (map.isNotEmpty) {
6128 return _firstString(map, const ['event_id', 'id', 'key']) ??
6129 _valueLabel(map);
6130 }
6131 final text = _valueLabel(value).trim();
6132 return text.isEmpty || text == '?' ? null : text;
6133 }
6134
6135 bool? _callbackPresent(Map<String, dynamic> row) {
6136 for (final key in const [
6137 'callback_url_present',
6138 'callbackUrlPresent',
6139 'has_callback_url',
6140 ]) {
6141 final parsed = _boolFromValue(row[key]);
6142 if (parsed != null) return parsed;
6143 }
6144 if (row.containsKey('callback_url')) return row['callback_url'] != null;
6145 return null;
6146 }
6147
6148 Map<String, dynamic> _mapValue(dynamic value) {
6149 if (value is Map<String, dynamic>) return value;
6150 if (value is Map) {
6151 return value.map((key, item) => MapEntry(key.toString(), item));
6152 }
6153 return const {};
6154 }
6155
6156 int? _intFromValue(dynamic value) {
6157 if (value is int) return value;
6158 if (value is num) return value.toInt();
6159 if (value is String) return int.tryParse(value);
6160 return null;
6161 }
6162
6163 bool? _boolFromValue(dynamic value) {
6164 if (value is bool) return value;
6165 if (value is num) return value != 0;
6166 if (value is String) {
6167 final normalized = value.toLowerCase();
6168 if (normalized == 'true' || normalized == 'yes' || normalized == '1') {
6169 return true;
6170 }
6171 if (normalized == 'false' || normalized == 'no' || normalized == '0') {
6172 return false;
6173 }
6174 }
6175 return null;
6176 }
6177
6178 Map<String, dynamic> _redactedMap(Map<String, dynamic> source) {
6179 return source.map((key, value) {
6180 return MapEntry(key, _redactedValue(key, value));
6181 });
6182 }
6183
6184 dynamic _redactedValue(String key, dynamic value) {
6185 final normalized = key.toLowerCase();
6186 if (normalized.contains('payload') ||
6187 normalized.contains('callback_url') ||
6188 normalized.contains('secret') ||
6189 normalized.contains('token') ||
6190 normalized == 'body' ||
6191 normalized == 'content') {
6192 return '[redacted]';
6193 }
6194 if (value is Map<String, dynamic>) return _redactedMap(value);
6195 if (value is Map) {
6196 return value.map((itemKey, itemValue) {
6197 final textKey = itemKey.toString();
6198 return MapEntry(textKey, _redactedValue(textKey, itemValue));
6199 });
6200 }
6201 if (value is List) {
6202 return value.map((item) {
6203 if (item is Map<String, dynamic>) return _redactedMap(item);
6204 if (item is Map) {
6205 return item.map((itemKey, itemValue) {
6206 final textKey = itemKey.toString();
6207 return MapEntry(textKey, _redactedValue(textKey, itemValue));
6208 });
6209 }
6210 return item;
6211 }).toList();
6212 }
6213 return value;
6214 }
6215
6216 List<String> _statusValues(List<Map<String, dynamic>> rows) {
6217 final values = <String>{};
6218 for (final row in rows) {
6219 final status = _normalizedStatus(_rowStatus(row));
6220 if (status.isNotEmpty && status != 'unknown') values.add(status);
6221 }
6222 final sorted = values.toList()..sort();
6223 return sorted;
6224 }
6225
6226 String _rowStatus(Map<String, dynamic> row) {
6227 return _firstString(row, const [
6228 'status',
6229 'state',
6230 'delivery_status',
6231 'run_status',
6232 'visibility',
6233 ]) ??
6234 'unknown';
6235 }
6236
6237 String _daemonContextValue(Map<String, dynamic> row, _DaemonListKind kind) {
6238 if (kind == _DaemonListKind.queue) {
6239 final queue = _firstString(row, const ['queue_name', 'queue']);
6240 final priority = _firstString(row, const ['priority']);
6241 final visibleAt = _firstString(row, const [
6242 'visible_at',
6243 'available_at',
6244 'run_at',
6245 ]);
6246 final parts = [
6247 if (queue != null) queue,
6248 if (priority != null) 'p$priority',
6249 if (visibleAt != null) visibleAt,
6250 ];
6251 if (parts.isNotEmpty) return parts.join(' | ');
6252 }
6253 return _firstString(
6254 row,
6255 kind == _DaemonListKind.scheduler
6256 ? const [
6257 'next_run_at',
6258 'run_at',
6259 'scheduled_for',
6260 'cron',
6261 'interval_seconds',
6262 'created_at',
6263 ]
6264 : const ['created_at', 'updated_at', 'expires_at', 'attempts'],
6265 ) ??
6266 'No timing reported';
6267 }
6268
6269 String _daemonDetailLine(Map<String, dynamic> row, _DaemonListKind kind) {
6270 final preferred = kind == _DaemonListKind.scheduler
6271 ? const [
6272 'task_type',
6273 'handler',
6274 'object_id',
6275 'method',
6276 'last_run_at',
6277 'updated_at',
6278 ]
6279 : const [
6280 'topic',
6281 'message_type',
6282 'handler',
6283 'attempts',
6284 'max_attempts',
6285 'updated_at',
6286 ];
6287 final pieces = <String>[];
6288 for (final key in preferred) {
6289 final value = row[key];
6290 if (_isDetailValue(value)) {
6291 pieces.add('${_titleCase(key)}: ${_valueLabel(value)}');
6292 }
6293 }
6294 if (pieces.isEmpty) {
6295 for (final entry in row.entries) {
6296 if (_skipDaemonDetailKey(entry.key)) continue;
6297 if (_isDetailValue(entry.value)) {
6298 pieces.add('${_titleCase(entry.key)}: ${_valueLabel(entry.value)}');
6299 }
6300 if (pieces.length >= 3) break;
6301 }
6302 }
6303 return pieces.take(3).join(' | ');
6304 }
6305
6306 bool _isDetailValue(dynamic value) {
6307 if (value == null) return false;
6308 if (value is String) return value.trim().isNotEmpty;
6309 if (value is List) return value.isNotEmpty;
6310 if (value is Map) return value.isNotEmpty;
6311 return true;
6312 }
6313
6314 bool _skipDaemonDetailKey(String key) {
6315 final normalized = key.toLowerCase();
6316 if (normalized.contains('payload')) return true;
6317 if (normalized == 'body' ||
6318 normalized == 'content' ||
6319 normalized == 'data' ||
6320 normalized == 'status' ||
6321 normalized == 'state' ||
6322 normalized == 'id' ||
6323 normalized == 'task_id' ||
6324 normalized == 'message_id' ||
6325 normalized == 'key') {
6326 return true;
6327 }
6328 return false;
6329 }
6330
6331 bool? _payloadPresent(Map<String, dynamic> row) {
6332 for (final key in const [
6333 'payload_present',
6334 'has_payload',
6335 'payloadPresent',
6336 ]) {
6337 final value = row[key];
6338 if (value is bool) return value;
6339 if (value is num) return value != 0;
6340 if (value is String) {
6341 final normalized = value.toLowerCase();
6342 if (normalized == 'true' || normalized == 'yes' || normalized == '1') {
6343 return true;
6344 }
6345 if (normalized == 'false' || normalized == 'no' || normalized == '0') {
6346 return false;
6347 }
6348 }
6349 }
6350 if (row.containsKey('payload')) return row['payload'] != null;
6351 return null;
6352 }
6353
6354 String? _firstString(Map<String, dynamic> row, List<String> keys) {
6355 for (final key in keys) {
6356 final value = row[key];
6357 if (value == null) continue;
6358 final text = _valueLabel(value).trim();
6359 if (text.isNotEmpty && text != '?') return text;
6360 }
6361 return null;
6362 }
6363
6364 String _normalizedStatus(String status) {
6365 return status.trim().toLowerCase().replaceAll(' ', '_');
6366 }
6367
6368 String _listCountLabel(
6369 Map<String, dynamic>? response,
6370 int visibleCount,
6371 int rowCount,
6372 ) {
6373 final count = _responseCount(response, const ['count', 'total']);
6374 if (count == null) return '$visibleCount rows';
6375 if (visibleCount != rowCount) return '$visibleCount/$count shown';
6376 return '$count rows';
6377 }
6378
6379 int? _responseCount(Map<String, dynamic>? response, List<String> keys) {
6380 if (response == null) return null;
6381 for (final key in keys) {
6382 final value = response[key];
6383 if (value is int) return value;
6384 if (value is num) return value.toInt();
6385 if (value is String) {
6386 final parsed = int.tryParse(value);
6387 if (parsed != null) return parsed;
6388 }
6389 }
6390 return null;
6391 }
6392
6393 Color _statusTone(String status) {
6394 final normalized = _normalizedStatus(status);
6395 if (normalized == 'ok' ||
6396 normalized == 'ready' ||
6397 normalized == 'visible' ||
6398 normalized == 'running' ||
6399 normalized == 'active' ||
6400 normalized == 'complete' ||
6401 normalized == 'completed' ||
6402 normalized == 'sent') {
6403 return Colors.green;
6404 }
6405 if (normalized == 'failed' ||
6406 normalized == 'error' ||
6407 normalized == 'expired' ||
6408 normalized == 'dead' ||
6409 normalized == 'cancelled' ||
6410 normalized == 'canceled') {
6411 return Colors.red;
6412 }
6413 if (normalized == 'pending' ||
6414 normalized == 'delayed' ||
6415 normalized == 'scheduled' ||
6416 normalized == 'due' ||
6417 normalized == 'future' ||
6418 normalized == 'retry') {
6419 return Colors.orange;
6420 }
6421 return Colors.white54;
6422 }
6423
6424 Widget _sectionCard(
6425 BuildContext context,
6426 String title,
6427 IconData icon,
6428 Color color,
6429 Map<String, dynamic> values, {
6430 List<String> preferredKeys = const [],
6431 }) {
6432 final rows = _orderedRows(values, preferredKeys);
6433 return Container(
6434 padding: const EdgeInsets.all(14),
6435 decoration: BoxDecoration(
6436 color: Theme.of(context).colorScheme.surfaceContainerLow,
6437 borderRadius: BorderRadius.circular(8),
6438 border: Border.all(color: Colors.white10),
6439 ),
6440 child: Column(
6441 crossAxisAlignment: CrossAxisAlignment.start,
6442 children: [
6443 Row(
6444 children: [
6445 Icon(icon, size: 18, color: color),
6446 const SizedBox(width: 8),
6447 Text(
6448 title,
6449 style: const TextStyle(
6450 fontSize: 13,
6451 fontWeight: FontWeight.w700,
6452 ),
6453 ),
6454 const Spacer(),
6455 _statusChip(rows.isEmpty ? 'EMPTY' : 'READ ONLY', color),
6456 ],
6457 ),
6458 const SizedBox(height: 12),
6459 if (rows.isEmpty)
6460 Text(
6461 'Not reported',
6462 style: TextStyle(fontSize: 12, color: Colors.white38),
6463 )
6464 else
6465 ...rows.map((entry) => _statusRow(entry.key, entry.value)),
6466 ],
6467 ),
6468 );
6469 }
6470
6471 Widget _statusRow(String label, dynamic value) {
6472 return Padding(
6473 padding: const EdgeInsets.only(bottom: 7),
6474 child: Row(
6475 crossAxisAlignment: CrossAxisAlignment.start,
6476 children: [
6477 Expanded(
6478 flex: 5,
6479 child: Text(
6480 _titleCase(label),
6481 overflow: TextOverflow.ellipsis,
6482 style: TextStyle(fontSize: 12, color: Colors.white54),
6483 ),
6484 ),
6485 const SizedBox(width: 10),
6486 Expanded(
6487 flex: 7,
6488 child: Text(
6489 _valueLabel(value),
6490 maxLines: 3,
6491 overflow: TextOverflow.ellipsis,
6492 textAlign: TextAlign.right,
6493 style: TextStyle(
6494 fontSize: 12,
6495 color: _valueColor(value),
6496 fontWeight: FontWeight.w600,
6497 ),
6498 ),
6499 ),
6500 ],
6501 ),
6502 );
6503 }
6504
6505 Widget _rawStatusPanel(Map<String, dynamic> status) {
6506 return _rawJsonPanel('Raw daemon response', status);
6507 }
6508
6509 Widget _rawJsonPanel(String title, Map<String, dynamic> status) {
6510 return ExpansionTile(
6511 tilePadding: const EdgeInsets.symmetric(horizontal: 4),
6512 title: Text(title, style: TextStyle(fontSize: 12, color: Colors.white54)),
6513 children: [
6514 Container(
6515 width: double.infinity,
6516 padding: const EdgeInsets.all(12),
6517 decoration: BoxDecoration(
6518 color: Colors.black26,
6519 borderRadius: BorderRadius.circular(8),
6520 border: Border.all(color: Colors.white10),
6521 ),
6522 child: SelectableText(
6523 const JsonEncoder.withIndent(' ').convert(status),
6524 style: const TextStyle(
6525 fontFamily: 'monospace',
6526 fontSize: 11,
6527 height: 1.35,
6528 ),
6529 ),
6530 ),
6531 ],
6532 );
6533 }
6534
6535 Widget _statusChip(String text, Color color) {
6536 return Container(
6537 padding: const EdgeInsets.symmetric(horizontal: 7, vertical: 2),
6538 decoration: BoxDecoration(
6539 color: color.withValues(alpha: 0.1),
6540 borderRadius: BorderRadius.circular(4),
6541 border: Border.all(color: color.withValues(alpha: 0.16)),
6542 ),
6543 child: Text(
6544 text,
6545 style: TextStyle(
6546 fontSize: 10,
6547 color: color,
6548 fontWeight: FontWeight.bold,
6549 ),
6550 ),
6551 );
6552 }
6553
6554 List<MapEntry<String, dynamic>> _orderedRows(
6555 Map<String, dynamic> values,
6556 List<String> preferredKeys,
6557 ) {
6558 final rows = <MapEntry<String, dynamic>>[];
6559 final used = <String>{};
6560 for (final key in preferredKeys) {
6561 if (values.containsKey(key)) {
6562 rows.add(MapEntry(key, values[key]));
6563 used.add(key);
6564 }
6565 }
6566 for (final entry in values.entries) {
6567 if (!used.contains(entry.key)) rows.add(entry);
6568 }
6569 return rows.take(8).toList();
6570 }
6571
6572 int? _firstCount(Map<String, dynamic> values, List<String> keys) {
6573 for (final key in keys) {
6574 final value = values[key];
6575 if (value is int) return value;
6576 if (value is num) return value.toInt();
6577 if (value is String) {
6578 final parsed = int.tryParse(value);
6579 if (parsed != null) return parsed;
6580 }
6581 if (value is Map) {
6582 var total = 0;
6583 var found = false;
6584 for (final item in value.values) {
6585 if (item is num) {
6586 total += item.toInt();
6587 found = true;
6588 }
6589 }
6590 if (found) return total;
6591 }
6592 }
6593 return null;
6594 }
6595
6596 String _countText(int? value) => value == null ? '?' : value.toString();
6597
6598 String _valueLabel(dynamic value) {
6599 if (value == null) return '?';
6600 if (value is bool) return value ? 'yes' : 'no';
6601 if (value is num || value is String) return value.toString();
6602 if (value is List) return '${value.length} items';
6603 if (value is Map) {
6604 final entries = value.entries.take(4).map((entry) {
6605 return '${_titleCase(entry.key.toString())}: ${_valueLabel(entry.value)}';
6606 });
6607 return entries.join(', ');
6608 }
6609 return value.toString();
6610 }
6611
6612 String _titleCase(String value) {
6613 return value
6614 .replaceAll('_', ' ')
6615 .replaceAll('-', ' ')
6616 .split(' ')
6617 .where((part) => part.isNotEmpty)
6618 .map((part) => '${part[0].toUpperCase()}${part.substring(1)}')
6619 .join(' ');
6620 }
6621
6622 Color _valueColor(dynamic value) {
6623 if (value is bool) return value ? Colors.green : Colors.orange;
6624 final normalized = value?.toString().toLowerCase() ?? '';
6625 if (normalized == 'ok' ||
6626 normalized == 'ready' ||
6627 normalized == 'enabled' ||
6628 normalized == 'present') {
6629 return Colors.green;
6630 }
6631 if (normalized == 'missing' ||
6632 normalized == 'disabled' ||
6633 normalized == 'blocked') {
6634 return Colors.orange;
6635 }
6636 return Colors.white70;
6637 }
6638}
6639
6640// ---------------------------------------------------------------------------
6641// Object Workspace (admin read-only object inspection)
6642// ---------------------------------------------------------------------------
6643
6644class ObjectWorkspace extends StatefulWidget {
6645 final void Function(String, Widget, [IconData])? onNavigate;
6646 const ObjectWorkspace({super.key, this.onNavigate});
6647
6648 @override
6649 State<ObjectWorkspace> createState() => _ObjectWorkspaceState();
6650}
6651
6652class _ObjectWorkspaceState extends State<ObjectWorkspace> {
6653 String? _selectedObject;
6654 String _tab = 'Overview';
6655 Map<String, List<Map<String, dynamic>>> _objects = {};
6656 bool _loading = true;
6657 String? _loadError;
6658
6659 // Cached data for selected object
6660 Map<String, dynamic>? _selectedObjectInfo;
6661 Map<String, dynamic>? _metadataData;
6662 String? _sourceCode;
6663 Map<String, dynamic>? _sourceSaveResponse;
6664 Map<String, dynamic>? _executeResponse;
6665 Map<String, dynamic>? _stateData;
6666 List<dynamic>? _logsData;
6667 List<dynamic>? _versionsData;
6668 List<dynamic>? _changesData;
6669 bool _tabLoading = false;
6670 bool _sourceSaving = false;
6671 bool _executing = false;
6672
6673 @override
6674 void initState() {
6675 super.initState();
6676 _loadObjects();
6677 }
6678
6679 Future<void> _loadObjects() async {
6680 setState(() => _loading = true);
6681 try {
6682 final list = await ScrollAPI().listAdminObjects();
6683 final Map<String, List<Map<String, dynamic>>> categorized = {};
6684 for (final obj in list) {
6685 final object = _mapFromDynamic(obj);
6686 final id = (object['object_id'] ?? object['id'] ?? object['name'] ?? '')
6687 .toString();
6688 if (id.isEmpty) continue;
6689 final owner = (object['owner'] ?? '').toString();
6690 final path = (object['path'] ?? object['file'] ?? '').toString();
6691
6692 String category;
6693 if (owner == 'system' && id.startsWith('tools_')) {
6694 category = 'Tools';
6695 } else if (owner == 'system' && id.startsWith('views_')) {
6696 category = 'Views';
6697 } else if (owner == 'system' && id.startsWith('triggers_')) {
6698 category = 'Triggers';
6699 } else if (owner == 'system' && id.startsWith('basics_')) {
6700 category = 'Basics';
6701 } else if (owner == 'system' && id.startsWith('apps_')) {
6702 category = 'Apps';
6703 } else if (owner == 'system' && id.startsWith('tutorial_')) {
6704 category = 'Tutorials';
6705 } else if (owner == 'system' && id.startsWith('advanced_')) {
6706 category = 'Advanced';
6707 } else if (owner == 'system' &&
6708 (id.startsWith('config_') ||
6709 id.startsWith('layouts_') ||
6710 id.startsWith('pages_'))) {
6711 category = 'System';
6712 } else if (owner != 'system') {
6713 category = 'My Objects';
6714 } else {
6715 category = 'Other';
6716 }
6717
6718 categorized.putIfAbsent(category, () => []);
6719 categorized[category]!.add({
6720 ...object,
6721 'id': id,
6722 'owner': owner,
6723 'path': path,
6724 });
6725 }
6726 // Sort: My Objects first, then alphabetical
6727 final sorted = Map.fromEntries(
6728 categorized.entries.toList()..sort((a, b) {
6729 if (a.key == 'My Objects') return -1;
6730 if (b.key == 'My Objects') return 1;
6731 return a.key.compareTo(b.key);
6732 }),
6733 );
6734 setState(() {
6735 _objects = sorted;
6736 _loading = false;
6737 });
6738 } catch (e) {
6739 setState(() {
6740 _loading = false;
6741 _loadError = e.toString();
6742 });
6743 }
6744 }
6745
6746 Future<void> _loadTabData(String tab) async {
6747 if (_selectedObject == null) return;
6748 setState(() => _tabLoading = true);
6749 final api = ScrollAPI();
6750 try {
6751 switch (tab) {
6752 case 'Overview':
6753 _metadataData = await api.getAdminObjectMetadata(_selectedObject!);
6754 break;
6755 case 'Source':
6756 _sourceCode = await api.getAdminObjectSource(_selectedObject!);
6757 break;
6758 case 'State':
6759 _stateData = await api.getAdminObjectState(_selectedObject!);
6760 break;
6761 case 'Logs':
6762 _logsData = await api.getAdminObjectLogs(_selectedObject!);
6763 break;
6764 case 'Versions':
6765 _versionsData = await api.getAdminObjectVersions(_selectedObject!);
6766 break;
6767 case 'Activity':
6768 _changesData = await api.getAdminObjectChanges(_selectedObject!);
6769 break;
6770 }
6771 } catch (_) {}
6772 if (mounted) setState(() => _tabLoading = false);
6773 }
6774
6775 void _selectObject(String id) {
6776 setState(() {
6777 _selectedObject = id;
6778 _selectedObjectInfo = _objectInfo(id);
6779 _tab = 'Overview';
6780 _metadataData = null;
6781 _sourceCode = null;
6782 _sourceSaveResponse = null;
6783 _executeResponse = null;
6784 _stateData = null;
6785 _logsData = null;
6786 _versionsData = null;
6787 _changesData = null;
6788 });
6789 _loadTabData('Overview');
6790 }
6791
6792 void _selectTab(String tab) {
6793 setState(() => _tab = tab);
6794 _loadTabData(tab);
6795 }
6796
6797 Future<void> _runSelectedObject() async {
6798 final objectId = _selectedObject;
6799 if (objectId == null || _executing) return;
6800 setState(() {
6801 _executing = true;
6802 _executeResponse = null;
6803 _tab = 'Overview';
6804 });
6805 final result = await ScrollAPI().executeAdminObject(objectId);
6806 if (!mounted) return;
6807 setState(() {
6808 _executing = false;
6809 _executeResponse = result;
6810 });
6811 }
6812
6813 Future<void> _showSourceEditDialog() async {
6814 final objectId = _selectedObject;
6815 if (objectId == null || !ScrollData().sourceWritesEnabled) return;
6816 final source =
6817 _sourceCode ?? await ScrollAPI().getAdminObjectSource(objectId);
6818 if (!mounted) return;
6819 final controller = TextEditingController(text: source ?? '');
6820 final submitted = await showDialog<bool>(
6821 context: context,
6822 builder: (dialogContext) {
6823 return AlertDialog(
6824 title: Text('Edit $objectId Source'),
6825 content: SizedBox(
6826 width: 760,
6827 height: 520,
6828 child: TextField(
6829 controller: controller,
6830 maxLines: null,
6831 expands: true,
6832 decoration: const InputDecoration(
6833 alignLabelWithHint: true,
6834 border: OutlineInputBorder(),
6835 labelText: 'Source code',
6836 ),
6837 style: const TextStyle(
6838 fontFamily: 'monospace',
6839 fontSize: 12,
6840 height: 1.35,
6841 ),
6842 ),
6843 ),
6844 actions: [
6845 TextButton(
6846 onPressed: () => Navigator.of(dialogContext).pop(false),
6847 child: const Text('Cancel'),
6848 ),
6849 FilledButton.icon(
6850 onPressed: () => Navigator.of(dialogContext).pop(true),
6851 icon: const Icon(Icons.save_outlined, size: 16),
6852 label: const Text('Save Source'),
6853 ),
6854 ],
6855 );
6856 },
6857 );
6858 if (submitted != true) {
6859 controller.dispose();
6860 return;
6861 }
6862 final updatedSource = controller.text;
6863 controller.dispose();
6864 setState(() {
6865 _sourceSaving = true;
6866 _sourceSaveResponse = null;
6867 });
6868 final result = await ScrollAPI().updateObjectSource(
6869 objectId,
6870 updatedSource,
6871 );
6872 final refreshedSource = await ScrollAPI().getAdminObjectSource(objectId);
6873 final refreshedMetadata = await ScrollAPI().getAdminObjectMetadata(
6874 objectId,
6875 );
6876 if (!mounted) return;
6877 final saveSucceeded = result != null;
6878 setState(() {
6879 _sourceSaving = false;
6880 _sourceCode =
6881 refreshedSource ?? (saveSucceeded ? updatedSource : _sourceCode);
6882 _metadataData = refreshedMetadata ?? _metadataData;
6883 _sourceSaveResponse = result is Map<String, dynamic>
6884 ? result
6885 : {
6886 if (result != null) 'response': result,
6887 if (result == null)
6888 'error': ScrollAPI().lastError ?? 'Source update failed',
6889 };
6890 });
6891 }
6892
6893 @override
6894 Widget build(BuildContext context) {
6895 return Row(
6896 children: [
6897 // Object sidebar
6898 Container(
6899 width: 220,
6900 color: Theme.of(context).colorScheme.surfaceContainerLow,
6901 child: Column(
6902 crossAxisAlignment: CrossAxisAlignment.start,
6903 children: [
6904 Padding(
6905 padding: const EdgeInsets.fromLTRB(16, 12, 8, 4),
6906 child: Row(
6907 children: [
6908 Text(
6909 'OBJECTS',
6910 style: TextStyle(
6911 fontSize: 10,
6912 fontWeight: FontWeight.bold,
6913 color: Colors.white38,
6914 letterSpacing: 1,
6915 ),
6916 ),
6917 const Spacer(),
6918 Text(
6919 '${_objects.values.fold<int>(0, (s, l) => s + l.length)}',
6920 style: TextStyle(fontSize: 11, color: Colors.white38),
6921 ),
6922 ],
6923 ),
6924 ),
6925 Padding(
6926 padding: const EdgeInsets.symmetric(
6927 horizontal: 12,
6928 vertical: 4,
6929 ),
6930 child: TextField(
6931 decoration: InputDecoration(
6932 hintText: 'Search objects...',
6933 prefixIcon: const Icon(Icons.search, size: 16),
6934 isDense: true,
6935 contentPadding: const EdgeInsets.symmetric(vertical: 6),
6936 border: OutlineInputBorder(
6937 borderRadius: BorderRadius.circular(8),
6938 ),
6939 ),
6940 style: const TextStyle(fontSize: 12),
6941 ),
6942 ),
6943 Expanded(
6944 child: _loading
6945 ? const Center(child: CircularProgressIndicator())
6946 : _loadError != null
6947 ? Center(
6948 child: Column(
6949 mainAxisSize: MainAxisSize.min,
6950 children: [
6951 Icon(Icons.error_outline, color: Colors.red[300]),
6952 const SizedBox(height: 8),
6953 Text(
6954 'Failed to load',
6955 style: TextStyle(
6956 color: Colors.red[300],
6957 fontSize: 12,
6958 ),
6959 ),
6960 TextButton(
6961 onPressed: _loadObjects,
6962 child: const Text('Retry'),
6963 ),
6964 ],
6965 ),
6966 )
6967 : ListView(
6968 padding: const EdgeInsets.symmetric(horizontal: 4),
6969 children: _objects.entries.map((cat) {
6970 final isUser = cat.key == 'My Objects';
6971 return ExpansionTile(
6972 dense: true,
6973 initiallyExpanded: isUser,
6974 tilePadding: const EdgeInsets.symmetric(
6975 horizontal: 12,
6976 ),
6977 leading: Icon(
6978 isUser ? Icons.person : Icons.folder_outlined,
6979 size: 16,
6980 color: isUser
6981 ? Theme.of(context).colorScheme.primary
6982 : Colors.white38,
6983 ),
6984 title: Text(
6985 cat.key,
6986 style: const TextStyle(fontSize: 13),
6987 ),
6988 trailing: Text(
6989 '${cat.value.length}',
6990 style: TextStyle(
6991 fontSize: 11,
6992 color: Colors.white38,
6993 ),
6994 ),
6995 children: cat.value.map((obj) {
6996 final id = obj['id'] as String;
6997 final selected = _selectedObject == id;
6998 return ListTile(
6999 dense: true,
7000 visualDensity: VisualDensity.compact,
7001 selected: selected,
7002 selectedTileColor: Theme.of(
7003 context,
7004 ).colorScheme.primaryContainer.withOpacity(0.2),
7005 contentPadding: const EdgeInsets.only(
7006 left: 40,
7007 right: 8,
7008 ),
7009 leading: Container(
7010 width: 8,
7011 height: 8,
7012 decoration: const BoxDecoration(
7013 color: Colors.green,
7014 shape: BoxShape.circle,
7015 ),
7016 ),
7017 title: Text(
7018 id,
7019 style: TextStyle(
7020 fontSize: 12,
7021 fontFamily: 'monospace',
7022 ),
7023 ),
7024 onTap: () => _selectObject(id),
7025 );
7026 }).toList(),
7027 );
7028 }).toList(),
7029 ),
7030 ),
7031 ],
7032 ),
7033 ),
7034 Container(width: 1, color: Colors.white10),
7035 // Object detail
7036 Expanded(
7037 child: _selectedObject == null
7038 ? Center(
7039 child: Column(
7040 mainAxisSize: MainAxisSize.min,
7041 children: [
7042 Icon(Icons.code, size: 48, color: Colors.white12),
7043 const SizedBox(height: 12),
7044 Text(
7045 'Select an object',
7046 style: TextStyle(color: Colors.white24),
7047 ),
7048 ],
7049 ),
7050 )
7051 : _buildObjectDetail(context),
7052 ),
7053 ],
7054 );
7055 }
7056
7057 Widget _buildObjectDetail(BuildContext context) {
7058 final info = _selectedObjectInfo ?? const <String, dynamic>{};
7059 final isView =
7060 _selectedObject!.startsWith('view_') ||
7061 _selectedObject == 'counter_dashboard' ||
7062 _selectedObject == 'server_status';
7063 final typeLabel = _objectTypeLabel(info, isView);
7064 final typeColor = isView ? Colors.blue : Colors.green;
7065 final versionLabel = _objectVersionLabel(info);
7066
7067 return Column(
7068 children: [
7069 // Object header with tabs
7070 Container(
7071 height: 48,
7072 padding: const EdgeInsets.symmetric(horizontal: 16),
7073 decoration: BoxDecoration(
7074 border: Border(bottom: BorderSide(color: Colors.white10)),
7075 ),
7076 child: Row(
7077 children: [
7078 Container(
7079 width: 10,
7080 height: 10,
7081 decoration: BoxDecoration(
7082 color: Colors.green,
7083 shape: BoxShape.circle,
7084 ),
7085 ),
7086 const SizedBox(width: 8),
7087 Text(
7088 _selectedObject!,
7089 style: TextStyle(
7090 fontWeight: FontWeight.bold,
7091 fontFamily: 'monospace',
7092 fontSize: 14,
7093 ),
7094 ),
7095 const SizedBox(width: 8),
7096 // Object type badge
7097 Container(
7098 padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
7099 decoration: BoxDecoration(
7100 color: typeColor.withOpacity(0.12),
7101 borderRadius: BorderRadius.circular(4),
7102 ),
7103 child: Text(
7104 typeLabel,
7105 style: TextStyle(fontSize: 10, color: typeColor),
7106 ),
7107 ),
7108 if (versionLabel != null) ...[
7109 const SizedBox(width: 4),
7110 Text(
7111 versionLabel,
7112 style: TextStyle(fontSize: 10, color: Colors.white24),
7113 ),
7114 ],
7115 const SizedBox(width: 16),
7116 ..._tabBtn('Overview', _selectTab),
7117 ..._tabBtn('Source', _selectTab),
7118 ..._tabBtn('Activity', _selectTab),
7119 ..._tabBtn('State', _selectTab),
7120 ..._tabBtn('Logs', _selectTab),
7121 ..._tabBtn('Versions', _selectTab),
7122 const Spacer(),
7123 if (isView)
7124 Tooltip(
7125 message:
7126 'Public view routes stay separate from admin execution',
7127 child: TextButton.icon(
7128 onPressed: null,
7129 icon: Icon(Icons.open_in_new, size: 14),
7130 label: Text(
7131 '/v/${_selectedObject!.replaceFirst('view_', '')}/',
7132 style: TextStyle(fontSize: 11),
7133 ),
7134 style: TextButton.styleFrom(foregroundColor: Colors.blue),
7135 ),
7136 ),
7137 Tooltip(
7138 message: 'Run through POST /admin/objects/{object_id}/execute',
7139 child: FilledButton.icon(
7140 onPressed: _executing ? null : _runSelectedObject,
7141 icon: _executing
7142 ? const SizedBox(
7143 width: 14,
7144 height: 14,
7145 child: CircularProgressIndicator(strokeWidth: 2),
7146 )
7147 : const Icon(Icons.play_arrow, size: 16),
7148 label: Text(_executing ? 'Running...' : 'Run'),
7149 ),
7150 ),
7151 const SizedBox(width: 8),
7152 Tooltip(
7153 message: 'Object deletes are disabled on staging',
7154 child: IconButton(
7155 onPressed: null,
7156 icon: const Icon(Icons.delete_outline, size: 18),
7157 tooltip: 'Delete disabled',
7158 visualDensity: VisualDensity.compact,
7159 ),
7160 ),
7161 ],
7162 ),
7163 ),
7164 // Tab content
7165 Expanded(child: _buildTabContent()),
7166 ],
7167 );
7168 }
7169
7170 List<Widget> _tabBtn(String label, void Function(String) onSelect) {
7171 final active = _tab == label;
7172 return [
7173 InkWell(
7174 onTap: () => onSelect(label),
7175 borderRadius: BorderRadius.circular(6),
7176 child: Container(
7177 padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
7178 decoration: BoxDecoration(
7179 color: active
7180 ? Theme.of(context).colorScheme.primary.withOpacity(0.2)
7181 : Colors.transparent,
7182 borderRadius: BorderRadius.circular(6),
7183 ),
7184 child: Text(
7185 label,
7186 style: TextStyle(
7187 fontSize: 11,
7188 color: active
7189 ? Theme.of(context).colorScheme.primary
7190 : Colors.white38,
7191 fontWeight: active ? FontWeight.bold : FontWeight.normal,
7192 ),
7193 ),
7194 ),
7195 ),
7196 const SizedBox(width: 2),
7197 ];
7198 }
7199
7200 Widget _buildTabContent() {
7201 if (_tabLoading) {
7202 return const Center(child: CircularProgressIndicator());
7203 }
7204 return switch (_tab) {
7205 'Overview' => _buildOverviewTab(),
7206 'Source' => _buildCodeTab(),
7207 'Activity' => _buildActivityTab(),
7208 'State' => _buildStateTab(),
7209 'Logs' => _buildLogsTab(),
7210 'Versions' => _buildVersionsTab(),
7211 _ => const SizedBox(),
7212 };
7213 }
7214
7215 Map<String, dynamic>? _objectInfo(String id) {
7216 for (final group in _objects.values) {
7217 for (final object in group) {
7218 if (object['id']?.toString() == id) return object;
7219 }
7220 }
7221 return null;
7222 }
7223
7224 Map<String, dynamic> _mapFromDynamic(dynamic value) {
7225 if (value is Map<String, dynamic>) return value;
7226 if (value is Map) {
7227 return value.map((key, item) => MapEntry(key.toString(), item));
7228 }
7229 return const {};
7230 }
7231
7232 Widget _objectMetric(IconData icon, String label, String value, Color color) {
7233 return Container(
7234 width: 150,
7235 padding: const EdgeInsets.all(12),
7236 decoration: BoxDecoration(
7237 color: color.withValues(alpha: 0.08),
7238 borderRadius: BorderRadius.circular(8),
7239 border: Border.all(color: color.withValues(alpha: 0.2)),
7240 ),
7241 child: Row(
7242 children: [
7243 Icon(icon, size: 18, color: color),
7244 const SizedBox(width: 8),
7245 Expanded(
7246 child: Column(
7247 crossAxisAlignment: CrossAxisAlignment.start,
7248 children: [
7249 Text(
7250 label,
7251 overflow: TextOverflow.ellipsis,
7252 style: TextStyle(fontSize: 11, color: Colors.white38),
7253 ),
7254 Text(
7255 value,
7256 overflow: TextOverflow.ellipsis,
7257 style: const TextStyle(
7258 fontSize: 15,
7259 fontWeight: FontWeight.w600,
7260 ),
7261 ),
7262 ],
7263 ),
7264 ),
7265 ],
7266 ),
7267 );
7268 }
7269
7270 Widget _objectInfoCard(
7271 BuildContext context,
7272 String title,
7273 IconData icon,
7274 Color color,
7275 List<MapEntry<String, dynamic>> rows,
7276 ) {
7277 return Container(
7278 padding: const EdgeInsets.all(14),
7279 decoration: BoxDecoration(
7280 color: Theme.of(context).colorScheme.surfaceContainerLow,
7281 borderRadius: BorderRadius.circular(8),
7282 border: Border.all(color: Colors.white10),
7283 ),
7284 child: Column(
7285 crossAxisAlignment: CrossAxisAlignment.start,
7286 children: [
7287 Row(
7288 children: [
7289 Icon(icon, size: 18, color: color),
7290 const SizedBox(width: 8),
7291 Text(
7292 title,
7293 style: const TextStyle(
7294 fontSize: 13,
7295 fontWeight: FontWeight.w700,
7296 ),
7297 ),
7298 const Spacer(),
7299 _objectChip(rows.isEmpty ? 'EMPTY' : 'READ ONLY', color),
7300 ],
7301 ),
7302 const SizedBox(height: 12),
7303 if (rows.isEmpty)
7304 Text(
7305 'Not reported',
7306 style: TextStyle(fontSize: 12, color: Colors.white38),
7307 )
7308 else
7309 ...rows.map((entry) => _objectInfoRow(entry.key, entry.value)),
7310 ],
7311 ),
7312 );
7313 }
7314
7315 Widget _objectInfoRow(String label, dynamic value) {
7316 return Padding(
7317 padding: const EdgeInsets.only(bottom: 7),
7318 child: Row(
7319 crossAxisAlignment: CrossAxisAlignment.start,
7320 children: [
7321 Expanded(
7322 flex: 5,
7323 child: Text(
7324 _titleCase(label),
7325 overflow: TextOverflow.ellipsis,
7326 style: TextStyle(fontSize: 12, color: Colors.white54),
7327 ),
7328 ),
7329 const SizedBox(width: 10),
7330 Expanded(
7331 flex: 7,
7332 child: Text(
7333 _valueText(value),
7334 maxLines: 3,
7335 overflow: TextOverflow.ellipsis,
7336 textAlign: TextAlign.right,
7337 style: TextStyle(
7338 fontSize: 12,
7339 color: Colors.white70,
7340 fontWeight: FontWeight.w600,
7341 ),
7342 ),
7343 ),
7344 ],
7345 ),
7346 );
7347 }
7348
7349 Widget _objectChip(String text, Color color) {
7350 return Container(
7351 padding: const EdgeInsets.symmetric(horizontal: 7, vertical: 2),
7352 decoration: BoxDecoration(
7353 color: color.withValues(alpha: 0.1),
7354 borderRadius: BorderRadius.circular(4),
7355 border: Border.all(color: color.withValues(alpha: 0.16)),
7356 ),
7357 child: Text(
7358 text,
7359 style: TextStyle(
7360 fontSize: 10,
7361 color: color,
7362 fontWeight: FontWeight.bold,
7363 ),
7364 ),
7365 );
7366 }
7367
7368 Widget _rawObjectPanel(String title, Map<String, dynamic> value) {
7369 return ExpansionTile(
7370 tilePadding: const EdgeInsets.symmetric(horizontal: 4),
7371 title: Text(title, style: TextStyle(fontSize: 12, color: Colors.white54)),
7372 children: [
7373 Container(
7374 width: double.infinity,
7375 padding: const EdgeInsets.all(12),
7376 decoration: BoxDecoration(
7377 color: Colors.black26,
7378 borderRadius: BorderRadius.circular(8),
7379 border: Border.all(color: Colors.white10),
7380 ),
7381 child: SelectableText(
7382 const JsonEncoder.withIndent(' ').convert(value),
7383 style: const TextStyle(
7384 fontFamily: 'monospace',
7385 fontSize: 11,
7386 height: 1.35,
7387 ),
7388 ),
7389 ),
7390 ],
7391 );
7392 }
7393
7394 List<MapEntry<String, dynamic>> _orderedObjectRows(
7395 Map<String, dynamic> values,
7396 ) {
7397 final preferred = [
7398 'id',
7399 'object_id',
7400 'name',
7401 'owner',
7402 'type',
7403 'path',
7404 'version',
7405 'created_at',
7406 'updated_at',
7407 'description',
7408 ];
7409 final rows = <MapEntry<String, dynamic>>[];
7410 final used = <String>{};
7411 for (final key in preferred) {
7412 final value = values[key];
7413 if (_hasValue(value)) {
7414 rows.add(MapEntry(key, value));
7415 used.add(key);
7416 }
7417 }
7418 for (final entry in values.entries) {
7419 if (used.contains(entry.key) || !_hasValue(entry.value)) continue;
7420 rows.add(entry);
7421 }
7422 return rows.take(10).toList();
7423 }
7424
7425 List<MapEntry<String, dynamic>> _objectOverviewRows(
7426 Map<String, dynamic> listInfo,
7427 Map<String, dynamic> metadata,
7428 ) {
7429 return _orderedObjectRows({...listInfo, ...metadata});
7430 }
7431
7432 bool _hasValue(dynamic value) {
7433 if (value == null) return false;
7434 if (value is String) return value.trim().isNotEmpty;
7435 if (value is List) return value.isNotEmpty;
7436 if (value is Map) return value.isNotEmpty;
7437 return true;
7438 }
7439
7440 String _objectTypeLabel(Map<String, dynamic> info, bool isView) {
7441 if (isView) return 'view';
7442 final type = (info['type'] ?? info['kind'] ?? info['object_type'])
7443 ?.toString();
7444 if (type != null && type.isNotEmpty) return type;
7445 return 'object';
7446 }
7447
7448 String? _objectVersionLabel(Map<String, dynamic> info) {
7449 final value =
7450 info['version'] ??
7451 info['current_version'] ??
7452 info['version_id'] ??
7453 info['revision'];
7454 if (value == null || value.toString().isEmpty) return null;
7455 final text = value.toString();
7456 return text.startsWith('v') ? text : 'v$text';
7457 }
7458
7459 String _versionLabel(Map<String, dynamic> version) {
7460 final value =
7461 version['version'] ??
7462 version['id'] ??
7463 version['version_id'] ??
7464 version['revision'] ??
7465 '?';
7466 final text = value.toString();
7467 return text.startsWith('v') ? text : 'v$text';
7468 }
7469
7470 String _valueText(dynamic value) {
7471 if (value == null) return '?';
7472 if (value is bool) return value ? 'yes' : 'no';
7473 if (value is List) return '${value.length} items';
7474 if (value is Map) {
7475 final entries = value.entries.take(4).map((entry) {
7476 return '${_titleCase(entry.key.toString())}: ${_valueText(entry.value)}';
7477 });
7478 return entries.join(', ');
7479 }
7480 return value.toString();
7481 }
7482
7483 String _titleCase(String value) {
7484 return value
7485 .replaceAll('_', ' ')
7486 .replaceAll('-', ' ')
7487 .split(' ')
7488 .where((part) => part.isNotEmpty)
7489 .map((part) => '${part[0].toUpperCase()}${part.substring(1)}')
7490 .join(' ');
7491 }
7492
7493 Widget _buildOverviewTab() {
7494 final listInfo = _selectedObjectInfo ?? const <String, dynamic>{};
7495 final metadata = _metadataData ?? const <String, dynamic>{};
7496 final sourceRows = _objectOverviewRows(listInfo, metadata);
7497 final selectedId = _selectedObject ?? '';
7498 final isView =
7499 selectedId.startsWith('view_') ||
7500 selectedId == 'counter_dashboard' ||
7501 selectedId == 'server_status';
7502
7503 return Container(
7504 color: Colors.black26,
7505 child: SingleChildScrollView(
7506 padding: const EdgeInsets.all(16),
7507 child: Column(
7508 crossAxisAlignment: CrossAxisAlignment.start,
7509 children: [
7510 Wrap(
7511 spacing: 12,
7512 runSpacing: 12,
7513 children: [
7514 _objectMetric(
7515 Icons.badge_outlined,
7516 'Owner',
7517 _valueText(listInfo['owner']),
7518 Colors.blue,
7519 ),
7520 _objectMetric(
7521 Icons.category_outlined,
7522 'Type',
7523 _objectTypeLabel(listInfo, isView),
7524 isView ? Colors.blue : Colors.green,
7525 ),
7526 _objectMetric(
7527 Icons.history_outlined,
7528 'Version',
7529 _objectVersionLabel({...listInfo, ...metadata}) ?? '?',
7530 Colors.purple,
7531 ),
7532 _objectMetric(
7533 Icons.storage_outlined,
7534 'State',
7535 metadata.isEmpty ? 'metadata?' : 'available',
7536 metadata.isEmpty ? Colors.orange : Colors.green,
7537 ),
7538 ],
7539 ),
7540 const SizedBox(height: 16),
7541 LayoutBuilder(
7542 builder: (context, constraints) {
7543 final twoColumns = constraints.maxWidth >= 900;
7544 final cards = [
7545 _objectInfoCard(
7546 context,
7547 'Object List Row',
7548 Icons.inventory_2_outlined,
7549 Colors.blue,
7550 _orderedObjectRows(listInfo),
7551 ),
7552 _objectInfoCard(
7553 context,
7554 'Object Metadata',
7555 Icons.info_outline,
7556 Colors.green,
7557 _orderedObjectRows(metadata),
7558 ),
7559 ];
7560 if (!twoColumns) {
7561 return Column(
7562 children: [
7563 for (final card in cards) ...[
7564 card,
7565 if (card != cards.last) const SizedBox(height: 12),
7566 ],
7567 ],
7568 );
7569 }
7570 return Row(
7571 crossAxisAlignment: CrossAxisAlignment.start,
7572 children: [
7573 Expanded(child: cards.first),
7574 const SizedBox(width: 12),
7575 Expanded(child: cards.last),
7576 ],
7577 );
7578 },
7579 ),
7580 if (sourceRows.isNotEmpty) ...[
7581 const SizedBox(height: 16),
7582 _rawObjectPanel('Raw object detail', {
7583 'list_row': listInfo,
7584 if (metadata.isNotEmpty) 'metadata': metadata,
7585 }),
7586 ],
7587 if (_executeResponse != null) ...[
7588 const SizedBox(height: 16),
7589 _rawObjectPanel('Admin execute response', _executeResponse!),
7590 ],
7591 ],
7592 ),
7593 ),
7594 );
7595 }
7596
7597 Widget _buildCodeTab() {
7598 final sourceWritesEnabled = ScrollData().sourceWritesEnabled;
7599 return Container(
7600 color: Colors.black26,
7601 child: Column(
7602 children: [
7603 Container(
7604 padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
7605 decoration: BoxDecoration(
7606 border: Border(bottom: BorderSide(color: Colors.white10)),
7607 ),
7608 child: Row(
7609 children: [
7610 Text(
7611 'Source Code',
7612 style: TextStyle(fontSize: 11, color: Colors.white38),
7613 ),
7614 const Spacer(),
7615 _objectChip(
7616 sourceWritesEnabled ? 'SOURCE EDITS ENABLED' : 'READ ONLY',
7617 sourceWritesEnabled ? Colors.orange : Colors.green,
7618 ),
7619 const SizedBox(width: 8),
7620 _objectChip(
7621 sourceWritesEnabled
7622 ? 'SOURCE WRITES ENABLED'
7623 : 'SOURCE WRITES OFF',
7624 sourceWritesEnabled ? Colors.orange : Colors.green,
7625 ),
7626 const SizedBox(width: 8),
7627 Tooltip(
7628 message: sourceWritesEnabled
7629 ? 'Save through PUT /admin/objects/{object_id}?source=true'
7630 : 'Source writes are locked: /admin/status.capabilities.source_writes.enabled is false',
7631 child: OutlinedButton.icon(
7632 onPressed:
7633 sourceWritesEnabled &&
7634 !_sourceSaving &&
7635 _sourceCode != null
7636 ? _showSourceEditDialog
7637 : null,
7638 icon: _sourceSaving
7639 ? const SizedBox(
7640 width: 14,
7641 height: 14,
7642 child: CircularProgressIndicator(strokeWidth: 2),
7643 )
7644 : const Icon(Icons.edit, size: 14),
7645 label: Text(
7646 _sourceSaving
7647 ? 'Saving...'
7648 : sourceWritesEnabled
7649 ? 'Edit Source'
7650 : 'Edit locked',
7651 ),
7652 ),
7653 ),
7654 ],
7655 ),
7656 ),
7657 if (_sourceSaveResponse != null)
7658 Builder(
7659 builder: (context) {
7660 final color = _sourceSaveResponse!['error'] == null
7661 ? Colors.green
7662 : Colors.red;
7663 return Container(
7664 width: double.infinity,
7665 margin: const EdgeInsets.fromLTRB(16, 12, 16, 0),
7666 padding: const EdgeInsets.all(10),
7667 decoration: BoxDecoration(
7668 color: color.withValues(alpha: 0.06),
7669 borderRadius: BorderRadius.circular(8),
7670 border: Border.all(color: color.withValues(alpha: 0.18)),
7671 ),
7672 child: SelectableText(
7673 const JsonEncoder.withIndent(
7674 ' ',
7675 ).convert(_sourceSaveResponse),
7676 maxLines: 5,
7677 style: const TextStyle(
7678 fontFamily: 'monospace',
7679 fontSize: 11,
7680 height: 1.3,
7681 ),
7682 ),
7683 );
7684 },
7685 ),
7686 Expanded(
7687 child: Padding(
7688 padding: const EdgeInsets.all(16),
7689 child: SelectableText(
7690 _sourceCode ?? '// Loading source...',
7691 style: TextStyle(
7692 fontFamily: 'monospace',
7693 fontSize: 13,
7694 color: _sourceCode != null
7695 ? Colors.green[300]
7696 : Colors.white24,
7697 ),
7698 ),
7699 ),
7700 ),
7701 ],
7702 ),
7703 );
7704 }
7705
7706 Widget _buildActivityTab() {
7707 final changes = _changesData ?? const [];
7708 return Container(
7709 color: Colors.black26,
7710 padding: const EdgeInsets.all(16),
7711 child: Column(
7712 crossAxisAlignment: CrossAxisAlignment.start,
7713 children: [
7714 Row(
7715 children: [
7716 Text(
7717 'Object Activity',
7718 style: TextStyle(fontSize: 13, fontWeight: FontWeight.bold),
7719 ),
7720 const Spacer(),
7721 _objectChip('READ ONLY', Colors.green),
7722 ],
7723 ),
7724 const SizedBox(height: 16),
7725 if (changes.isEmpty)
7726 Expanded(
7727 child: Center(
7728 child: Text(
7729 'No object activity',
7730 style: TextStyle(color: Colors.white24),
7731 ),
7732 ),
7733 )
7734 else
7735 Expanded(
7736 child: ListView.builder(
7737 itemCount: changes.length + 1,
7738 itemBuilder: (context, i) {
7739 if (i == changes.length) {
7740 return _rawObjectPanel('Raw object changes', {
7741 'changes': changes,
7742 });
7743 }
7744 final raw = changes[i];
7745 final change = _mapFromDynamic(raw);
7746 String pick(List<String> keys, [String fallback = '']) {
7747 for (final key in keys) {
7748 final value = change[key]?.toString();
7749 if (value != null && value.trim().isNotEmpty) {
7750 return value;
7751 }
7752 }
7753 return fallback;
7754 }
7755
7756 String valueText(dynamic value) {
7757 if (value == null) return '';
7758 if (value is Map || value is List) {
7759 return const JsonEncoder.withIndent(' ').convert(value);
7760 }
7761 return value.toString();
7762 }
7763
7764 final kind = pick(['kind'], 'source');
7765 final action = pick([
7766 'action',
7767 'type',
7768 'event_type',
7769 'change_type',
7770 ], '${kind}_change');
7771 final timestamp = pick([
7772 'timestamp',
7773 'created_at',
7774 'changed_at',
7775 'time',
7776 ]);
7777 final actor = pick([
7778 'actor',
7779 'author',
7780 'user',
7781 'user_id',
7782 'principal',
7783 ], 'unknown');
7784 final message = pick([
7785 'summary',
7786 'message',
7787 'description',
7788 'note',
7789 ], action);
7790 final target = _mapFromDynamic(change['target']);
7791 final targetParts = <String>[
7792 for (final key in const [
7793 'object_id',
7794 'collection',
7795 'record_id',
7796 'package_id',
7797 'file',
7798 ])
7799 if (target[key]?.toString().trim().isNotEmpty == true)
7800 '${key.replaceAll('_id', '')}: ${target[key]}',
7801 ];
7802 final targetText = targetParts.isEmpty
7803 ? valueText(change['target'])
7804 : targetParts.join(' | ');
7805 final version = pick([
7806 'version_id',
7807 'to_version_id',
7808 'version',
7809 'revision',
7810 ]);
7811 final fromVersion = pick([
7812 'from_version_id',
7813 'from_version',
7814 'previous_version_id',
7815 ]);
7816 final correlation = pick(['correlation_id', 'request_id']);
7817 String short(String value, int limit) {
7818 if (value.length <= limit) return value;
7819 return '${value.substring(0, limit)}...';
7820 }
7821
7822 final normalizedAction = action.toLowerCase();
7823 final normalizedKind = kind.toLowerCase();
7824 final color = normalizedAction.contains('rollback')
7825 ? Colors.orange
7826 : normalizedAction.contains('delete')
7827 ? Colors.red
7828 : normalizedKind == 'file'
7829 ? Colors.teal
7830 : normalizedKind == 'record'
7831 ? Colors.blue
7832 : normalizedKind == 'package'
7833 ? Colors.amber
7834 : Colors.green;
7835
7836 return Container(
7837 margin: const EdgeInsets.only(bottom: 8),
7838 padding: const EdgeInsets.all(12),
7839 decoration: BoxDecoration(
7840 color: color.withValues(alpha: 0.05),
7841 borderRadius: BorderRadius.circular(8),
7842 border: Border.all(color: Colors.white10),
7843 ),
7844 child: Column(
7845 crossAxisAlignment: CrossAxisAlignment.start,
7846 children: [
7847 Row(
7848 children: [
7849 _objectChip(kind.toUpperCase(), color),
7850 const SizedBox(width: 6),
7851 _objectChip(action, color),
7852 const SizedBox(width: 10),
7853 Expanded(
7854 child: Text(
7855 message,
7856 maxLines: 2,
7857 overflow: TextOverflow.ellipsis,
7858 style: TextStyle(
7859 fontSize: 13,
7860 color: Colors.white70,
7861 fontWeight: FontWeight.w600,
7862 ),
7863 ),
7864 ),
7865 ],
7866 ),
7867 const SizedBox(height: 8),
7868 Wrap(
7869 spacing: 12,
7870 runSpacing: 6,
7871 children: [
7872 _objectChip(
7873 'actor: ${short(actor, 32)}',
7874 Colors.blue,
7875 ),
7876 if (timestamp.isNotEmpty)
7877 _objectChip(short(timestamp, 32), Colors.white54),
7878 if (version.isNotEmpty)
7879 _objectChip(
7880 'version: ${short(version, 24)}',
7881 Colors.purple,
7882 ),
7883 if (targetText.isNotEmpty)
7884 _objectChip(short(targetText, 42), Colors.teal),
7885 if (fromVersion.isNotEmpty)
7886 _objectChip(
7887 'from: ${short(fromVersion, 24)}',
7888 Colors.orange,
7889 ),
7890 if (correlation.isNotEmpty)
7891 _objectChip(
7892 'corr: ${short(correlation, 18)}',
7893 Colors.white54,
7894 ),
7895 ],
7896 ),
7897 ],
7898 ),
7899 );
7900 },
7901 ),
7902 ),
7903 ],
7904 ),
7905 );
7906 }
7907
7908 Widget _buildStateTab() {
7909 return Container(
7910 color: Colors.black26,
7911 child: Column(
7912 children: [
7913 Container(
7914 padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
7915 decoration: BoxDecoration(
7916 border: Border(bottom: BorderSide(color: Colors.white10)),
7917 ),
7918 child: Row(
7919 children: [
7920 Text(
7921 'State (TSV)',
7922 style: TextStyle(fontSize: 11, color: Colors.white38),
7923 ),
7924 const Spacer(),
7925 _objectChip('READ ONLY', Colors.green),
7926 ],
7927 ),
7928 ),
7929 Expanded(
7930 child: _stateData == null || _stateData!.isEmpty
7931 ? Center(
7932 child: Text(
7933 'No state data',
7934 style: TextStyle(color: Colors.white24),
7935 ),
7936 )
7937 : SingleChildScrollView(
7938 padding: const EdgeInsets.all(16),
7939 child: DataTable(
7940 headingRowHeight: 32,
7941 dataRowMinHeight: 32,
7942 dataRowMaxHeight: 32,
7943 columnSpacing: 32,
7944 headingTextStyle: TextStyle(
7945 fontSize: 12,
7946 fontWeight: FontWeight.bold,
7947 color: Colors.white54,
7948 ),
7949 dataTextStyle: TextStyle(
7950 fontSize: 13,
7951 fontFamily: 'monospace',
7952 ),
7953 columns: const [
7954 DataColumn(label: Text('KEY')),
7955 DataColumn(label: Text('VALUE')),
7956 ],
7957 rows: _stateData!.entries.map((kv) {
7958 final isMeta = kv.key.startsWith('_');
7959 final val = kv.value?.toString() ?? '';
7960 return DataRow(
7961 cells: [
7962 DataCell(
7963 Text(
7964 kv.key,
7965 style: TextStyle(
7966 color: isMeta
7967 ? Colors.blue[200]
7968 : Colors.white70,
7969 ),
7970 ),
7971 ),
7972 DataCell(
7973 Text(
7974 val.length > 100
7975 ? '${val.substring(0, 100)}...'
7976 : val,
7977 style: TextStyle(
7978 color: isMeta
7979 ? Colors.white38
7980 : Colors.white70,
7981 ),
7982 ),
7983 ),
7984 ],
7985 );
7986 }).toList(),
7987 ),
7988 ),
7989 ),
7990 ],
7991 ),
7992 );
7993 }
7994
7995 Widget _buildLogsTab() {
7996 return Container(
7997 color: Colors.black26,
7998 padding: const EdgeInsets.all(12),
7999 child: _logsData == null || _logsData!.isEmpty
8000 ? Center(
8001 child: Text('No logs', style: TextStyle(color: Colors.white24)),
8002 )
8003 : ListView.builder(
8004 itemCount: _logsData!.length,
8005 itemBuilder: (context, i) {
8006 final log = _logsData![i];
8007 final time =
8008 log['timestamp']?.toString() ??
8009 log['time']?.toString() ??
8010 '';
8011 final level = log['level']?.toString() ?? 'INFO';
8012 final msg = log['message']?.toString() ?? log.toString();
8013 return _objLog(time, level, msg);
8014 },
8015 ),
8016 );
8017 }
8018
8019 Widget _buildVersionsTab() {
8020 final versions = _versionsData ?? const [];
8021 final currentVersion = _objectVersionLabel({
8022 ...?_selectedObjectInfo,
8023 ...?_metadataData,
8024 });
8025 return Container(
8026 color: Colors.black26,
8027 padding: const EdgeInsets.all(16),
8028 child: Column(
8029 crossAxisAlignment: CrossAxisAlignment.start,
8030 children: [
8031 Row(
8032 children: [
8033 Text(
8034 'Version History',
8035 style: TextStyle(fontSize: 13, fontWeight: FontWeight.bold),
8036 ),
8037 const Spacer(),
8038 _objectChip('READ ONLY', Colors.green),
8039 ],
8040 ),
8041 const SizedBox(height: 16),
8042 if (versions.isEmpty)
8043 Expanded(
8044 child: Center(
8045 child: Text(
8046 'No version data',
8047 style: TextStyle(color: Colors.white24),
8048 ),
8049 ),
8050 )
8051 else
8052 Expanded(
8053 child: ListView.builder(
8054 itemCount: versions.length,
8055 itemBuilder: (context, i) {
8056 final raw = versions[i];
8057 final version = _mapFromDynamic(raw);
8058 final label = _versionLabel(version);
8059 final isCurrent =
8060 currentVersion != null && label == currentVersion;
8061 final created =
8062 version['created_at']?.toString() ??
8063 version['date']?.toString() ??
8064 version['timestamp']?.toString() ??
8065 '';
8066 final author =
8067 version['author']?.toString() ??
8068 version['actor']?.toString() ??
8069 version['user']?.toString() ??
8070 'unknown';
8071 final message =
8072 version['message']?.toString() ??
8073 version['description']?.toString() ??
8074 version['change']?.toString() ??
8075 '';
8076 return Container(
8077 margin: const EdgeInsets.only(bottom: 8),
8078 padding: const EdgeInsets.all(12),
8079 decoration: BoxDecoration(
8080 color: isCurrent
8081 ? Colors.green.withOpacity(0.05)
8082 : Colors.transparent,
8083 borderRadius: BorderRadius.circular(8),
8084 border: Border.all(
8085 color: isCurrent
8086 ? Colors.green.withOpacity(0.2)
8087 : Colors.white10,
8088 ),
8089 ),
8090 child: Row(
8091 children: [
8092 Container(
8093 padding: const EdgeInsets.symmetric(
8094 horizontal: 8,
8095 vertical: 2,
8096 ),
8097 decoration: BoxDecoration(
8098 color: isCurrent
8099 ? Colors.green.withOpacity(0.15)
8100 : Colors.white.withOpacity(0.05),
8101 borderRadius: BorderRadius.circular(4),
8102 ),
8103 child: Text(
8104 label,
8105 style: TextStyle(
8106 fontSize: 12,
8107 fontWeight: FontWeight.bold,
8108 color: isCurrent ? Colors.green : Colors.white54,
8109 fontFamily: 'monospace',
8110 ),
8111 ),
8112 ),
8113 const SizedBox(width: 12),
8114 Text(
8115 created,
8116 style: TextStyle(fontSize: 12, color: Colors.white38),
8117 ),
8118 const SizedBox(width: 12),
8119 Text(
8120 author,
8121 style: TextStyle(fontSize: 12, color: Colors.white54),
8122 ),
8123 const SizedBox(width: 12),
8124 Expanded(
8125 child: Text(
8126 message,
8127 maxLines: 2,
8128 overflow: TextOverflow.ellipsis,
8129 style: TextStyle(
8130 fontSize: 12,
8131 color: Colors.white54,
8132 ),
8133 ),
8134 ),
8135 if (isCurrent) _objectChip('CURRENT', Colors.green),
8136 ],
8137 ),
8138 );
8139 },
8140 ),
8141 ),
8142 ],
8143 ),
8144 );
8145 }
8146
8147 Widget _objLog(String time, String level, String msg) {
8148 final color = switch (level) {
8149 'INFO' => Colors.green,
8150 'DEBUG' => Colors.grey,
8151 'ROUTE' => Colors.blue,
8152 'ERROR' => Colors.red,
8153 _ => Colors.white54,
8154 };
8155 return Padding(
8156 padding: const EdgeInsets.only(bottom: 4),
8157 child: Text.rich(
8158 TextSpan(
8159 children: [
8160 TextSpan(
8161 text: '$time ',
8162 style: TextStyle(
8163 color: Colors.white30,
8164 fontFamily: 'monospace',
8165 fontSize: 12,
8166 ),
8167 ),
8168 TextSpan(
8169 text: '[$level] ',
8170 style: TextStyle(
8171 color: color,
8172 fontFamily: 'monospace',
8173 fontSize: 12,
8174 fontWeight: FontWeight.bold,
8175 ),
8176 ),
8177 TextSpan(
8178 text: msg,
8179 style: TextStyle(
8180 color: Colors.white70,
8181 fontFamily: 'monospace',
8182 fontSize: 12,
8183 ),
8184 ),
8185 ],
8186 ),
8187 ),
8188 );
8189 }
8190}
8191
8192// ---------------------------------------------------------------------------
8193// Collection Browser (admin)
8194// ---------------------------------------------------------------------------
8195
8196class CollectionBrowser extends StatefulWidget {
8197 const CollectionBrowser({super.key});
8198
8199 @override
8200 State<CollectionBrowser> createState() => _CollectionBrowserState();
8201}
8202
8203class _CollectionBrowserState extends State<CollectionBrowser> {
8204 List<Map<String, dynamic>> _collections = [];
8205 String? _selectedCollection;
8206 Map<String, dynamic>? _collectionDetail;
8207 Map<String, dynamic>? _collectionSchema;
8208 List<dynamic> _records = [];
8209 List<dynamic> _collectionChanges = [];
8210 Map<String, dynamic>? _selectedRecord;
8211 List<dynamic> _recordChanges = [];
8212 String _tab = 'Records';
8213 bool _loading = true;
8214 bool _detailLoading = false;
8215 bool _recordLoading = false;
8216 bool _writing = false;
8217 Map<String, dynamic>? _writeResponse;
8218 String? _error;
8219 String? _rtCollection;
8220 VoidCallback? _rtDispose;
8221
8222 @override
8223 void initState() {
8224 super.initState();
8225 _loadCollections();
8226 }
8227
8228 @override
8229 void dispose() {
8230 _rtDispose?.call();
8231 super.dispose();
8232 }
8233
8234 /// Keep one realtime subscription tracking the visible collection. On a
8235 /// record event, quietly refetch the record list + changes without
8236 /// blanking the panel or losing the selected record.
8237 void _bindRealtime(String? collection) {
8238 if (collection == _rtCollection) return;
8239 _rtDispose?.call();
8240 _rtCollection = collection;
8241 _rtDispose = collection == null
8242 ? null
8243 : ScrollRealtime().bind(collection, _refetchRecordsQuietly);
8244 }
8245
8246 Future<void> _refetchRecordsQuietly() async {
8247 final collection = _selectedCollection;
8248 if (collection == null || !mounted) return;
8249 final results = await Future.wait<dynamic>([
8250 ScrollAPI().listAdminCollectionRecords(collection, limit: 100),
8251 ScrollAPI().listAdminCollectionChanges(collection, limit: 100),
8252 ]);
8253 if (!mounted || collection != _selectedCollection) return;
8254 setState(() {
8255 _records = results[0] is List ? results[0] as List : _records;
8256 _collectionChanges = results[1] is List
8257 ? results[1] as List
8258 : _collectionChanges;
8259 });
8260 }
8261
8262 Future<void> _loadCollections() async {
8263 setState(() {
8264 _loading = true;
8265 _error = null;
8266 });
8267 try {
8268 final raw = await ScrollAPI().listAdminCollections();
8269 final collections = raw
8270 .map(_mapFromDynamic)
8271 .where((collection) => _collectionName(collection).isNotEmpty)
8272 .toList();
8273 final current = _selectedCollection;
8274 final selected =
8275 collections.any((item) => _collectionName(item) == current)
8276 ? current
8277 : (collections.isNotEmpty
8278 ? _collectionName(collections.first)
8279 : null);
8280 if (!mounted) return;
8281 setState(() {
8282 _collections = collections;
8283 _selectedCollection = selected;
8284 _loading = false;
8285 });
8286 _bindRealtime(selected);
8287 if (selected != null) await _loadCollection(selected);
8288 } catch (e) {
8289 if (!mounted) return;
8290 setState(() {
8291 _loading = false;
8292 _error = e.toString();
8293 });
8294 }
8295 }
8296
8297 Future<void> _loadCollection(String collection) async {
8298 setState(() {
8299 _detailLoading = true;
8300 _collectionDetail = null;
8301 _collectionSchema = null;
8302 _records = [];
8303 _collectionChanges = [];
8304 _selectedRecord = null;
8305 _recordChanges = [];
8306 });
8307 final api = ScrollAPI();
8308 final responses = await Future.wait<dynamic>([
8309 api.getAdminCollection(collection),
8310 api.listAdminCollectionRecords(collection, limit: 100),
8311 api.listAdminCollectionChanges(collection, limit: 100),
8312 api.getAdminSchema(collection),
8313 ]);
8314 if (!mounted) return;
8315 setState(() {
8316 _collectionDetail = _mapOrNull(responses[0]);
8317 _records = responses[1] is List ? responses[1] as List : const [];
8318 _collectionChanges = responses[2] is List
8319 ? responses[2] as List
8320 : const [];
8321 _collectionSchema = _mapOrNull(responses[3]);
8322 _detailLoading = false;
8323 });
8324 }
8325
8326 Future<void> _selectCollection(String collection) async {
8327 setState(() {
8328 _selectedCollection = collection;
8329 _tab = 'Records';
8330 });
8331 _bindRealtime(collection);
8332 await _loadCollection(collection);
8333 }
8334
8335 Future<void> _selectRecord(dynamic value) async {
8336 final record = _mapFromDynamic(value);
8337 final collection = _selectedCollection;
8338 final id = _recordId(record);
8339 setState(() {
8340 _selectedRecord = record;
8341 _recordChanges = [];
8342 _recordLoading = id.isNotEmpty;
8343 });
8344 if (collection == null || id.isEmpty) {
8345 setState(() => _recordLoading = false);
8346 return;
8347 }
8348 final api = ScrollAPI();
8349 final responses = await Future.wait<dynamic>([
8350 api.getAdminCollectionRecord(collection, id),
8351 api.listAdminCollectionRecordChanges(collection, id, limit: 100),
8352 ]);
8353 if (!mounted) return;
8354 final detail = _mapOrNull(responses[0]);
8355 setState(() {
8356 _selectedRecord = detail == null ? record : {...record, ...detail};
8357 _recordChanges = responses[1] is List ? responses[1] as List : const [];
8358 _recordLoading = false;
8359 });
8360 }
8361
8362 Future<Map<String, dynamic>?> _promptRecordJson({
8363 required String title,
8364 required String initialJson,
8365 String confirmLabel = 'Save Record',
8366 }) async {
8367 final controller = TextEditingController(text: initialJson);
8368 String? parseError;
8369 final submitted = await showDialog<Map<String, dynamic>>(
8370 context: context,
8371 builder: (dialogContext) {
8372 return StatefulBuilder(
8373 builder: (dialogContext, setDialogState) {
8374 return AlertDialog(
8375 title: Text(title),
8376 content: SizedBox(
8377 width: 640,
8378 height: 420,
8379 child: Column(
8380 children: [
8381 Expanded(
8382 child: TextField(
8383 controller: controller,
8384 maxLines: null,
8385 expands: true,
8386 decoration: const InputDecoration(
8387 alignLabelWithHint: true,
8388 border: OutlineInputBorder(),
8389 labelText: 'Record JSON',
8390 ),
8391 style: const TextStyle(
8392 fontFamily: 'monospace',
8393 fontSize: 12,
8394 height: 1.35,
8395 ),
8396 ),
8397 ),
8398 if (parseError != null) ...[
8399 const SizedBox(height: 8),
8400 Align(
8401 alignment: Alignment.centerLeft,
8402 child: Text(
8403 parseError!,
8404 style: TextStyle(
8405 fontSize: 12,
8406 color: Colors.red[300],
8407 ),
8408 ),
8409 ),
8410 ],
8411 ],
8412 ),
8413 ),
8414 actions: [
8415 TextButton(
8416 onPressed: () => Navigator.of(dialogContext).pop(null),
8417 child: const Text('Cancel'),
8418 ),
8419 FilledButton.icon(
8420 onPressed: () {
8421 try {
8422 final decoded = jsonDecode(controller.text) as Object?;
8423 if (decoded is! Map<String, dynamic>) {
8424 setDialogState(
8425 () => parseError = 'Record JSON must be an object',
8426 );
8427 return;
8428 }
8429 Navigator.of(dialogContext).pop(decoded);
8430 } catch (e) {
8431 setDialogState(() => parseError = 'Invalid JSON: $e');
8432 }
8433 },
8434 icon: const Icon(Icons.save_outlined, size: 16),
8435 label: Text(confirmLabel),
8436 ),
8437 ],
8438 );
8439 },
8440 );
8441 },
8442 );
8443 controller.dispose();
8444 return submitted;
8445 }
8446
8447 Future<bool> _runRecordWrite(
8448 Future<Map<String, dynamic>> Function() write,
8449 ) async {
8450 final collection = _selectedCollection;
8451 if (collection == null) return false;
8452 setState(() {
8453 _writing = true;
8454 _writeResponse = null;
8455 });
8456 final result = await write();
8457 if (!mounted) return false;
8458 setState(() {
8459 _writing = false;
8460 _writeResponse = result;
8461 });
8462 await _loadCollection(collection);
8463 final status = result['status'];
8464 return status is int && status >= 200 && status < 300;
8465 }
8466
8467 SchemaFormSpec get _schemaSpec =>
8468 SchemaFormSpec.fromSchema(_collectionSchema);
8469
8470 Future<void> _showCreateRecordDialog() async {
8471 final collection = _selectedCollection;
8472 if (collection == null) return;
8473 Map<String, dynamic>? record;
8474 final spec = _schemaSpec;
8475 if (spec.hasFields) {
8476 final result = await showSchemaRecordFormDialog(
8477 context,
8478 collection: collection,
8479 spec: spec,
8480 );
8481 if (!mounted) return;
8482 if (result == null) return;
8483 if (result is Map<String, dynamic>) record = result;
8484 // schemaFormRawJsonRequested falls through to the JSON editor.
8485 }
8486 record ??= await _promptRecordJson(
8487 title: 'New $collection record',
8488 initialJson: '{\n "id": ""\n}',
8489 confirmLabel: 'Create Record',
8490 );
8491 if (record == null || !mounted) return;
8492 final written = record;
8493 final ok = await _runRecordWrite(
8494 () => ScrollAPI().createAdminCollectionRecord(collection, written),
8495 );
8496 final id = _recordId(written);
8497 if (ok && id.isNotEmpty && mounted) await _selectRecord({'id': id});
8498 }
8499
8500 Future<void> _showEditRecordDialog() async {
8501 final collection = _selectedCollection;
8502 final record = _selectedRecord;
8503 if (collection == null || record == null) return;
8504 final id = _recordId(record);
8505 if (id.isEmpty) return;
8506 Map<String, dynamic>? updated;
8507 final spec = _schemaSpec;
8508 if (spec.hasFields) {
8509 final result = await showSchemaRecordFormDialog(
8510 context,
8511 collection: collection,
8512 spec: spec,
8513 initial: record,
8514 );
8515 if (!mounted) return;
8516 if (result == null) return;
8517 if (result is Map<String, dynamic>) updated = result;
8518 }
8519 updated ??= await _promptRecordJson(
8520 title: 'Edit $collection/$id',
8521 initialJson: const JsonEncoder.withIndent(' ').convert(record),
8522 );
8523 if (updated == null || !mounted) return;
8524 final written = updated;
8525 final ok = await _runRecordWrite(
8526 () => ScrollAPI().updateAdminCollectionRecord(collection, id, written),
8527 );
8528 if (ok && mounted) await _selectRecord({'id': id});
8529 }
8530
8531 Future<void> _confirmDeleteRecord() async {
8532 final collection = _selectedCollection;
8533 final record = _selectedRecord;
8534 if (collection == null || record == null) return;
8535 final id = _recordId(record);
8536 if (id.isEmpty) return;
8537 final confirmed = await showDialog<bool>(
8538 context: context,
8539 builder: (dialogContext) {
8540 return AlertDialog(
8541 title: const Text('Delete record?'),
8542 content: Text(
8543 'DELETE /admin/collections/$collection/records/$id\n\n'
8544 'The delete is recorded in the collection change history.',
8545 ),
8546 actions: [
8547 TextButton(
8548 onPressed: () => Navigator.of(dialogContext).pop(false),
8549 child: const Text('Cancel'),
8550 ),
8551 FilledButton.icon(
8552 style: FilledButton.styleFrom(backgroundColor: Colors.red[700]),
8553 onPressed: () => Navigator.of(dialogContext).pop(true),
8554 icon: const Icon(Icons.delete_outline, size: 16),
8555 label: const Text('Delete Record'),
8556 ),
8557 ],
8558 );
8559 },
8560 );
8561 if (confirmed != true || !mounted) return;
8562 await _runRecordWrite(
8563 () => ScrollAPI().deleteAdminCollectionRecord(collection, id),
8564 );
8565 }
8566
8567 @override
8568 Widget build(BuildContext context) {
8569 return Row(
8570 children: [
8571 Container(
8572 width: 250,
8573 color: Theme.of(context).colorScheme.surfaceContainerLow,
8574 child: Column(
8575 children: [
8576 Padding(
8577 padding: const EdgeInsets.fromLTRB(16, 12, 8, 8),
8578 child: Row(
8579 children: [
8580 Text(
8581 'COLLECTIONS',
8582 style: TextStyle(
8583 fontSize: 10,
8584 fontWeight: FontWeight.bold,
8585 color: Colors.white38,
8586 letterSpacing: 1,
8587 ),
8588 ),
8589 const Spacer(),
8590 Text(
8591 '${_collections.length}',
8592 style: TextStyle(fontSize: 11, color: Colors.white38),
8593 ),
8594 IconButton(
8595 onPressed: _loading ? null : _loadCollections,
8596 icon: const Icon(Icons.refresh, size: 16),
8597 tooltip: 'Refresh',
8598 visualDensity: VisualDensity.compact,
8599 ),
8600 ],
8601 ),
8602 ),
8603 Expanded(
8604 child: _loading
8605 ? const Center(child: CircularProgressIndicator())
8606 : _error != null
8607 ? Center(
8608 child: Padding(
8609 padding: const EdgeInsets.all(16),
8610 child: Text(
8611 'Failed to load collections',
8612 style: TextStyle(color: Colors.red[300]),
8613 ),
8614 ),
8615 )
8616 : ListView.builder(
8617 padding: const EdgeInsets.symmetric(horizontal: 4),
8618 itemCount: _collections.length,
8619 itemBuilder: (context, index) {
8620 final collection = _collections[index];
8621 final name = _collectionName(collection);
8622 final selected = name == _selectedCollection;
8623 final hasRecords = _hasRecords(collection);
8624 return ListTile(
8625 dense: true,
8626 selected: selected,
8627 selectedTileColor: Theme.of(context)
8628 .colorScheme
8629 .primaryContainer
8630 .withValues(alpha: 0.2),
8631 leading: Icon(
8632 hasRecords
8633 ? Icons.storage_outlined
8634 : Icons.code_outlined,
8635 size: 18,
8636 color: selected
8637 ? Theme.of(context).colorScheme.primary
8638 : Colors.white38,
8639 ),
8640 title: Text(
8641 name,
8642 overflow: TextOverflow.ellipsis,
8643 style: const TextStyle(
8644 fontSize: 13,
8645 fontFamily: 'monospace',
8646 ),
8647 ),
8648 trailing: Text(
8649 hasRecords
8650 ? _collectionCount(collection)
8651 : '${collection['object_count'] ?? '?'} obj',
8652 style: TextStyle(
8653 fontSize: 11,
8654 color: Colors.white38,
8655 ),
8656 ),
8657 onTap: () => _selectCollection(name),
8658 );
8659 },
8660 ),
8661 ),
8662 ],
8663 ),
8664 ),
8665 Container(width: 1, color: Colors.white10),
8666 Expanded(child: _buildDetail(context)),
8667 ],
8668 );
8669 }
8670
8671 Widget _buildDetail(BuildContext context) {
8672 final collection = _selectedCollection;
8673 if (collection == null) {
8674 return Center(
8675 child: Text('No collections', style: TextStyle(color: Colors.white38)),
8676 );
8677 }
8678 return Column(
8679 children: [
8680 Container(
8681 height: 52,
8682 padding: const EdgeInsets.symmetric(horizontal: 16),
8683 decoration: BoxDecoration(
8684 border: Border(bottom: BorderSide(color: Colors.white10)),
8685 ),
8686 child: Row(
8687 children: [
8688 Icon(Icons.storage_outlined, size: 18, color: Colors.teal),
8689 const SizedBox(width: 8),
8690 Text(
8691 collection,
8692 style: const TextStyle(
8693 fontSize: 15,
8694 fontWeight: FontWeight.bold,
8695 fontFamily: 'monospace',
8696 ),
8697 ),
8698 const SizedBox(width: 10),
8699 if (_selectedHasRecords)
8700 _chip('RECORD WRITES ADMIN', Colors.orange)
8701 else
8702 _chip('OBJECT NAMESPACE', Colors.blue),
8703 const SizedBox(width: 18),
8704 ..._tabButton('Overview'),
8705 ..._tabButton('Records'),
8706 ..._tabButton('Activity'),
8707 const Spacer(),
8708 Tooltip(
8709 message: _selectedHasRecords
8710 ? 'Create through POST /admin/collections/$collection/records'
8711 : 'Object namespaces have no record storage — browse these objects on the Objects screen',
8712 child: FilledButton.icon(
8713 onPressed: _writing || !_selectedHasRecords
8714 ? null
8715 : _showCreateRecordDialog,
8716 icon: _writing
8717 ? const SizedBox(
8718 width: 14,
8719 height: 14,
8720 child: CircularProgressIndicator(strokeWidth: 2),
8721 )
8722 : const Icon(Icons.add, size: 16),
8723 label: const Text('New Record'),
8724 ),
8725 ),
8726 ],
8727 ),
8728 ),
8729 if (_writeResponse != null) _writeResponsePanel(),
8730 Expanded(
8731 child: _detailLoading
8732 ? const Center(child: CircularProgressIndicator())
8733 : switch (_tab) {
8734 'Overview' => _buildOverviewTab(context),
8735 'Activity' => _buildActivityTab(context),
8736 _ => _buildRecordsTab(context),
8737 },
8738 ),
8739 ],
8740 );
8741 }
8742
8743 Widget _writeResponsePanel() {
8744 final response = _writeResponse ?? const <String, dynamic>{};
8745 final status = response['status'];
8746 final ok = status is int && status >= 200 && status < 300;
8747 final color = ok ? Colors.green : Colors.red;
8748 return Container(
8749 width: double.infinity,
8750 margin: const EdgeInsets.fromLTRB(16, 12, 16, 0),
8751 padding: const EdgeInsets.all(10),
8752 decoration: BoxDecoration(
8753 color: color.withValues(alpha: 0.06),
8754 borderRadius: BorderRadius.circular(8),
8755 border: Border.all(color: color.withValues(alpha: 0.18)),
8756 ),
8757 child: Row(
8758 crossAxisAlignment: CrossAxisAlignment.start,
8759 children: [
8760 Expanded(
8761 child: SelectableText(
8762 const JsonEncoder.withIndent(' ').convert(response),
8763 maxLines: 6,
8764 style: const TextStyle(
8765 fontFamily: 'monospace',
8766 fontSize: 11,
8767 height: 1.3,
8768 ),
8769 ),
8770 ),
8771 IconButton(
8772 onPressed: () => setState(() => _writeResponse = null),
8773 icon: const Icon(Icons.close, size: 14),
8774 tooltip: 'Dismiss',
8775 visualDensity: VisualDensity.compact,
8776 ),
8777 ],
8778 ),
8779 );
8780 }
8781
8782 List<Widget> _tabButton(String label) {
8783 final active = _tab == label;
8784 return [
8785 InkWell(
8786 onTap: () => setState(() => _tab = label),
8787 borderRadius: BorderRadius.circular(6),
8788 child: Container(
8789 padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
8790 decoration: BoxDecoration(
8791 color: active
8792 ? Theme.of(context).colorScheme.primary.withValues(alpha: 0.2)
8793 : Colors.transparent,
8794 borderRadius: BorderRadius.circular(6),
8795 ),
8796 child: Text(
8797 label,
8798 style: TextStyle(
8799 fontSize: 11,
8800 color: active
8801 ? Theme.of(context).colorScheme.primary
8802 : Colors.white38,
8803 fontWeight: active ? FontWeight.bold : FontWeight.normal,
8804 ),
8805 ),
8806 ),
8807 ),
8808 const SizedBox(width: 2),
8809 ];
8810 }
8811
8812 Widget _buildOverviewTab(BuildContext context) {
8813 Map<String, dynamic>? selected;
8814 for (final item in _collections) {
8815 if (_collectionName(item) == _selectedCollection) {
8816 selected = item;
8817 break;
8818 }
8819 }
8820 final detail = _collectionDetail ?? const <String, dynamic>{};
8821 return SingleChildScrollView(
8822 padding: const EdgeInsets.all(16),
8823 child: Column(
8824 crossAxisAlignment: CrossAxisAlignment.start,
8825 children: [
8826 Wrap(
8827 spacing: 12,
8828 runSpacing: 12,
8829 children: [
8830 _metric(
8831 Icons.storage_outlined,
8832 'Records',
8833 '${_records.length}',
8834 Colors.teal,
8835 ),
8836 _metric(
8837 Icons.history_outlined,
8838 'Changes',
8839 '${_collectionChanges.length}',
8840 Colors.purple,
8841 ),
8842 _metric(
8843 Icons.shield_outlined,
8844 'Access',
8845 _valueText(detail['access'] ?? detail['mode'] ?? 'admin'),
8846 Colors.green,
8847 ),
8848 ],
8849 ),
8850 const SizedBox(height: 16),
8851 LayoutBuilder(
8852 builder: (context, constraints) {
8853 final cards = [
8854 _infoCard(
8855 context,
8856 'Collection List Row',
8857 Icons.list_alt_outlined,
8858 Colors.teal,
8859 _orderedRows(selected ?? const {}),
8860 ),
8861 _infoCard(
8862 context,
8863 'Collection Detail',
8864 Icons.info_outline,
8865 Colors.blue,
8866 _orderedRows(detail),
8867 ),
8868 ];
8869 if (constraints.maxWidth < 900) {
8870 return Column(
8871 children: [
8872 cards.first,
8873 const SizedBox(height: 12),
8874 cards.last,
8875 ],
8876 );
8877 }
8878 return Row(
8879 crossAxisAlignment: CrossAxisAlignment.start,
8880 children: [
8881 Expanded(child: cards.first),
8882 const SizedBox(width: 12),
8883 Expanded(child: cards.last),
8884 ],
8885 );
8886 },
8887 ),
8888 const SizedBox(height: 16),
8889 _rawPanel('Raw collection payload', {
8890 if (selected != null) 'list_row': selected,
8891 if (detail.isNotEmpty) 'detail': detail,
8892 }),
8893 ],
8894 ),
8895 );
8896 }
8897
8898 Widget _buildRecordsTab(BuildContext context) {
8899 return Padding(
8900 padding: const EdgeInsets.all(16),
8901 child: LayoutBuilder(
8902 builder: (context, constraints) {
8903 final records = _recordsList(context);
8904 final detail = _recordDetail(context);
8905 if (constraints.maxWidth < 880) {
8906 return Column(
8907 children: [
8908 Expanded(child: records),
8909 const SizedBox(height: 12),
8910 Expanded(child: detail),
8911 ],
8912 );
8913 }
8914 return Row(
8915 children: [
8916 SizedBox(width: 360, child: records),
8917 const SizedBox(width: 12),
8918 Expanded(child: detail),
8919 ],
8920 );
8921 },
8922 ),
8923 );
8924 }
8925
8926 Widget _recordsList(BuildContext context) {
8927 return _framed(
8928 context,
8929 title: 'Records',
8930 icon: Icons.article_outlined,
8931 color: Colors.teal,
8932 trailing: Row(
8933 mainAxisSize: MainAxisSize.min,
8934 children: [
8935 if (_schemaSpec.listMode != 'table') ...[
8936 _chip(_schemaSpec.listMode.toUpperCase(), Colors.purple),
8937 const SizedBox(width: 6),
8938 ],
8939 _chip('${_records.length}', Colors.teal),
8940 ],
8941 ),
8942 child: _records.isEmpty
8943 ? Center(
8944 child: Text(
8945 _selectedHasRecords
8946 ? 'No records'
8947 : 'Object namespace — records not applicable.\nBrowse these objects on the Objects screen.',
8948 textAlign: TextAlign.center,
8949 style: TextStyle(color: Colors.white38),
8950 ),
8951 )
8952 : ListView.separated(
8953 itemCount: _records.length,
8954 separatorBuilder: (_, __) => const SizedBox(height: 8),
8955 itemBuilder: (context, index) {
8956 final record = _mapFromDynamic(_records[index]);
8957 final id = _recordId(record);
8958 final selected =
8959 id.isNotEmpty &&
8960 id == _recordId(_selectedRecord ?? const {});
8961 return InkWell(
8962 borderRadius: BorderRadius.circular(6),
8963 onTap: () => _selectRecord(record),
8964 child: Container(
8965 padding: const EdgeInsets.all(10),
8966 decoration: BoxDecoration(
8967 color: selected
8968 ? Theme.of(
8969 context,
8970 ).colorScheme.primary.withValues(alpha: 0.12)
8971 : Colors.white.withValues(alpha: 0.03),
8972 borderRadius: BorderRadius.circular(6),
8973 border: Border.all(
8974 color: selected
8975 ? Theme.of(context).colorScheme.primary
8976 : Colors.white10,
8977 ),
8978 ),
8979 // views.list_mode picks the reading mode for the row.
8980 child: switch (_schemaSpec.listMode) {
8981 'cards' => _recordCardTile(record, id, index),
8982 'feed' => _recordFeedTile(record, id, index),
8983 _ => _recordTableTile(record, id, index),
8984 },
8985 ),
8986 );
8987 },
8988 ),
8989 );
8990 }
8991
8992 Widget _recordTableTile(Map<String, dynamic> record, String id, int index) {
8993 final preview = _recordPreview(record);
8994 return Column(
8995 crossAxisAlignment: CrossAxisAlignment.start,
8996 children: [
8997 Text(
8998 id.isEmpty ? 'record ${index + 1}' : id,
8999 overflow: TextOverflow.ellipsis,
9000 style: const TextStyle(
9001 fontWeight: FontWeight.w600,
9002 fontFamily: 'monospace',
9003 ),
9004 ),
9005 if (preview.isNotEmpty) ...[
9006 const SizedBox(height: 4),
9007 Text(
9008 preview,
9009 maxLines: 2,
9010 overflow: TextOverflow.ellipsis,
9011 style: TextStyle(fontSize: 12, color: Colors.white54),
9012 ),
9013 ],
9014 ],
9015 );
9016 }
9017
9018 /// First non-empty list-field value — the record's display title in
9019 /// cards/feed modes.
9020 String _recordListTitle(Map<String, dynamic> record, String id, int index) {
9021 for (final key in _schemaSpec.listFields) {
9022 final value = record[key];
9023 if (_hasValue(value)) return _valueText(value);
9024 }
9025 return id.isEmpty ? 'record ${index + 1}' : id;
9026 }
9027
9028 Widget _recordCardTile(Map<String, dynamic> record, String id, int index) {
9029 final fields = _schemaSpec.listFields;
9030 return Column(
9031 crossAxisAlignment: CrossAxisAlignment.start,
9032 children: [
9033 Text(
9034 _recordListTitle(record, id, index),
9035 maxLines: 2,
9036 overflow: TextOverflow.ellipsis,
9037 style: const TextStyle(fontSize: 13, fontWeight: FontWeight.w600),
9038 ),
9039 const SizedBox(height: 4),
9040 for (final key in fields.skip(1))
9041 if (_hasValue(record[key]) && key != 'is_public')
9042 Text(
9043 '${_titleCase(key)}: ${_valueText(record[key])}',
9044 maxLines: 1,
9045 overflow: TextOverflow.ellipsis,
9046 style: TextStyle(fontSize: 11, color: Colors.white54),
9047 ),
9048 const SizedBox(height: 4),
9049 Row(
9050 children: [
9051 if (record.containsKey('is_public'))
9052 Padding(
9053 padding: const EdgeInsets.only(right: 8),
9054 child: _chip(
9055 schemaBoolIsTrue(record['is_public']) ? 'PUBLIC' : 'PRIVATE',
9056 schemaBoolIsTrue(record['is_public'])
9057 ? Colors.green
9058 : Colors.blueGrey,
9059 ),
9060 ),
9061 Expanded(
9062 child: Text(
9063 id,
9064 overflow: TextOverflow.ellipsis,
9065 style: const TextStyle(
9066 fontSize: 10,
9067 fontFamily: 'monospace',
9068 color: Colors.white30,
9069 ),
9070 ),
9071 ),
9072 ],
9073 ),
9074 ],
9075 );
9076 }
9077
9078 Widget _recordFeedTile(Map<String, dynamic> record, String id, int index) {
9079 final fields = _schemaSpec.listFields;
9080 final when = (record['created_at'] ?? record['updated_at'] ?? record['at'])
9081 ?.toString();
9082 // The longest remaining list-field value reads as the entry body.
9083 String? body;
9084 for (final key in fields.skip(1)) {
9085 final value = record[key];
9086 if (!_hasValue(value)) continue;
9087 final text = _valueText(value);
9088 if (body == null || text.length > body.length) body = text;
9089 }
9090 return Column(
9091 crossAxisAlignment: CrossAxisAlignment.start,
9092 children: [
9093 Row(
9094 children: [
9095 Expanded(
9096 child: Text(
9097 _recordListTitle(record, id, index),
9098 maxLines: 1,
9099 overflow: TextOverflow.ellipsis,
9100 style: const TextStyle(
9101 fontSize: 13,
9102 fontWeight: FontWeight.w600,
9103 ),
9104 ),
9105 ),
9106 if (when != null)
9107 Text(
9108 when.length > 16 ? when.substring(0, 16) : when,
9109 style: const TextStyle(
9110 fontSize: 10,
9111 fontFamily: 'monospace',
9112 color: Colors.white30,
9113 ),
9114 ),
9115 ],
9116 ),
9117 if (body != null) ...[
9118 const SizedBox(height: 4),
9119 Text(
9120 body,
9121 maxLines: 4,
9122 overflow: TextOverflow.ellipsis,
9123 style: TextStyle(fontSize: 12, color: Colors.white70, height: 1.3),
9124 ),
9125 ],
9126 ],
9127 );
9128 }
9129
9130 Widget _recordDetail(BuildContext context) {
9131 final record = _selectedRecord;
9132 final canWrite =
9133 !_writing && record != null && _recordId(record).isNotEmpty;
9134 return _framed(
9135 context,
9136 title: 'Record Detail',
9137 icon: Icons.article_outlined,
9138 color: Colors.blue,
9139 trailing: Row(
9140 mainAxisSize: MainAxisSize.min,
9141 children: [
9142 Tooltip(
9143 message:
9144 'Update through PUT /admin/collections/{collection}/records/{record_id}',
9145 child: OutlinedButton.icon(
9146 onPressed: canWrite ? _showEditRecordDialog : null,
9147 icon: const Icon(Icons.edit, size: 14),
9148 label: const Text('Edit'),
9149 ),
9150 ),
9151 const SizedBox(width: 8),
9152 Tooltip(
9153 message:
9154 'Delete through DELETE /admin/collections/{collection}/records/{record_id}',
9155 child: OutlinedButton.icon(
9156 style: OutlinedButton.styleFrom(foregroundColor: Colors.red),
9157 onPressed: canWrite ? _confirmDeleteRecord : null,
9158 icon: const Icon(Icons.delete_outline, size: 14),
9159 label: const Text('Delete'),
9160 ),
9161 ),
9162 ],
9163 ),
9164 child: _recordLoading
9165 ? const Center(child: CircularProgressIndicator())
9166 : record == null
9167 ? Center(
9168 child: Text(
9169 'No record selected',
9170 style: TextStyle(color: Colors.white38),
9171 ),
9172 )
9173 : ListView(
9174 children: [
9175 ..._orderedRows(record).map((entry) {
9176 return _infoRow(entry.key, entry.value);
9177 }),
9178 const SizedBox(height: 12),
9179 _changeList(
9180 context,
9181 title: 'Record Activity',
9182 changes: _recordChanges,
9183 expand: false,
9184 ),
9185 const SizedBox(height: 12),
9186 _rawPanel('Raw record payload', {
9187 'record': record,
9188 if (_recordChanges.isNotEmpty) 'changes': _recordChanges,
9189 }),
9190 ],
9191 ),
9192 );
9193 }
9194
9195 Widget _buildActivityTab(BuildContext context) {
9196 return Padding(
9197 padding: const EdgeInsets.all(16),
9198 child: _changeList(
9199 context,
9200 title: 'Collection Activity',
9201 changes: _collectionChanges,
9202 ),
9203 );
9204 }
9205
9206 Widget _changeList(
9207 BuildContext context, {
9208 required String title,
9209 required List<dynamic> changes,
9210 bool expand = true,
9211 }) {
9212 return _framed(
9213 context,
9214 title: title,
9215 icon: Icons.history_outlined,
9216 color: Colors.purple,
9217 trailing: _chip('${changes.length}', Colors.purple),
9218 expandChild: expand,
9219 child: changes.isEmpty
9220 ? Center(
9221 child: Text(
9222 'No changes',
9223 style: TextStyle(color: Colors.white38),
9224 ),
9225 )
9226 : ListView.separated(
9227 shrinkWrap: !expand,
9228 physics: expand ? null : const NeverScrollableScrollPhysics(),
9229 itemCount: changes.length,
9230 separatorBuilder: (_, __) => const SizedBox(height: 8),
9231 itemBuilder: (context, index) {
9232 final change = _mapFromDynamic(changes[index]);
9233 final action = _firstText(change, const [
9234 'action',
9235 'type',
9236 'event_type',
9237 'change_type',
9238 'operation',
9239 ], fallback: 'change');
9240 final message = _firstText(change, const [
9241 'message',
9242 'description',
9243 'note',
9244 'summary',
9245 ], fallback: action);
9246 final actor = _firstText(change, const [
9247 'actor',
9248 'author',
9249 'user',
9250 'user_id',
9251 'principal',
9252 ], fallback: 'unknown');
9253 final timestamp = _firstText(change, const [
9254 'timestamp',
9255 'created_at',
9256 'changed_at',
9257 'time',
9258 ]);
9259 final color = _actionColor(action);
9260 return Container(
9261 padding: const EdgeInsets.all(10),
9262 decoration: BoxDecoration(
9263 color: color.withValues(alpha: 0.05),
9264 borderRadius: BorderRadius.circular(6),
9265 border: Border.all(color: Colors.white10),
9266 ),
9267 child: Column(
9268 crossAxisAlignment: CrossAxisAlignment.start,
9269 children: [
9270 Row(
9271 children: [
9272 _chip(action, color),
9273 const SizedBox(width: 8),
9274 Expanded(
9275 child: Text(
9276 message,
9277 maxLines: 2,
9278 overflow: TextOverflow.ellipsis,
9279 style: const TextStyle(
9280 fontSize: 13,
9281 fontWeight: FontWeight.w600,
9282 ),
9283 ),
9284 ),
9285 ],
9286 ),
9287 const SizedBox(height: 7),
9288 Wrap(
9289 spacing: 8,
9290 runSpacing: 6,
9291 children: [
9292 _chip('actor: ${_short(actor, 28)}', Colors.blue),
9293 if (timestamp.isNotEmpty)
9294 _chip(_short(timestamp, 32), Colors.white54),
9295 if (change['record_id'] != null)
9296 _chip(
9297 'record: ${_short(change['record_id'].toString(), 24)}',
9298 Colors.teal,
9299 ),
9300 if (change['correlation_id'] != null)
9301 _chip(
9302 'corr: ${_short(change['correlation_id'].toString(), 18)}',
9303 Colors.white54,
9304 ),
9305 ],
9306 ),
9307 ],
9308 ),
9309 );
9310 },
9311 ),
9312 );
9313 }
9314
9315 Widget _metric(IconData icon, String label, String value, Color color) {
9316 return Container(
9317 width: 150,
9318 padding: const EdgeInsets.all(12),
9319 decoration: BoxDecoration(
9320 color: color.withValues(alpha: 0.08),
9321 borderRadius: BorderRadius.circular(8),
9322 border: Border.all(color: color.withValues(alpha: 0.2)),
9323 ),
9324 child: Row(
9325 children: [
9326 Icon(icon, size: 18, color: color),
9327 const SizedBox(width: 8),
9328 Expanded(
9329 child: Column(
9330 crossAxisAlignment: CrossAxisAlignment.start,
9331 children: [
9332 Text(
9333 label,
9334 overflow: TextOverflow.ellipsis,
9335 style: TextStyle(fontSize: 11, color: Colors.white38),
9336 ),
9337 Text(
9338 value,
9339 overflow: TextOverflow.ellipsis,
9340 style: const TextStyle(
9341 fontSize: 15,
9342 fontWeight: FontWeight.w600,
9343 ),
9344 ),
9345 ],
9346 ),
9347 ),
9348 ],
9349 ),
9350 );
9351 }
9352
9353 Widget _infoCard(
9354 BuildContext context,
9355 String title,
9356 IconData icon,
9357 Color color,
9358 List<MapEntry<String, dynamic>> rows,
9359 ) {
9360 return _framed(
9361 context,
9362 title: title,
9363 icon: icon,
9364 color: color,
9365 trailing: _chip(rows.isEmpty ? 'EMPTY' : 'READ ONLY', color),
9366 expandChild: false,
9367 child: rows.isEmpty
9368 ? Text('Not reported', style: TextStyle(color: Colors.white38))
9369 : Column(
9370 children: rows.map((entry) {
9371 return _infoRow(entry.key, entry.value);
9372 }).toList(),
9373 ),
9374 );
9375 }
9376
9377 Widget _framed(
9378 BuildContext context, {
9379 required String title,
9380 required IconData icon,
9381 required Color color,
9382 required Widget child,
9383 Widget? trailing,
9384 bool expandChild = true,
9385 }) {
9386 return Container(
9387 padding: const EdgeInsets.all(14),
9388 decoration: BoxDecoration(
9389 color: Theme.of(context).colorScheme.surfaceContainerLow,
9390 borderRadius: BorderRadius.circular(8),
9391 border: Border.all(color: Colors.white10),
9392 ),
9393 child: Column(
9394 crossAxisAlignment: CrossAxisAlignment.start,
9395 children: [
9396 Row(
9397 children: [
9398 Icon(icon, size: 18, color: color),
9399 const SizedBox(width: 8),
9400 Text(
9401 title,
9402 style: const TextStyle(
9403 fontSize: 13,
9404 fontWeight: FontWeight.w700,
9405 ),
9406 ),
9407 const Spacer(),
9408 if (trailing != null) trailing,
9409 ],
9410 ),
9411 const SizedBox(height: 12),
9412 if (expandChild) Expanded(child: child) else child,
9413 ],
9414 ),
9415 );
9416 }
9417
9418 Widget _infoRow(String label, dynamic value) {
9419 return Padding(
9420 padding: const EdgeInsets.only(bottom: 7),
9421 child: Row(
9422 crossAxisAlignment: CrossAxisAlignment.start,
9423 children: [
9424 Expanded(
9425 flex: 5,
9426 child: Text(
9427 _titleCase(label),
9428 overflow: TextOverflow.ellipsis,
9429 style: TextStyle(fontSize: 12, color: Colors.white54),
9430 ),
9431 ),
9432 const SizedBox(width: 10),
9433 Expanded(
9434 flex: 7,
9435 child: Text(
9436 _valueText(value),
9437 maxLines: 3,
9438 overflow: TextOverflow.ellipsis,
9439 textAlign: TextAlign.right,
9440 style: TextStyle(
9441 fontSize: 12,
9442 color: Colors.white70,
9443 fontWeight: FontWeight.w600,
9444 ),
9445 ),
9446 ),
9447 ],
9448 ),
9449 );
9450 }
9451
9452 Widget _rawPanel(String title, Map<String, dynamic> value) {
9453 return ExpansionTile(
9454 tilePadding: const EdgeInsets.symmetric(horizontal: 4),
9455 title: Text(title, style: TextStyle(fontSize: 12, color: Colors.white54)),
9456 children: [
9457 Container(
9458 width: double.infinity,
9459 padding: const EdgeInsets.all(12),
9460 decoration: BoxDecoration(
9461 color: Colors.black26,
9462 borderRadius: BorderRadius.circular(8),
9463 border: Border.all(color: Colors.white10),
9464 ),
9465 child: SelectableText(
9466 const JsonEncoder.withIndent(' ').convert(value),
9467 style: const TextStyle(
9468 fontFamily: 'monospace',
9469 fontSize: 11,
9470 height: 1.35,
9471 ),
9472 ),
9473 ),
9474 ],
9475 );
9476 }
9477
9478 Widget _chip(String text, Color color) {
9479 return Container(
9480 padding: const EdgeInsets.symmetric(horizontal: 7, vertical: 2),
9481 decoration: BoxDecoration(
9482 color: color.withValues(alpha: 0.1),
9483 borderRadius: BorderRadius.circular(4),
9484 border: Border.all(color: color.withValues(alpha: 0.16)),
9485 ),
9486 child: Text(
9487 _short(text, 44),
9488 overflow: TextOverflow.ellipsis,
9489 style: TextStyle(
9490 fontSize: 10,
9491 color: color,
9492 fontWeight: FontWeight.bold,
9493 ),
9494 ),
9495 );
9496 }
9497
9498 List<MapEntry<String, dynamic>> _orderedRows(Map<String, dynamic> values) {
9499 final preferred = [
9500 'name',
9501 'collection',
9502 'id',
9503 'count',
9504 'total',
9505 'record_count',
9506 'created_at',
9507 'updated_at',
9508 'description',
9509 ];
9510 final rows = <MapEntry<String, dynamic>>[];
9511 final used = <String>{};
9512 for (final key in preferred) {
9513 final value = values[key];
9514 if (_hasValue(value)) {
9515 rows.add(MapEntry(key, value));
9516 used.add(key);
9517 }
9518 }
9519 for (final entry in values.entries) {
9520 if (used.contains(entry.key) || !_hasValue(entry.value)) continue;
9521 rows.add(entry);
9522 }
9523 return rows.take(12).toList();
9524 }
9525
9526 Map<String, dynamic> _mapFromDynamic(dynamic value) {
9527 if (value is Map<String, dynamic>) return value;
9528 if (value is Map) {
9529 return value.map((key, item) => MapEntry(key.toString(), item));
9530 }
9531 if (value is String) return {'name': value};
9532 return {'value': value};
9533 }
9534
9535 Map<String, dynamic>? _mapOrNull(dynamic value) {
9536 if (value == null) return null;
9537 return _mapFromDynamic(value);
9538 }
9539
9540 String _collectionName(Map<String, dynamic> value) {
9541 final raw =
9542 value['collection'] ?? value['name'] ?? value['id'] ?? value['key'];
9543 if (raw is Map) return _collectionName(_mapFromDynamic(raw));
9544 return raw?.toString() ?? '';
9545 }
9546
9547 String _collectionCount(Map<String, dynamic> value) {
9548 final raw =
9549 value['count'] ??
9550 value['record_count'] ??
9551 value['records_count'] ??
9552 value['total'];
9553 return raw == null ? '' : raw.toString();
9554 }
9555
9556 /// Servers report object namespaces (directory prefixes like `system`)
9557 /// alongside record collections; only the latter have record storage.
9558 bool _hasRecords(Map<String, dynamic> value) {
9559 final raw = value['has_records'];
9560 if (raw is bool) return raw;
9561 return true;
9562 }
9563
9564 bool get _selectedHasRecords {
9565 for (final item in _collections) {
9566 if (_collectionName(item) == _selectedCollection) {
9567 return _hasRecords(item);
9568 }
9569 }
9570 return true;
9571 }
9572
9573 String _recordId(Map<String, dynamic> value) {
9574 final raw =
9575 value['id'] ?? value['record_id'] ?? value['key'] ?? value['name'];
9576 return raw?.toString() ?? '';
9577 }
9578
9579 String _recordPreview(Map<String, dynamic> record) {
9580 final parts = <String>[];
9581 // views.list_fields from the schema picks the preview columns.
9582 final listFields = _schemaSpec.listFields;
9583 if (listFields.isNotEmpty) {
9584 for (final key in listFields) {
9585 final value = record[key];
9586 if (!_hasValue(value)) continue;
9587 parts.add('${_titleCase(key)}: ${_valueText(value)}');
9588 if (parts.length == 3) break;
9589 }
9590 if (parts.isNotEmpty) return parts.join(' ');
9591 }
9592 for (final entry in record.entries) {
9593 if (_internalRecordKeys.contains(entry.key)) continue;
9594 if (!_hasValue(entry.value)) continue;
9595 parts.add('${_titleCase(entry.key)}: ${_valueText(entry.value)}');
9596 if (parts.length == 2) break;
9597 }
9598 return parts.join(' ');
9599 }
9600
9601 String _firstText(
9602 Map<String, dynamic> value,
9603 List<String> keys, {
9604 String fallback = '',
9605 }) {
9606 for (final key in keys) {
9607 final raw = value[key]?.toString();
9608 if (raw != null && raw.trim().isNotEmpty) return raw;
9609 }
9610 return fallback;
9611 }
9612
9613 Color _actionColor(String value) {
9614 final normalized = value.toLowerCase();
9615 if (normalized.contains('delete')) return Colors.red;
9616 if (normalized.contains('update') || normalized.contains('change')) {
9617 return Colors.orange;
9618 }
9619 if (normalized.contains('create') || normalized.contains('insert')) {
9620 return Colors.green;
9621 }
9622 return Colors.purple;
9623 }
9624
9625 bool _hasValue(dynamic value) {
9626 if (value == null) return false;
9627 if (value is String) return value.trim().isNotEmpty;
9628 if (value is List) return value.isNotEmpty;
9629 if (value is Map) return value.isNotEmpty;
9630 return true;
9631 }
9632
9633 String _valueText(dynamic value) {
9634 if (value == null) return '?';
9635 if (value is bool) return value ? 'yes' : 'no';
9636 if (value is List) return '${value.length} items';
9637 if (value is Map) {
9638 final entries = value.entries.take(3).map((entry) {
9639 return '${_titleCase(entry.key.toString())}: ${_valueText(entry.value)}';
9640 });
9641 return entries.join(', ');
9642 }
9643 return value.toString();
9644 }
9645
9646 String _titleCase(String value) {
9647 return value
9648 .replaceAll('_', ' ')
9649 .replaceAll('-', ' ')
9650 .split(' ')
9651 .where((part) => part.isNotEmpty)
9652 .map((part) => '${part[0].toUpperCase()}${part.substring(1)}')
9653 .join(' ');
9654 }
9655
9656 String _short(String value, int limit) {
9657 if (value.length <= limit) return value;
9658 return '${value.substring(0, limit)}...';
9659 }
9660}
9661
9662class ProbeCrudPanel extends StatefulWidget {
9663 const ProbeCrudPanel({super.key});
9664
9665 @override
9666 State<ProbeCrudPanel> createState() => _ProbeCrudPanelState();
9667}
9668
9669class _ProbeCrudPanelState extends State<ProbeCrudPanel> {
9670 final _idController = TextEditingController(text: 'probe_001');
9671 final _statusController = TextEditingController(text: 'created');
9672 final _noteController = TextEditingController(text: 'admin write test');
9673 Map<String, dynamic>? _schema;
9674 Map<String, dynamic>? _lastResponse;
9675 List<dynamic> _records = [];
9676 List<dynamic> _changes = [];
9677 String _message = 'Ready';
9678 bool _busy = false;
9679
9680 @override
9681 void initState() {
9682 super.initState();
9683 _refresh();
9684 }
9685
9686 @override
9687 void dispose() {
9688 _idController.dispose();
9689 _statusController.dispose();
9690 _noteController.dispose();
9691 super.dispose();
9692 }
9693
9694 Future<Map<String, dynamic>> _request(
9695 String method,
9696 String path, {
9697 Map<String, dynamic>? data,
9698 }) {
9699 final api = ScrollAPI();
9700 final base = api.objectServerUrl;
9701 if (base == null || base.isEmpty) {
9702 return Future.value({'error': 'Object server is not connected'});
9703 }
9704 return api.rawRequest(method, '$base$path', data: data);
9705 }
9706
9707 Future<void> _refresh({String? completionMessage}) async {
9708 if (!mounted) return;
9709 setState(() {
9710 _busy = true;
9711 _message = 'Refreshing probe';
9712 });
9713
9714 final schemaResponse = await _request('GET', 'schemas/dbbasic_probe');
9715 final recordsResponse = await _request(
9716 'GET',
9717 'collections/dbbasic_probe/records',
9718 );
9719 final changesResponse = await _request(
9720 'GET',
9721 'collections/dbbasic_probe/changes',
9722 );
9723
9724 if (!mounted) return;
9725 final schemaBody = schemaResponse['body'];
9726 final records = _listFromBody(recordsResponse['body'], 'records');
9727 final changes = _listFromBody(changesResponse['body'], 'changes');
9728 setState(() {
9729 _schema = schemaBody is Map<String, dynamic> ? schemaBody : null;
9730 _records = records;
9731 _changes = changes;
9732 _lastResponse = recordsResponse;
9733 _message =
9734 completionMessage ??
9735 'Schema ${_statusText(schemaResponse)}, records ${_statusText(recordsResponse)}, changes ${_statusText(changesResponse)}';
9736 _busy = false;
9737 });
9738 }
9739
9740 Future<void> _mutate(
9741 String label,
9742 Future<Map<String, dynamic>> Function() action,
9743 ) async {
9744 setState(() {
9745 _busy = true;
9746 _message = '$label in progress';
9747 });
9748 final response = await action();
9749 if (!mounted) return;
9750 final summary = '$label ${_statusText(response)}';
9751 if (_isOk(response)) {
9752 setState(() => _lastResponse = response);
9753 await _refresh(completionMessage: summary);
9754 return;
9755 }
9756 setState(() {
9757 _lastResponse = response;
9758 _message = summary;
9759 _busy = false;
9760 });
9761 }
9762
9763 Map<String, dynamic> _payload({required bool includeId}) {
9764 final id = _idController.text.trim();
9765 return {
9766 if (includeId) 'id': id,
9767 'status': _statusController.text.trim(),
9768 'note': _noteController.text.trim(),
9769 'updated_at': DateTime.now().toUtc().toIso8601String(),
9770 };
9771 }
9772
9773 Future<void> _create() {
9774 return _mutate(
9775 'Create',
9776 () => _request(
9777 'POST',
9778 'collections/dbbasic_probe/records',
9779 data: _payload(includeId: true),
9780 ),
9781 );
9782 }
9783
9784 Future<void> _update() {
9785 final id = _idController.text.trim();
9786 return _mutate(
9787 'Update',
9788 () => _request(
9789 'PUT',
9790 'collections/dbbasic_probe/records/${Uri.encodeComponent(id)}',
9791 data: _payload(includeId: false),
9792 ),
9793 );
9794 }
9795
9796 Future<void> _delete() {
9797 final id = _idController.text.trim();
9798 return _mutate(
9799 'Delete',
9800 () => _request(
9801 'DELETE',
9802 'collections/dbbasic_probe/records/${Uri.encodeComponent(id)}',
9803 ),
9804 );
9805 }
9806
9807 Future<void> _loadRecordChanges() async {
9808 final id = _idController.text.trim();
9809 setState(() {
9810 _busy = true;
9811 _message = 'Loading record changes';
9812 });
9813 final response = await _request(
9814 'GET',
9815 'collections/dbbasic_probe/records/${Uri.encodeComponent(id)}/changes',
9816 );
9817 if (!mounted) return;
9818 setState(() {
9819 _changes = _listFromBody(response['body'], 'changes');
9820 _lastResponse = response;
9821 _message = 'Record changes ${_statusText(response)}';
9822 _busy = false;
9823 });
9824 }
9825
9826 void _selectRecord(dynamic record) {
9827 final map = _asMap(record);
9828 final id = map['id']?.toString();
9829 if (id != null && id.isNotEmpty) _idController.text = id;
9830 _statusController.text = map['status']?.toString() ?? '';
9831 _noteController.text = map['note']?.toString() ?? '';
9832 setState(() => _message = 'Selected ${id ?? 'record'}');
9833 }
9834
9835 bool _isOk(Map<String, dynamic> response) {
9836 final status = response['status'];
9837 return status is int && status >= 200 && status < 300;
9838 }
9839
9840 String _statusText(Map<String, dynamic> response) {
9841 final error = response['error'];
9842 if (error != null) return 'error';
9843 final status = response['status'];
9844 return status is int ? status.toString() : 'unknown';
9845 }
9846
9847 List<dynamic> _listFromBody(dynamic body, String preferredKey) {
9848 if (body is List) return body;
9849 if (body is Map) {
9850 final preferred = body[preferredKey];
9851 if (preferred is List) return preferred;
9852 final results = body['results'];
9853 if (results is List) return results;
9854 final items = body['items'];
9855 if (items is List) return items;
9856 }
9857 return [];
9858 }
9859
9860 Map<String, dynamic> _asMap(dynamic value) {
9861 if (value is Map<String, dynamic>) return value;
9862 if (value is Map) {
9863 return value.map((key, item) => MapEntry(key.toString(), item));
9864 }
9865 return {'value': value};
9866 }
9867
9868 String _valueText(dynamic value) {
9869 if (value == null) return '';
9870 if (value is String) return value;
9871 if (value is num || value is bool) return value.toString();
9872 return const JsonEncoder.withIndent(' ').convert(value);
9873 }
9874
9875 List<String> _schemaFieldNames() {
9876 final schema = _schema;
9877 if (schema == null) return const ['id', 'status', 'note', 'updated_at'];
9878 final fields = schema['fields'];
9879 if (fields is Map) return fields.keys.map((key) => key.toString()).toList();
9880 if (fields is List) {
9881 return fields
9882 .map((field) {
9883 if (field is Map && field['name'] != null) {
9884 return field['name'].toString();
9885 }
9886 return field.toString();
9887 })
9888 .where((name) => name.isNotEmpty)
9889 .toList();
9890 }
9891 return const ['id', 'status', 'note', 'updated_at'];
9892 }
9893
9894 @override
9895 Widget build(BuildContext context) {
9896 final fields = _schemaFieldNames().join(', ');
9897 return Container(
9898 padding: const EdgeInsets.all(16),
9899 decoration: BoxDecoration(
9900 color: Theme.of(context).colorScheme.surfaceContainerLow,
9901 borderRadius: BorderRadius.circular(8),
9902 border: Border.all(color: Colors.white10),
9903 ),
9904 child: Column(
9905 crossAxisAlignment: CrossAxisAlignment.start,
9906 children: [
9907 Row(
9908 children: [
9909 const Icon(Icons.science_outlined, size: 20),
9910 const SizedBox(width: 8),
9911 Text(
9912 'dbbasic_probe',
9913 style: Theme.of(context).textTheme.titleMedium,
9914 ),
9915 const SizedBox(width: 10),
9916 _statusChip(_busy ? 'BUSY' : _message),
9917 const Spacer(),
9918 IconButton(
9919 onPressed: _busy ? null : () => _refresh(),
9920 icon: const Icon(Icons.refresh, size: 18),
9921 tooltip: 'Refresh',
9922 ),
9923 ],
9924 ),
9925 const SizedBox(height: 4),
9926 Text(
9927 'Fields: $fields',
9928 style: TextStyle(fontSize: 12, color: Colors.white54),
9929 ),
9930 const SizedBox(height: 14),
9931 LayoutBuilder(
9932 builder: (context, constraints) {
9933 final narrow = constraints.maxWidth < 860;
9934 final editor = _buildEditor(context);
9935 final records = _buildRecords(context);
9936 final changes = _buildChanges(context);
9937 if (narrow) {
9938 return Column(
9939 children: [
9940 editor,
9941 const SizedBox(height: 12),
9942 records,
9943 const SizedBox(height: 12),
9944 changes,
9945 ],
9946 );
9947 }
9948 return Row(
9949 crossAxisAlignment: CrossAxisAlignment.start,
9950 children: [
9951 SizedBox(width: 320, child: editor),
9952 const SizedBox(width: 12),
9953 Expanded(child: records),
9954 const SizedBox(width: 12),
9955 Expanded(child: changes),
9956 ],
9957 );
9958 },
9959 ),
9960 ],
9961 ),
9962 );
9963 }
9964
9965 Widget _buildEditor(BuildContext context) {
9966 return _section(
9967 context,
9968 title: 'Record',
9969 child: Column(
9970 children: [
9971 _field(_idController, 'id'),
9972 const SizedBox(height: 8),
9973 _field(_statusController, 'status'),
9974 const SizedBox(height: 8),
9975 _field(_noteController, 'note', maxLines: 3),
9976 const SizedBox(height: 12),
9977 Wrap(
9978 spacing: 8,
9979 runSpacing: 8,
9980 children: [
9981 FilledButton.icon(
9982 onPressed: _busy ? null : _create,
9983 icon: const Icon(Icons.add, size: 16),
9984 label: const Text('Create'),
9985 ),
9986 FilledButton.tonalIcon(
9987 onPressed: _busy ? null : _update,
9988 icon: const Icon(Icons.save_outlined, size: 16),
9989 label: const Text('Update'),
9990 ),
9991 OutlinedButton.icon(
9992 onPressed: _busy ? null : _delete,
9993 icon: const Icon(Icons.delete_outline, size: 16),
9994 label: const Text('Delete'),
9995 ),
9996 OutlinedButton.icon(
9997 onPressed: _busy ? null : _loadRecordChanges,
9998 icon: const Icon(Icons.history, size: 16),
9999 label: const Text('Changes'),
10000 ),
10001 ],
10002 ),
10003 const SizedBox(height: 12),
10004 Container(
10005 width: double.infinity,
10006 padding: const EdgeInsets.all(10),
10007 decoration: BoxDecoration(
10008 color: Colors.black26,
10009 borderRadius: BorderRadius.circular(6),
10010 border: Border.all(color: Colors.white10),
10011 ),
10012 child: SelectableText(
10013 _lastResponse == null
10014 ? '// No response yet'
10015 : const JsonEncoder.withIndent(' ').convert(_lastResponse),
10016 style: TextStyle(
10017 fontSize: 11,
10018 height: 1.35,
10019 fontFamily: 'monospace',
10020 color: _lastResponse == null ? Colors.white24 : Colors.white70,
10021 ),
10022 ),
10023 ),
10024 ],
10025 ),
10026 );
10027 }
10028
10029 Widget _buildRecords(BuildContext context) {
10030 return _section(
10031 context,
10032 title: 'Records',
10033 child: SizedBox(
10034 height: 260,
10035 child: _records.isEmpty
10036 ? Center(
10037 child: Text(
10038 'No records',
10039 style: TextStyle(fontSize: 12, color: Colors.white38),
10040 ),
10041 )
10042 : ListView.separated(
10043 itemCount: _records.length,
10044 separatorBuilder: (_, __) => const SizedBox(height: 8),
10045 itemBuilder: (context, index) {
10046 final map = _asMap(_records[index]);
10047 final id = _valueText(map['id']);
10048 final status = _valueText(map['status']);
10049 final note = _valueText(map['note']);
10050 return InkWell(
10051 borderRadius: BorderRadius.circular(6),
10052 onTap: () => _selectRecord(map),
10053 child: Container(
10054 padding: const EdgeInsets.all(10),
10055 decoration: BoxDecoration(
10056 color: Colors.white.withValues(alpha: 0.03),
10057 borderRadius: BorderRadius.circular(6),
10058 border: Border.all(color: Colors.white10),
10059 ),
10060 child: Row(
10061 children: [
10062 Expanded(
10063 child: Column(
10064 crossAxisAlignment: CrossAxisAlignment.start,
10065 children: [
10066 Text(
10067 id.isEmpty ? 'record ${index + 1}' : id,
10068 overflow: TextOverflow.ellipsis,
10069 style: const TextStyle(
10070 fontWeight: FontWeight.w600,
10071 ),
10072 ),
10073 if (note.isNotEmpty) ...[
10074 const SizedBox(height: 2),
10075 Text(
10076 note,
10077 maxLines: 2,
10078 overflow: TextOverflow.ellipsis,
10079 style: TextStyle(
10080 fontSize: 12,
10081 color: Colors.white54,
10082 ),
10083 ),
10084 ],
10085 ],
10086 ),
10087 ),
10088 if (status.isNotEmpty) _statusChip(status),
10089 ],
10090 ),
10091 ),
10092 );
10093 },
10094 ),
10095 ),
10096 );
10097 }
10098
10099 Widget _buildChanges(BuildContext context) {
10100 return _section(
10101 context,
10102 title: 'Changes',
10103 child: SizedBox(
10104 height: 260,
10105 child: _changes.isEmpty
10106 ? Center(
10107 child: Text(
10108 'No changes',
10109 style: TextStyle(fontSize: 12, color: Colors.white38),
10110 ),
10111 )
10112 : ListView.separated(
10113 itemCount: _changes.length,
10114 separatorBuilder: (_, __) => const Divider(height: 14),
10115 itemBuilder: (context, index) {
10116 final map = _asMap(_changes[index]);
10117 final label = _valueText(
10118 map['action'] ?? map['event'] ?? map['type'],
10119 );
10120 final id = _valueText(
10121 map['record_id'] ?? map['id'] ?? map['object_id'],
10122 );
10123 final time = _valueText(
10124 map['created_at'] ?? map['updated_at'] ?? map['timestamp'],
10125 );
10126 return Column(
10127 crossAxisAlignment: CrossAxisAlignment.start,
10128 children: [
10129 Row(
10130 children: [
10131 Expanded(
10132 child: Text(
10133 label.isEmpty ? 'change ${index + 1}' : label,
10134 overflow: TextOverflow.ellipsis,
10135 style: const TextStyle(
10136 fontWeight: FontWeight.w600,
10137 ),
10138 ),
10139 ),
10140 if (id.isNotEmpty) _statusChip(id),
10141 ],
10142 ),
10143 if (time.isNotEmpty) ...[
10144 const SizedBox(height: 2),
10145 Text(
10146 time,
10147 overflow: TextOverflow.ellipsis,
10148 style: TextStyle(fontSize: 11, color: Colors.white38),
10149 ),
10150 ],
10151 ],
10152 );
10153 },
10154 ),
10155 ),
10156 );
10157 }
10158
10159 Widget _section(
10160 BuildContext context, {
10161 required String title,
10162 required Widget child,
10163 }) {
10164 return Container(
10165 padding: const EdgeInsets.all(12),
10166 decoration: BoxDecoration(
10167 color: Theme.of(context).colorScheme.surface.withValues(alpha: 0.45),
10168 borderRadius: BorderRadius.circular(8),
10169 border: Border.all(color: Colors.white10),
10170 ),
10171 child: Column(
10172 crossAxisAlignment: CrossAxisAlignment.start,
10173 children: [
10174 Text(
10175 title,
10176 style: TextStyle(
10177 fontSize: 12,
10178 fontWeight: FontWeight.bold,
10179 color: Colors.white70,
10180 ),
10181 ),
10182 const SizedBox(height: 10),
10183 child,
10184 ],
10185 ),
10186 );
10187 }
10188
10189 Widget _field(
10190 TextEditingController controller,
10191 String label, {
10192 int maxLines = 1,
10193 }) {
10194 return TextField(
10195 controller: controller,
10196 maxLines: maxLines,
10197 decoration: InputDecoration(
10198 labelText: label,
10199 border: const OutlineInputBorder(),
10200 isDense: true,
10201 contentPadding: const EdgeInsets.symmetric(
10202 horizontal: 10,
10203 vertical: 10,
10204 ),
10205 ),
10206 style: const TextStyle(fontSize: 13),
10207 );
10208 }
10209
10210 Widget _statusChip(String text) {
10211 final normalized = text.length > 28 ? '${text.substring(0, 25)}...' : text;
10212 return Container(
10213 padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
10214 decoration: BoxDecoration(
10215 color: Colors.green.withValues(alpha: 0.1),
10216 borderRadius: BorderRadius.circular(4),
10217 border: Border.all(color: Colors.green.withValues(alpha: 0.18)),
10218 ),
10219 child: Text(
10220 normalized,
10221 overflow: TextOverflow.ellipsis,
10222 style: TextStyle(
10223 fontSize: 10,
10224 color: Colors.green.shade300,
10225 fontWeight: FontWeight.bold,
10226 ),
10227 ),
10228 );
10229 }
10230}
10231
10232// ---------------------------------------------------------------------------
10233// Placeholder
10234// ---------------------------------------------------------------------------
10235
10236// ---------------------------------------------------------------------------
10237// Invoice Form — sub-data, permissions, the real test
10238// ---------------------------------------------------------------------------
10239
10240class InvoiceFormView extends StatelessWidget {
10241 const InvoiceFormView({super.key});
10242
10243 @override
10244 Widget build(BuildContext context) {
10245 return SingleChildScrollView(
10246 padding: const EdgeInsets.all(32),
10247 child: Center(
10248 child: Container(
10249 constraints: const BoxConstraints(maxWidth: 750),
10250 child: Column(
10251 crossAxisAlignment: CrossAxisAlignment.start,
10252 children: [
10253 // Header
10254 Row(
10255 children: [
10256 Expanded(
10257 child: Column(
10258 crossAxisAlignment: CrossAxisAlignment.start,
10259 children: [
10260 Text(
10261 'Invoice #1043',
10262 style: Theme.of(context).textTheme.titleLarge,
10263 ),
10264 Text(
10265 'Draft — not yet sent',
10266 style: TextStyle(fontSize: 13, color: Colors.orange),
10267 ),
10268 ],
10269 ),
10270 ),
10271 Row(
10272 children: [
10273 IconButton(
10274 onPressed: () {},
10275 icon: const Icon(Icons.chevron_left, size: 20),
10276 tooltip: 'Previous',
10277 visualDensity: VisualDensity.compact,
10278 ),
10279 const Text(
10280 '#1043',
10281 style: TextStyle(fontSize: 12, color: Colors.white38),
10282 ),
10283 IconButton(
10284 onPressed: () {},
10285 icon: const Icon(Icons.chevron_right, size: 20),
10286 tooltip: 'Next',
10287 visualDensity: VisualDensity.compact,
10288 ),
10289 ],
10290 ),
10291 ],
10292 ),
10293 const SizedBox(height: 20),
10294
10295 // Customer section — auto-loaded sub-data
10296 Container(
10297 padding: const EdgeInsets.all(16),
10298 decoration: BoxDecoration(
10299 color: Theme.of(context).colorScheme.surfaceContainerLow,
10300 borderRadius: BorderRadius.circular(12),
10301 border: Border.all(color: Colors.white10),
10302 ),
10303 child: Column(
10304 crossAxisAlignment: CrossAxisAlignment.start,
10305 children: [
10306 Row(
10307 children: [
10308 Text(
10309 'CUSTOMER',
10310 style: TextStyle(
10311 fontSize: 10,
10312 fontWeight: FontWeight.bold,
10313 color: Colors.white38,
10314 letterSpacing: 1,
10315 ),
10316 ),
10317 const Spacer(),
10318 Text(
10319 'auto-loaded from contacts',
10320 style: TextStyle(
10321 fontSize: 10,
10322 color: Colors.blue,
10323 fontStyle: FontStyle.italic,
10324 ),
10325 ),
10326 ],
10327 ),
10328 const SizedBox(height: 12),
10329 Row(
10330 children: [
10331 Expanded(
10332 child: DropdownButtonFormField<String>(
10333 decoration: const InputDecoration(
10334 labelText: 'Customer',
10335 border: OutlineInputBorder(),
10336 isDense: true,
10337 ),
10338 value: 'Acme Corp',
10339 items:
10340 [
10341 'Acme Corp',
10342 'TechStart',
10343 'DataFlow',
10344 'CloudNine',
10345 ]
10346 .map(
10347 (v) => DropdownMenuItem(
10348 value: v,
10349 child: Text(v),
10350 ),
10351 )
10352 .toList(),
10353 onChanged: (_) {},
10354 ),
10355 ),
10356 ],
10357 ),
10358 const SizedBox(height: 12),
10359 // Auto-loaded customer details
10360 Container(
10361 padding: const EdgeInsets.all(12),
10362 decoration: BoxDecoration(
10363 color: Colors.blue.withOpacity(0.05),
10364 borderRadius: BorderRadius.circular(8),
10365 border: Border.all(
10366 color: Colors.blue.withOpacity(0.15),
10367 ),
10368 ),
10369 child: Column(
10370 children: [
10371 _subDataRow(
10372 'Contact',
10373 'Alice Chen — alice@acmecorp.com',
10374 ),
10375 _subDataRow(
10376 'Address',
10377 '123 Business Ave, Houston TX 77002',
10378 ),
10379 _subDataRow('Payment Terms', 'Net 30'),
10380 _subDataRow('Outstanding', '\$4,200 (2 invoices)'),
10381 ],
10382 ),
10383 ),
10384 ],
10385 ),
10386 ),
10387 const SizedBox(height: 16),
10388
10389 // Invoice details
10390 Row(
10391 children: [
10392 Expanded(
10393 child: AdminFieldOverlay(
10394 fieldName: 'Invoice Date',
10395 fieldType: 'date',
10396 required: true,
10397 child: TextField(
10398 decoration: const InputDecoration(
10399 labelText: 'Invoice Date',
10400 border: OutlineInputBorder(),
10401 suffixIcon: Icon(Icons.calendar_today, size: 18),
10402 ),
10403 controller: TextEditingController(text: '2026-04-08'),
10404 ),
10405 ),
10406 ),
10407 const SizedBox(width: 12),
10408 Expanded(
10409 child: AdminFieldOverlay(
10410 fieldName: 'Due Date',
10411 fieldType: 'date',
10412 required: true,
10413 child: TextField(
10414 decoration: const InputDecoration(
10415 labelText: 'Due Date',
10416 border: OutlineInputBorder(),
10417 suffixIcon: Icon(Icons.calendar_today, size: 18),
10418 ),
10419 controller: TextEditingController(text: '2026-05-08'),
10420 ),
10421 ),
10422 ),
10423 const SizedBox(width: 12),
10424 Expanded(
10425 child: AdminFieldOverlay(
10426 fieldName: 'Status',
10427 fieldType: 'dropdown',
10428 child: DropdownButtonFormField<String>(
10429 decoration: const InputDecoration(
10430 labelText: 'Status',
10431 border: OutlineInputBorder(),
10432 isDense: true,
10433 ),
10434 value: 'draft',
10435 items: ['draft', 'sent', 'paid', 'overdue', 'cancelled']
10436 .map(
10437 (v) => DropdownMenuItem(value: v, child: Text(v)),
10438 )
10439 .toList(),
10440 onChanged: (_) {},
10441 ),
10442 ),
10443 ),
10444 ],
10445 ),
10446 const SizedBox(height: 20),
10447
10448 // Line items — sub-data table
10449 AdminFieldOverlay(
10450 fieldName: 'Line Items',
10451 fieldType: 'sub_table',
10452 rolePermissions: const {'sales': 'edit'},
10453 child: Column(
10454 children: [
10455 Row(
10456 children: [
10457 Text(
10458 'LINE ITEMS',
10459 style: TextStyle(
10460 fontSize: 10,
10461 fontWeight: FontWeight.bold,
10462 color: Colors.white38,
10463 letterSpacing: 1,
10464 ),
10465 ),
10466 const Spacer(),
10467 TextButton.icon(
10468 onPressed: () {},
10469 icon: const Icon(Icons.add, size: 16),
10470 label: const Text(
10471 'Add Line',
10472 style: TextStyle(fontSize: 12),
10473 ),
10474 ),
10475 ],
10476 ),
10477 const SizedBox(height: 8),
10478 Container(
10479 decoration: BoxDecoration(
10480 border: Border.all(color: Colors.white10),
10481 borderRadius: BorderRadius.circular(8),
10482 ),
10483 child: DataTable(
10484 headingRowHeight: 36,
10485 dataRowMinHeight: 40,
10486 dataRowMaxHeight: 40,
10487 columnSpacing: 16,
10488 headingTextStyle: TextStyle(
10489 fontSize: 12,
10490 fontWeight: FontWeight.bold,
10491 color: Colors.white54,
10492 ),
10493 dataTextStyle: const TextStyle(fontSize: 13),
10494 columns: const [
10495 DataColumn(label: Text('Product')),
10496 DataColumn(label: Text('Description')),
10497 DataColumn(label: Text('Qty'), numeric: true),
10498 DataColumn(label: Text('Unit Price'), numeric: true),
10499 DataColumn(label: Text('Total'), numeric: true),
10500 DataColumn(label: Text('')),
10501 ],
10502 rows: [
10503 _lineItem(
10504 'Web Hosting',
10505 'Annual plan — Pro tier',
10506 1,
10507 299.00,
10508 ),
10509 _lineItem(
10510 'SSL Certificate',
10511 'Wildcard, 1 year',
10512 2,
10513 79.00,
10514 ),
10515 _lineItem(
10516 'Support Hours',
10517 'Priority support block',
10518 10,
10519 150.00,
10520 ),
10521 ],
10522 ),
10523 ),
10524 ],
10525 ),
10526 ),
10527 const SizedBox(height: 12),
10528 // Totals
10529 Container(
10530 padding: const EdgeInsets.all(16),
10531 decoration: BoxDecoration(
10532 color: Theme.of(context).colorScheme.surfaceContainerLow,
10533 borderRadius: BorderRadius.circular(8),
10534 ),
10535 child: Column(
10536 children: [
10537 _totalRow('Subtotal', '\$1,957.00'),
10538 _totalRow('Tax (8.25%)', '\$161.45'),
10539 const Divider(),
10540 _totalRow('Total', '\$2,118.45', bold: true, large: true),
10541 ],
10542 ),
10543 ),
10544 const SizedBox(height: 16),
10545
10546 // Notes
10547 AdminFieldOverlay(
10548 fieldName: 'Notes',
10549 fieldType: 'textarea',
10550 rolePermissions: const {'sales': 'read'},
10551 child: TextField(
10552 maxLines: 2,
10553 decoration: const InputDecoration(
10554 labelText: 'Notes',
10555 border: OutlineInputBorder(),
10556 alignLabelWithHint: true,
10557 ),
10558 controller: TextEditingController(
10559 text:
10560 'Payment due within 30 days. Thank you for your business.',
10561 ),
10562 ),
10563 ),
10564 const SizedBox(height: 12),
10565
10566 // Ownership & permissions
10567 Container(
10568 padding: const EdgeInsets.all(12),
10569 decoration: BoxDecoration(
10570 color: Colors.white.withOpacity(0.03),
10571 borderRadius: BorderRadius.circular(8),
10572 border: Border.all(color: Colors.white10),
10573 ),
10574 child: Column(
10575 children: [
10576 Row(
10577 children: [
10578 Icon(
10579 Icons.person_outline,
10580 size: 16,
10581 color: Colors.white38,
10582 ),
10583 const SizedBox(width: 8),
10584 Text(
10585 'Owner: you',
10586 style: TextStyle(fontSize: 12, color: Colors.white38),
10587 ),
10588 const Spacer(),
10589 Text(
10590 'Access: ROLE-BASED',
10591 style: TextStyle(fontSize: 12, color: Colors.orange),
10592 ),
10593 ],
10594 ),
10595 const Divider(height: 16),
10596 Row(
10597 children: [
10598 Icon(Icons.visibility, size: 14, color: Colors.white24),
10599 const SizedBox(width: 6),
10600 Text(
10601 'Field Permissions (your role: admin)',
10602 style: TextStyle(fontSize: 11, color: Colors.white38),
10603 ),
10604 ],
10605 ),
10606 const SizedBox(height: 8),
10607 Wrap(
10608 spacing: 6,
10609 runSpacing: 4,
10610 children: [
10611 _permChip('Customer', true, true),
10612 _permChip('Dates', true, true),
10613 _permChip('Line Items', true, true),
10614 _permChip('Totals', true, false),
10615 _permChip('Notes', true, true),
10616 _permChip('Status', true, true),
10617 _permChip('Cost Price', false, false),
10618 _permChip('Margin', false, false),
10619 ],
10620 ),
10621 const SizedBox(height: 8),
10622 Row(
10623 children: [
10624 Icon(
10625 Icons.info_outline,
10626 size: 13,
10627 color: Colors.white24,
10628 ),
10629 const SizedBox(width: 6),
10630 Expanded(
10631 child: Text(
10632 '"sales" role cannot see Cost Price or Margin fields. Totals are read-only for non-admin.',
10633 style: TextStyle(
10634 fontSize: 11,
10635 color: Colors.white30,
10636 fontStyle: FontStyle.italic,
10637 ),
10638 ),
10639 ),
10640 ],
10641 ),
10642 ],
10643 ),
10644 ),
10645
10646 const SizedBox(height: 24),
10647
10648 // Actions
10649 Row(
10650 children: [
10651 FilledButton.icon(
10652 onPressed: () {},
10653 icon: const Icon(Icons.save, size: 18),
10654 label: const Text('Save'),
10655 ),
10656 const SizedBox(width: 8),
10657 OutlinedButton.icon(
10658 onPressed: () {},
10659 icon: const Icon(Icons.send, size: 16),
10660 label: const Text('Save & Send'),
10661 ),
10662 const SizedBox(width: 8),
10663 OutlinedButton.icon(
10664 onPressed: () {},
10665 icon: const Icon(Icons.picture_as_pdf, size: 16),
10666 label: const Text('PDF'),
10667 ),
10668 const SizedBox(width: 8),
10669 OutlinedButton.icon(
10670 onPressed: () {},
10671 icon: const Icon(Icons.print, size: 16),
10672 label: const Text('Print'),
10673 ),
10674 const Spacer(),
10675 TextButton.icon(
10676 onPressed: () {},
10677 icon: const Icon(
10678 Icons.auto_awesome,
10679 size: 16,
10680 color: Colors.amber,
10681 ),
10682 label: const Text(
10683 'AI Fill',
10684 style: TextStyle(color: Colors.amber),
10685 ),
10686 ),
10687 ],
10688 ),
10689 ],
10690 ),
10691 ),
10692 ),
10693 );
10694 }
10695
10696 DataRow _lineItem(String product, String desc, int qty, double price) {
10697 return DataRow(
10698 cells: [
10699 DataCell(Text(product)),
10700 DataCell(
10701 Text(desc, style: TextStyle(color: Colors.white54, fontSize: 12)),
10702 ),
10703 DataCell(Text('$qty')),
10704 DataCell(Text('\$${price.toStringAsFixed(2)}')),
10705 DataCell(
10706 Text(
10707 '\$${(qty * price).toStringAsFixed(2)}',
10708 style: TextStyle(fontWeight: FontWeight.bold),
10709 ),
10710 ),
10711 DataCell(
10712 IconButton(
10713 onPressed: () {},
10714 icon: const Icon(Icons.close, size: 14),
10715 visualDensity: VisualDensity.compact,
10716 ),
10717 ),
10718 ],
10719 );
10720 }
10721
10722 Widget _subDataRow(String label, String value) {
10723 return Padding(
10724 padding: const EdgeInsets.symmetric(vertical: 2),
10725 child: Row(
10726 crossAxisAlignment: CrossAxisAlignment.start,
10727 children: [
10728 SizedBox(
10729 width: 110,
10730 child: Text(
10731 label,
10732 style: TextStyle(fontSize: 12, color: Colors.white38),
10733 ),
10734 ),
10735 Expanded(child: Text(value, style: const TextStyle(fontSize: 13))),
10736 ],
10737 ),
10738 );
10739 }
10740
10741 Widget _totalRow(
10742 String label,
10743 String value, {
10744 bool bold = false,
10745 bool large = false,
10746 }) {
10747 return Padding(
10748 padding: const EdgeInsets.symmetric(vertical: 2),
10749 child: Row(
10750 children: [
10751 Text(
10752 label,
10753 style: TextStyle(
10754 fontSize: large ? 15 : 13,
10755 fontWeight: bold ? FontWeight.bold : FontWeight.normal,
10756 ),
10757 ),
10758 const Spacer(),
10759 Text(
10760 value,
10761 style: TextStyle(
10762 fontSize: large ? 18 : 13,
10763 fontWeight: bold ? FontWeight.bold : FontWeight.normal,
10764 color: bold ? Colors.green[300] : null,
10765 ),
10766 ),
10767 ],
10768 ),
10769 );
10770 }
10771
10772 Widget _permChip(String field, bool canView, bool canEdit) {
10773 final color = !canView
10774 ? Colors.red
10775 : (canEdit ? Colors.green : Colors.orange);
10776 final label = !canView ? 'hidden' : (canEdit ? 'edit' : 'read');
10777 return Container(
10778 padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
10779 decoration: BoxDecoration(
10780 color: color.withOpacity(0.1),
10781 borderRadius: BorderRadius.circular(4),
10782 border: Border.all(color: color.withOpacity(0.3)),
10783 ),
10784 child: Text.rich(
10785 TextSpan(
10786 children: [
10787 TextSpan(
10788 text: '$field ',
10789 style: TextStyle(fontSize: 11, color: Colors.white70),
10790 ),
10791 TextSpan(
10792 text: label,
10793 style: TextStyle(
10794 fontSize: 10,
10795 color: color,
10796 fontWeight: FontWeight.bold,
10797 ),
10798 ),
10799 ],
10800 ),
10801 ),
10802 );
10803 }
10804}
10805
10806// ---------------------------------------------------------------------------
10807// Placeholder
10808// ---------------------------------------------------------------------------
10809
10810// ---------------------------------------------------------------------------
10811// Schema Editor (admin read-only schema inspection)
10812// ---------------------------------------------------------------------------
10813
10814class SchemaEditorView extends StatefulWidget {
10815 const SchemaEditorView({super.key});
10816
10817 @override
10818 State<SchemaEditorView> createState() => _SchemaEditorViewState();
10819}
10820
10821class _SchemaEditorViewState extends State<SchemaEditorView> {
10822 List<Map<String, dynamic>> _schemas = [];
10823 String? _selectedSchema;
10824 Map<String, dynamic>? _schemaDetail;
10825 List<dynamic> _versions = [];
10826 dynamic _versionDetail;
10827 int? _selectedVersionNumber;
10828 String _tab = 'Fields';
10829 bool _loading = true;
10830 bool _detailLoading = false;
10831 bool _versionLoading = false;
10832 bool _writing = false;
10833 Map<String, dynamic>? _writeResponse;
10834 String? _error;
10835
10836 @override
10837 void initState() {
10838 super.initState();
10839 _loadSchemas();
10840 }
10841
10842 Future<void> _loadSchemas() async {
10843 setState(() {
10844 _loading = true;
10845 _error = null;
10846 });
10847 try {
10848 final raw = await ScrollAPI().listAdminSchemas();
10849 final schemas = raw
10850 .map(_mapFromDynamic)
10851 .where((schema) => _schemaName(schema).isNotEmpty)
10852 .toList();
10853 final current = _selectedSchema;
10854 final selected = schemas.any((item) => _schemaName(item) == current)
10855 ? current
10856 : (schemas.isNotEmpty ? _schemaName(schemas.first) : null);
10857 if (!mounted) return;
10858 setState(() {
10859 _schemas = schemas;
10860 _selectedSchema = selected;
10861 _loading = false;
10862 });
10863 if (selected != null) await _loadSchema(selected);
10864 } catch (e) {
10865 if (!mounted) return;
10866 setState(() {
10867 _loading = false;
10868 _error = e.toString();
10869 });
10870 }
10871 }
10872
10873 Future<void> _loadSchema(String schema) async {
10874 setState(() {
10875 _detailLoading = true;
10876 _schemaDetail = null;
10877 _versions = [];
10878 _versionDetail = null;
10879 _selectedVersionNumber = null;
10880 });
10881 final api = ScrollAPI();
10882 final responses = await Future.wait<dynamic>([
10883 api.getAdminSchema(schema),
10884 api.getAdminSchemaVersions(schema, limit: 10),
10885 ]);
10886 if (!mounted) return;
10887 setState(() {
10888 _schemaDetail = _mapOrNull(responses[0]);
10889 _versions = responses[1] is List ? responses[1] as List : const [];
10890 _detailLoading = false;
10891 });
10892 }
10893
10894 Future<void> _selectSchema(String schema) async {
10895 setState(() {
10896 _selectedSchema = schema;
10897 _tab = 'Fields';
10898 });
10899 await _loadSchema(schema);
10900 }
10901
10902 Future<void> _loadVersion(dynamic rawVersion) async {
10903 final schema = _selectedSchema;
10904 final version = _versionNumber(rawVersion);
10905 if (schema == null || version == null) {
10906 setState(() {
10907 _versionDetail = rawVersion;
10908 _selectedVersionNumber = null;
10909 });
10910 return;
10911 }
10912 setState(() {
10913 _versionLoading = true;
10914 _versionDetail = null;
10915 _selectedVersionNumber = version;
10916 });
10917 final detail = await ScrollAPI().getAdminSchemaVersion(schema, version);
10918 if (!mounted) return;
10919 setState(() {
10920 _versionDetail = detail ?? rawVersion;
10921 _versionLoading = false;
10922 });
10923 }
10924
10925 Future<void> _showEditSchemaDialog() async {
10926 final schema = _selectedSchema;
10927 if (schema == null) return;
10928 final detail = _schemaDetail ?? const <String, dynamic>{};
10929 final schemaBody = detail['schema'] is Map
10930 ? _mapFromDynamic(detail['schema'])
10931 : detail;
10932 final schemaController = TextEditingController(
10933 text: const JsonEncoder.withIndent(' ').convert(schemaBody),
10934 );
10935 final authorController = TextEditingController(text: 'scroll-operator');
10936 final messageController = TextEditingController();
10937 String? parseError;
10938 final submitted = await showDialog<Map<String, dynamic>>(
10939 context: context,
10940 builder: (dialogContext) {
10941 return StatefulBuilder(
10942 builder: (dialogContext, setDialogState) {
10943 return AlertDialog(
10944 title: Text('Edit $schema schema'),
10945 content: SizedBox(
10946 width: 680,
10947 height: 520,
10948 child: Column(
10949 children: [
10950 Expanded(
10951 child: TextField(
10952 controller: schemaController,
10953 maxLines: null,
10954 expands: true,
10955 decoration: const InputDecoration(
10956 alignLabelWithHint: true,
10957 border: OutlineInputBorder(),
10958 labelText: 'Schema JSON',
10959 ),
10960 style: const TextStyle(
10961 fontFamily: 'monospace',
10962 fontSize: 12,
10963 height: 1.35,
10964 ),
10965 ),
10966 ),
10967 const SizedBox(height: 10),
10968 Row(
10969 children: [
10970 Expanded(
10971 child: TextField(
10972 controller: authorController,
10973 decoration: const InputDecoration(
10974 border: OutlineInputBorder(),
10975 labelText: 'Author',
10976 isDense: true,
10977 ),
10978 ),
10979 ),
10980 const SizedBox(width: 10),
10981 Expanded(
10982 flex: 2,
10983 child: TextField(
10984 controller: messageController,
10985 decoration: const InputDecoration(
10986 border: OutlineInputBorder(),
10987 labelText: 'Message',
10988 isDense: true,
10989 ),
10990 ),
10991 ),
10992 ],
10993 ),
10994 if (parseError != null) ...[
10995 const SizedBox(height: 8),
10996 Align(
10997 alignment: Alignment.centerLeft,
10998 child: Text(
10999 parseError!,
11000 style: TextStyle(
11001 fontSize: 12,
11002 color: Colors.red[300],
11003 ),
11004 ),
11005 ),
11006 ],
11007 ],
11008 ),
11009 ),
11010 actions: [
11011 TextButton(
11012 onPressed: () => Navigator.of(dialogContext).pop(null),
11013 child: const Text('Cancel'),
11014 ),
11015 FilledButton.icon(
11016 onPressed: () {
11017 try {
11018 final decoded =
11019 jsonDecode(schemaController.text) as Object?;
11020 if (decoded is! Map<String, dynamic>) {
11021 setDialogState(
11022 () => parseError = 'Schema JSON must be an object',
11023 );
11024 return;
11025 }
11026 Navigator.of(dialogContext).pop(decoded);
11027 } catch (e) {
11028 setDialogState(() => parseError = 'Invalid JSON: $e');
11029 }
11030 },
11031 icon: const Icon(Icons.save_outlined, size: 16),
11032 label: const Text('Save Schema'),
11033 ),
11034 ],
11035 );
11036 },
11037 );
11038 },
11039 );
11040 final author = authorController.text;
11041 final message = messageController.text;
11042 schemaController.dispose();
11043 authorController.dispose();
11044 messageController.dispose();
11045 if (submitted == null || !mounted) return;
11046 await _runSchemaWrite(
11047 () => ScrollAPI().updateAdminSchema(
11048 schema,
11049 schema: submitted,
11050 author: author,
11051 message: message,
11052 ),
11053 );
11054 }
11055
11056 Future<void> _confirmRollbackSchema() async {
11057 final schema = _selectedSchema;
11058 final version = _selectedVersionNumber;
11059 if (schema == null || version == null) return;
11060 final confirmed = await showDialog<bool>(
11061 context: context,
11062 builder: (dialogContext) {
11063 return AlertDialog(
11064 title: const Text('Rollback schema?'),
11065 content: Text(
11066 'POST /admin/schemas/$schema with '
11067 '{"action": "rollback", "version_id": $version}\n\n'
11068 'The restored schema is recorded as a new schema version.',
11069 ),
11070 actions: [
11071 TextButton(
11072 onPressed: () => Navigator.of(dialogContext).pop(false),
11073 child: const Text('Cancel'),
11074 ),
11075 FilledButton.icon(
11076 style: FilledButton.styleFrom(
11077 backgroundColor: Colors.orange[800],
11078 ),
11079 onPressed: () => Navigator.of(dialogContext).pop(true),
11080 icon: const Icon(Icons.history, size: 16),
11081 label: Text('Rollback to v$version'),
11082 ),
11083 ],
11084 );
11085 },
11086 );
11087 if (confirmed != true || !mounted) return;
11088 await _runSchemaWrite(
11089 () => ScrollAPI().rollbackAdminSchema(schema, version),
11090 );
11091 }
11092
11093 Future<void> _runSchemaWrite(
11094 Future<Map<String, dynamic>> Function() write,
11095 ) async {
11096 final schema = _selectedSchema;
11097 if (schema == null) return;
11098 setState(() {
11099 _writing = true;
11100 _writeResponse = null;
11101 });
11102 final result = await write();
11103 if (!mounted) return;
11104 setState(() {
11105 _writing = false;
11106 _writeResponse = result;
11107 });
11108 await _loadSchema(schema);
11109 }
11110
11111 @override
11112 Widget build(BuildContext context) {
11113 return Row(
11114 children: [
11115 Container(
11116 width: 240,
11117 color: Theme.of(context).colorScheme.surfaceContainerLow,
11118 child: Column(
11119 crossAxisAlignment: CrossAxisAlignment.start,
11120 children: [
11121 Padding(
11122 padding: const EdgeInsets.fromLTRB(16, 12, 8, 8),
11123 child: Row(
11124 children: [
11125 Text(
11126 'SCHEMAS',
11127 style: TextStyle(
11128 fontSize: 10,
11129 fontWeight: FontWeight.bold,
11130 color: Colors.white38,
11131 letterSpacing: 1,
11132 ),
11133 ),
11134 const Spacer(),
11135 Text(
11136 '${_schemas.length}',
11137 style: TextStyle(fontSize: 11, color: Colors.white38),
11138 ),
11139 IconButton(
11140 onPressed: _loading ? null : _loadSchemas,
11141 icon: const Icon(Icons.refresh, size: 16),
11142 tooltip: 'Refresh',
11143 visualDensity: VisualDensity.compact,
11144 ),
11145 ],
11146 ),
11147 ),
11148 Expanded(
11149 child: _loading
11150 ? const Center(child: CircularProgressIndicator())
11151 : _error != null
11152 ? Center(
11153 child: Padding(
11154 padding: const EdgeInsets.all(16),
11155 child: Text(
11156 'Failed to load schemas',
11157 style: TextStyle(color: Colors.red[300]),
11158 ),
11159 ),
11160 )
11161 : ListView.builder(
11162 padding: const EdgeInsets.symmetric(horizontal: 4),
11163 itemCount: _schemas.length,
11164 itemBuilder: (context, index) {
11165 final schema = _schemas[index];
11166 final name = _schemaName(schema);
11167 final selected = name == _selectedSchema;
11168 return ListTile(
11169 dense: true,
11170 selected: selected,
11171 selectedTileColor: Theme.of(context)
11172 .colorScheme
11173 .primaryContainer
11174 .withValues(alpha: 0.2),
11175 leading: Icon(
11176 Icons.schema_outlined,
11177 size: 18,
11178 color: selected
11179 ? Theme.of(context).colorScheme.primary
11180 : Colors.white38,
11181 ),
11182 title: Text(
11183 name,
11184 overflow: TextOverflow.ellipsis,
11185 style: const TextStyle(
11186 fontSize: 13,
11187 fontFamily: 'monospace',
11188 ),
11189 ),
11190 trailing: Text(
11191 _schemaCount(schema),
11192 style: TextStyle(
11193 fontSize: 11,
11194 color: Colors.white38,
11195 ),
11196 ),
11197 onTap: () => _selectSchema(name),
11198 );
11199 },
11200 ),
11201 ),
11202 ],
11203 ),
11204 ),
11205 Container(width: 1, color: Colors.white10),
11206 Expanded(child: _buildDetail(context)),
11207 ],
11208 );
11209 }
11210
11211 Widget _buildDetail(BuildContext context) {
11212 final schema = _selectedSchema;
11213 if (schema == null) {
11214 return Center(
11215 child: Text('No schemas', style: TextStyle(color: Colors.white38)),
11216 );
11217 }
11218 return Column(
11219 children: [
11220 Container(
11221 height: 52,
11222 padding: const EdgeInsets.symmetric(horizontal: 16),
11223 decoration: BoxDecoration(
11224 border: Border(bottom: BorderSide(color: Colors.white10)),
11225 ),
11226 child: Row(
11227 children: [
11228 Icon(Icons.schema_outlined, size: 18, color: Colors.purple),
11229 const SizedBox(width: 8),
11230 Text(
11231 schema,
11232 style: const TextStyle(
11233 fontSize: 15,
11234 fontWeight: FontWeight.bold,
11235 fontFamily: 'monospace',
11236 ),
11237 ),
11238 const SizedBox(width: 10),
11239 _chip('SCHEMA WRITES ADMIN', Colors.orange),
11240 const SizedBox(width: 18),
11241 ..._tabButton('Overview'),
11242 ..._tabButton('Fields'),
11243 ..._tabButton('Versions'),
11244 const Spacer(),
11245 Tooltip(
11246 message: 'Replace through PUT /admin/schemas/$schema',
11247 child: FilledButton.icon(
11248 onPressed: _writing ? null : _showEditSchemaDialog,
11249 icon: _writing
11250 ? const SizedBox(
11251 width: 14,
11252 height: 14,
11253 child: CircularProgressIndicator(strokeWidth: 2),
11254 )
11255 : const Icon(Icons.edit, size: 16),
11256 label: const Text('Edit Schema'),
11257 ),
11258 ),
11259 ],
11260 ),
11261 ),
11262 if (_writeResponse != null) _writeResponsePanel(),
11263 Expanded(
11264 child: _detailLoading
11265 ? const Center(child: CircularProgressIndicator())
11266 : switch (_tab) {
11267 'Overview' => _buildOverviewTab(context),
11268 'Versions' => _buildVersionsTab(context),
11269 _ => _buildFieldsTab(context),
11270 },
11271 ),
11272 ],
11273 );
11274 }
11275
11276 Widget _writeResponsePanel() {
11277 final response = _writeResponse ?? const <String, dynamic>{};
11278 final status = response['status'];
11279 final ok = status is int && status >= 200 && status < 300;
11280 final color = ok ? Colors.green : Colors.red;
11281 return Container(
11282 width: double.infinity,
11283 margin: const EdgeInsets.fromLTRB(16, 12, 16, 0),
11284 padding: const EdgeInsets.all(10),
11285 decoration: BoxDecoration(
11286 color: color.withValues(alpha: 0.06),
11287 borderRadius: BorderRadius.circular(8),
11288 border: Border.all(color: color.withValues(alpha: 0.18)),
11289 ),
11290 child: Row(
11291 crossAxisAlignment: CrossAxisAlignment.start,
11292 children: [
11293 Expanded(
11294 child: SelectableText(
11295 const JsonEncoder.withIndent(' ').convert(response),
11296 maxLines: 6,
11297 style: const TextStyle(
11298 fontFamily: 'monospace',
11299 fontSize: 11,
11300 height: 1.3,
11301 ),
11302 ),
11303 ),
11304 IconButton(
11305 onPressed: () => setState(() => _writeResponse = null),
11306 icon: const Icon(Icons.close, size: 14),
11307 tooltip: 'Dismiss',
11308 visualDensity: VisualDensity.compact,
11309 ),
11310 ],
11311 ),
11312 );
11313 }
11314
11315 List<Widget> _tabButton(String label) {
11316 final active = _tab == label;
11317 return [
11318 InkWell(
11319 onTap: () => setState(() => _tab = label),
11320 borderRadius: BorderRadius.circular(6),
11321 child: Container(
11322 padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
11323 decoration: BoxDecoration(
11324 color: active
11325 ? Theme.of(context).colorScheme.primary.withValues(alpha: 0.2)
11326 : Colors.transparent,
11327 borderRadius: BorderRadius.circular(6),
11328 ),
11329 child: Text(
11330 label,
11331 style: TextStyle(
11332 fontSize: 11,
11333 color: active
11334 ? Theme.of(context).colorScheme.primary
11335 : Colors.white38,
11336 fontWeight: active ? FontWeight.bold : FontWeight.normal,
11337 ),
11338 ),
11339 ),
11340 ),
11341 const SizedBox(width: 2),
11342 ];
11343 }
11344
11345 Widget _buildOverviewTab(BuildContext context) {
11346 Map<String, dynamic>? selected;
11347 for (final item in _schemas) {
11348 if (_schemaName(item) == _selectedSchema) {
11349 selected = item;
11350 break;
11351 }
11352 }
11353 final detail = _schemaDetail ?? const <String, dynamic>{};
11354 final fields = _schemaFields(detail);
11355 return SingleChildScrollView(
11356 padding: const EdgeInsets.all(16),
11357 child: Column(
11358 crossAxisAlignment: CrossAxisAlignment.start,
11359 children: [
11360 Wrap(
11361 spacing: 12,
11362 runSpacing: 12,
11363 children: [
11364 _metric(
11365 Icons.view_column_outlined,
11366 'Fields',
11367 '${fields.length}',
11368 Colors.purple,
11369 ),
11370 _metric(
11371 Icons.history_outlined,
11372 'Versions',
11373 '${_versions.length}',
11374 Colors.blue,
11375 ),
11376 _metric(
11377 Icons.shield_outlined,
11378 'Access',
11379 _valueText(detail['access'] ?? detail['mode'] ?? 'admin'),
11380 Colors.green,
11381 ),
11382 ],
11383 ),
11384 const SizedBox(height: 16),
11385 LayoutBuilder(
11386 builder: (context, constraints) {
11387 final cards = [
11388 _infoCard(
11389 context,
11390 'Schema List Row',
11391 Icons.list_alt_outlined,
11392 Colors.purple,
11393 _orderedRows(selected ?? const {}),
11394 ),
11395 _infoCard(
11396 context,
11397 'Schema Detail',
11398 Icons.info_outline,
11399 Colors.blue,
11400 _orderedRows(detail),
11401 ),
11402 ];
11403 if (constraints.maxWidth < 900) {
11404 return Column(
11405 children: [
11406 cards.first,
11407 const SizedBox(height: 12),
11408 cards.last,
11409 ],
11410 );
11411 }
11412 return Row(
11413 crossAxisAlignment: CrossAxisAlignment.start,
11414 children: [
11415 Expanded(child: cards.first),
11416 const SizedBox(width: 12),
11417 Expanded(child: cards.last),
11418 ],
11419 );
11420 },
11421 ),
11422 const SizedBox(height: 16),
11423 _rawPanel('Raw schema payload', {
11424 if (selected != null) 'list_row': selected,
11425 if (detail.isNotEmpty) 'detail': detail,
11426 }),
11427 ],
11428 ),
11429 );
11430 }
11431
11432 Widget _buildFieldsTab(BuildContext context) {
11433 final fields = _schemaFields(_schemaDetail ?? const {});
11434 return Container(
11435 color: Colors.black26,
11436 padding: const EdgeInsets.all(16),
11437 child: _framed(
11438 context,
11439 title: 'Fields',
11440 icon: Icons.view_column_outlined,
11441 color: Colors.purple,
11442 trailing: _chip('${fields.length}', Colors.purple),
11443 child: fields.isEmpty
11444 ? Center(
11445 child: Text(
11446 'No fields',
11447 style: TextStyle(color: Colors.white38),
11448 ),
11449 )
11450 : SingleChildScrollView(
11451 child: SingleChildScrollView(
11452 scrollDirection: Axis.horizontal,
11453 child: DataTable(
11454 headingRowHeight: 36,
11455 dataRowMinHeight: 42,
11456 dataRowMaxHeight: 52,
11457 columnSpacing: 24,
11458 headingTextStyle: TextStyle(
11459 fontSize: 12,
11460 fontWeight: FontWeight.bold,
11461 color: Colors.white54,
11462 ),
11463 columns: const [
11464 DataColumn(label: Text('Field')),
11465 DataColumn(label: Text('Type')),
11466 DataColumn(label: Text('Required')),
11467 DataColumn(label: Text('Relation')),
11468 DataColumn(label: Text('Validation')),
11469 ],
11470 rows: fields.map((field) {
11471 final name = _fieldValue(field, const ['name', 'field']);
11472 final type = _fieldValue(field, const [
11473 'type',
11474 'field_type',
11475 'kind',
11476 ], fallback: '?');
11477 final required = _boolValue(
11478 field['required'] ?? field['nullable'] == false,
11479 );
11480 final relation = _fieldValue(field, const [
11481 'relation',
11482 'references',
11483 'ref',
11484 'foreign_key',
11485 ]);
11486 final validation = _fieldValue(field, const [
11487 'validation',
11488 'constraints',
11489 'rule',
11490 'rules',
11491 ]);
11492 final typeColor = _typeColor(type);
11493 return DataRow(
11494 cells: [
11495 DataCell(
11496 Text(
11497 name,
11498 style: const TextStyle(
11499 fontFamily: 'monospace',
11500 fontSize: 13,
11501 ),
11502 ),
11503 ),
11504 DataCell(_chip(type, typeColor)),
11505 DataCell(
11506 required
11507 ? Icon(
11508 Icons.check,
11509 size: 16,
11510 color: Colors.green,
11511 )
11512 : Icon(
11513 Icons.remove,
11514 size: 16,
11515 color: Colors.white24,
11516 ),
11517 ),
11518 DataCell(
11519 Text(
11520 relation.isEmpty ? '-' : relation,
11521 style: TextStyle(
11522 color: relation.isEmpty
11523 ? Colors.white24
11524 : Colors.blue,
11525 ),
11526 ),
11527 ),
11528 DataCell(
11529 Text(
11530 validation.isEmpty ? '-' : validation,
11531 maxLines: 2,
11532 overflow: TextOverflow.ellipsis,
11533 style: TextStyle(
11534 fontSize: 12,
11535 color: Colors.white54,
11536 ),
11537 ),
11538 ),
11539 ],
11540 );
11541 }).toList(),
11542 ),
11543 ),
11544 ),
11545 ),
11546 );
11547 }
11548
11549 Widget _buildVersionsTab(BuildContext context) {
11550 return Padding(
11551 padding: const EdgeInsets.all(16),
11552 child: LayoutBuilder(
11553 builder: (context, constraints) {
11554 final list = _framed(
11555 context,
11556 title: 'Versions',
11557 icon: Icons.history_outlined,
11558 color: Colors.blue,
11559 trailing: _chip('${_versions.length}', Colors.blue),
11560 child: _versions.isEmpty
11561 ? Center(
11562 child: Text(
11563 'No versions',
11564 style: TextStyle(color: Colors.white38),
11565 ),
11566 )
11567 : ListView.separated(
11568 itemCount: _versions.length,
11569 separatorBuilder: (_, __) => const SizedBox(height: 8),
11570 itemBuilder: (context, index) {
11571 final version = _mapFromDynamic(_versions[index]);
11572 final label = _versionLabel(version);
11573 final created = _fieldValue(version, const [
11574 'created_at',
11575 'timestamp',
11576 'date',
11577 ]);
11578 return InkWell(
11579 borderRadius: BorderRadius.circular(6),
11580 onTap: () => _loadVersion(_versions[index]),
11581 child: Container(
11582 padding: const EdgeInsets.all(10),
11583 decoration: BoxDecoration(
11584 color: Colors.white.withValues(alpha: 0.03),
11585 borderRadius: BorderRadius.circular(6),
11586 border: Border.all(color: Colors.white10),
11587 ),
11588 child: Row(
11589 children: [
11590 _chip(label, Colors.blue),
11591 const SizedBox(width: 10),
11592 Expanded(
11593 child: Text(
11594 created.isEmpty ? 'version detail' : created,
11595 overflow: TextOverflow.ellipsis,
11596 style: TextStyle(
11597 fontSize: 12,
11598 color: Colors.white54,
11599 ),
11600 ),
11601 ),
11602 ],
11603 ),
11604 ),
11605 );
11606 },
11607 ),
11608 );
11609 final detail = _framed(
11610 context,
11611 title: 'Version Detail',
11612 icon: Icons.info_outline,
11613 color: Colors.purple,
11614 trailing: Tooltip(
11615 message:
11616 'Restore through POST /admin/schemas/{collection} with action=rollback',
11617 child: OutlinedButton.icon(
11618 onPressed: !_writing && _selectedVersionNumber != null
11619 ? _confirmRollbackSchema
11620 : null,
11621 icon: const Icon(Icons.history, size: 14),
11622 label: Text(
11623 _selectedVersionNumber == null
11624 ? 'Rollback'
11625 : 'Rollback to v$_selectedVersionNumber',
11626 ),
11627 ),
11628 ),
11629 child: _versionLoading
11630 ? const Center(child: CircularProgressIndicator())
11631 : _versionDetail == null
11632 ? Center(
11633 child: Text(
11634 'No version selected',
11635 style: TextStyle(color: Colors.white38),
11636 ),
11637 )
11638 : SingleChildScrollView(
11639 child: SelectableText(
11640 const JsonEncoder.withIndent(
11641 ' ',
11642 ).convert(_versionDetail),
11643 style: const TextStyle(
11644 fontFamily: 'monospace',
11645 fontSize: 11,
11646 height: 1.35,
11647 ),
11648 ),
11649 ),
11650 );
11651 if (constraints.maxWidth < 860) {
11652 return Column(
11653 children: [
11654 Expanded(child: list),
11655 const SizedBox(height: 12),
11656 Expanded(child: detail),
11657 ],
11658 );
11659 }
11660 return Row(
11661 children: [
11662 SizedBox(width: 360, child: list),
11663 const SizedBox(width: 12),
11664 Expanded(child: detail),
11665 ],
11666 );
11667 },
11668 ),
11669 );
11670 }
11671
11672 Widget _metric(IconData icon, String label, String value, Color color) {
11673 return Container(
11674 width: 150,
11675 padding: const EdgeInsets.all(12),
11676 decoration: BoxDecoration(
11677 color: color.withValues(alpha: 0.08),
11678 borderRadius: BorderRadius.circular(8),
11679 border: Border.all(color: color.withValues(alpha: 0.2)),
11680 ),
11681 child: Row(
11682 children: [
11683 Icon(icon, size: 18, color: color),
11684 const SizedBox(width: 8),
11685 Expanded(
11686 child: Column(
11687 crossAxisAlignment: CrossAxisAlignment.start,
11688 children: [
11689 Text(
11690 label,
11691 overflow: TextOverflow.ellipsis,
11692 style: TextStyle(fontSize: 11, color: Colors.white38),
11693 ),
11694 Text(
11695 value,
11696 overflow: TextOverflow.ellipsis,
11697 style: const TextStyle(
11698 fontSize: 15,
11699 fontWeight: FontWeight.w600,
11700 ),
11701 ),
11702 ],
11703 ),
11704 ),
11705 ],
11706 ),
11707 );
11708 }
11709
11710 Widget _infoCard(
11711 BuildContext context,
11712 String title,
11713 IconData icon,
11714 Color color,
11715 List<MapEntry<String, dynamic>> rows,
11716 ) {
11717 return _framed(
11718 context,
11719 title: title,
11720 icon: icon,
11721 color: color,
11722 trailing: _chip(rows.isEmpty ? 'EMPTY' : 'READ ONLY', color),
11723 expandChild: false,
11724 child: rows.isEmpty
11725 ? Text('Not reported', style: TextStyle(color: Colors.white38))
11726 : Column(
11727 children: rows.map((entry) {
11728 return _infoRow(entry.key, entry.value);
11729 }).toList(),
11730 ),
11731 );
11732 }
11733
11734 Widget _framed(
11735 BuildContext context, {
11736 required String title,
11737 required IconData icon,
11738 required Color color,
11739 required Widget child,
11740 Widget? trailing,
11741 bool expandChild = true,
11742 }) {
11743 return Container(
11744 padding: const EdgeInsets.all(14),
11745 decoration: BoxDecoration(
11746 color: Theme.of(context).colorScheme.surfaceContainerLow,
11747 borderRadius: BorderRadius.circular(8),
11748 border: Border.all(color: Colors.white10),
11749 ),
11750 child: Column(
11751 crossAxisAlignment: CrossAxisAlignment.start,
11752 children: [
11753 Row(
11754 children: [
11755 Icon(icon, size: 18, color: color),
11756 const SizedBox(width: 8),
11757 Text(
11758 title,
11759 style: const TextStyle(
11760 fontSize: 13,
11761 fontWeight: FontWeight.w700,
11762 ),
11763 ),
11764 const Spacer(),
11765 if (trailing != null) trailing,
11766 ],
11767 ),
11768 const SizedBox(height: 12),
11769 if (expandChild) Expanded(child: child) else child,
11770 ],
11771 ),
11772 );
11773 }
11774
11775 Widget _infoRow(String label, dynamic value) {
11776 return Padding(
11777 padding: const EdgeInsets.only(bottom: 7),
11778 child: Row(
11779 crossAxisAlignment: CrossAxisAlignment.start,
11780 children: [
11781 Expanded(
11782 flex: 5,
11783 child: Text(
11784 _titleCase(label),
11785 overflow: TextOverflow.ellipsis,
11786 style: TextStyle(fontSize: 12, color: Colors.white54),
11787 ),
11788 ),
11789 const SizedBox(width: 10),
11790 Expanded(
11791 flex: 7,
11792 child: Text(
11793 _valueText(value),
11794 maxLines: 3,
11795 overflow: TextOverflow.ellipsis,
11796 textAlign: TextAlign.right,
11797 style: TextStyle(
11798 fontSize: 12,
11799 color: Colors.white70,
11800 fontWeight: FontWeight.w600,
11801 ),
11802 ),
11803 ),
11804 ],
11805 ),
11806 );
11807 }
11808
11809 Widget _rawPanel(String title, Map<String, dynamic> value) {
11810 return ExpansionTile(
11811 tilePadding: const EdgeInsets.symmetric(horizontal: 4),
11812 title: Text(title, style: TextStyle(fontSize: 12, color: Colors.white54)),
11813 children: [
11814 Container(
11815 width: double.infinity,
11816 padding: const EdgeInsets.all(12),
11817 decoration: BoxDecoration(
11818 color: Colors.black26,
11819 borderRadius: BorderRadius.circular(8),
11820 border: Border.all(color: Colors.white10),
11821 ),
11822 child: SelectableText(
11823 const JsonEncoder.withIndent(' ').convert(value),
11824 style: const TextStyle(
11825 fontFamily: 'monospace',
11826 fontSize: 11,
11827 height: 1.35,
11828 ),
11829 ),
11830 ),
11831 ],
11832 );
11833 }
11834
11835 Widget _chip(String text, Color color) {
11836 return Container(
11837 padding: const EdgeInsets.symmetric(horizontal: 7, vertical: 2),
11838 decoration: BoxDecoration(
11839 color: color.withValues(alpha: 0.1),
11840 borderRadius: BorderRadius.circular(4),
11841 border: Border.all(color: color.withValues(alpha: 0.16)),
11842 ),
11843 child: Text(
11844 _short(text, 44),
11845 overflow: TextOverflow.ellipsis,
11846 style: TextStyle(
11847 fontSize: 10,
11848 color: color,
11849 fontWeight: FontWeight.bold,
11850 ),
11851 ),
11852 );
11853 }
11854
11855 List<Map<String, dynamic>> _schemaFields(Map<String, dynamic> schema) {
11856 final candidate =
11857 schema['fields'] ??
11858 schema['columns'] ??
11859 schema['properties'] ??
11860 _mapFromDynamic(schema['schema'])['fields'];
11861 if (candidate is Map) {
11862 return candidate.entries.map((entry) {
11863 final value = _mapFromDynamic(entry.value);
11864 return {'name': entry.key.toString(), ...value};
11865 }).toList();
11866 }
11867 if (candidate is List) {
11868 return candidate.map((field) {
11869 final map = _mapFromDynamic(field);
11870 return map['name'] == null && map['field'] == null
11871 ? {'name': field.toString()}
11872 : map;
11873 }).toList();
11874 }
11875 return const [];
11876 }
11877
11878 List<MapEntry<String, dynamic>> _orderedRows(Map<String, dynamic> values) {
11879 final preferred = [
11880 'name',
11881 'collection',
11882 'id',
11883 'version',
11884 'fields_count',
11885 'field_count',
11886 'created_at',
11887 'updated_at',
11888 'description',
11889 ];
11890 final rows = <MapEntry<String, dynamic>>[];
11891 final used = <String>{};
11892 for (final key in preferred) {
11893 final value = values[key];
11894 if (_hasValue(value)) {
11895 rows.add(MapEntry(key, value));
11896 used.add(key);
11897 }
11898 }
11899 for (final entry in values.entries) {
11900 if (used.contains(entry.key) || !_hasValue(entry.value)) continue;
11901 rows.add(entry);
11902 }
11903 return rows.take(12).toList();
11904 }
11905
11906 Map<String, dynamic> _mapFromDynamic(dynamic value) {
11907 if (value is Map<String, dynamic>) return value;
11908 if (value is Map) {
11909 return value.map((key, item) => MapEntry(key.toString(), item));
11910 }
11911 if (value is String) return {'name': value};
11912 return {'value': value};
11913 }
11914
11915 Map<String, dynamic>? _mapOrNull(dynamic value) {
11916 if (value == null) return null;
11917 return _mapFromDynamic(value);
11918 }
11919
11920 String _schemaName(Map<String, dynamic> value) {
11921 final raw =
11922 value['collection'] ?? value['schema'] ?? value['name'] ?? value['id'];
11923 if (raw is Map) return _schemaName(_mapFromDynamic(raw));
11924 return raw?.toString() ?? '';
11925 }
11926
11927 String _schemaCount(Map<String, dynamic> value) {
11928 final raw =
11929 value['field_count'] ??
11930 value['fields_count'] ??
11931 value['count'] ??
11932 value['total'];
11933 return raw == null ? '' : raw.toString();
11934 }
11935
11936 String _fieldValue(
11937 Map<String, dynamic> value,
11938 List<String> keys, {
11939 String fallback = '',
11940 }) {
11941 for (final key in keys) {
11942 final raw = value[key];
11943 if (!_hasValue(raw)) continue;
11944 return _valueText(raw);
11945 }
11946 return fallback;
11947 }
11948
11949 bool _boolValue(dynamic value) {
11950 if (value is bool) return value;
11951 if (value is num) return value != 0;
11952 if (value is String) {
11953 final normalized = value.toLowerCase();
11954 return normalized == 'true' ||
11955 normalized == 'yes' ||
11956 normalized == 'required';
11957 }
11958 return false;
11959 }
11960
11961 int? _versionNumber(dynamic raw) {
11962 final map = _mapFromDynamic(raw);
11963 final value =
11964 map['version'] ?? map['id'] ?? map['version_id'] ?? map['revision'];
11965 if (value is int) return value;
11966 final text = value?.toString() ?? raw.toString();
11967 final match = RegExp(r'\d+').firstMatch(text);
11968 return match == null ? null : int.tryParse(match.group(0)!);
11969 }
11970
11971 String _versionLabel(Map<String, dynamic> version) {
11972 final value =
11973 version['version'] ??
11974 version['id'] ??
11975 version['version_id'] ??
11976 version['revision'] ??
11977 '?';
11978 final text = value.toString();
11979 return text.startsWith('v') ? text : 'v$text';
11980 }
11981
11982 Color _typeColor(String type) {
11983 final normalized = type.toLowerCase();
11984 if (normalized.contains('relation') || normalized.contains('ref')) {
11985 return Colors.blue;
11986 }
11987 if (normalized.contains('computed')) return Colors.purple;
11988 if (normalized.contains('enum')) return Colors.orange;
11989 if (normalized.contains('list') || normalized.contains('array')) {
11990 return Colors.teal;
11991 }
11992 return Colors.white54;
11993 }
11994
11995 bool _hasValue(dynamic value) {
11996 if (value == null) return false;
11997 if (value is String) return value.trim().isNotEmpty;
11998 if (value is List) return value.isNotEmpty;
11999 if (value is Map) return value.isNotEmpty;
12000 return true;
12001 }
12002
12003 String _valueText(dynamic value) {
12004 if (value == null) return '?';
12005 if (value is bool) return value ? 'yes' : 'no';
12006 if (value is List) return '${value.length} items';
12007 if (value is Map) {
12008 final entries = value.entries.take(3).map((entry) {
12009 return '${_titleCase(entry.key.toString())}: ${_valueText(entry.value)}';
12010 });
12011 return entries.join(', ');
12012 }
12013 return value.toString();
12014 }
12015
12016 String _titleCase(String value) {
12017 return value
12018 .replaceAll('_', ' ')
12019 .replaceAll('-', ' ')
12020 .split(' ')
12021 .where((part) => part.isNotEmpty)
12022 .map((part) => '${part[0].toUpperCase()}${part.substring(1)}')
12023 .join(' ');
12024 }
12025
12026 String _short(String value, int limit) {
12027 if (value.length <= limit) return value;
12028 return '${value.substring(0, limit)}...';
12029 }
12030}
12031
12032// ---------------------------------------------------------------------------
12033// Package Manager (admin) — install objects from dbbasic.com
12034// ---------------------------------------------------------------------------
12035
12036class PackageManagerView extends StatefulWidget {
12037 const PackageManagerView({super.key});
12038
12039 @override
12040 State<PackageManagerView> createState() => _PackageManagerViewState();
12041}
12042
12043class _PackageManagerViewState extends State<PackageManagerView> {
12044 final _searchController = TextEditingController();
12045 bool _refreshing = false;
12046 final Set<String> _expanded = {};
12047 final Set<String> _loadingProv = {};
12048 final Map<String, Map<String, dynamic>> _provenance = {};
12049 List<Map<String, dynamic>> _reconciles = [];
12050
12051 @override
12052 void initState() {
12053 super.initState();
12054 _loadReconciles();
12055 }
12056
12057 @override
12058 void dispose() {
12059 _searchController.dispose();
12060 super.dispose();
12061 }
12062
12063 Future<void> _refresh() async {
12064 setState(() {
12065 _refreshing = true;
12066 _provenance.clear();
12067 });
12068 await ScrollData().loadAll();
12069 await _loadReconciles();
12070 if (mounted) setState(() => _refreshing = false);
12071 }
12072
12073 /// Parked upgrade conflicts — a customization whose upstream also changed.
12074 Future<void> _loadReconciles() async {
12075 final result = await ScrollAPI().listReconciles(status: 'pending');
12076 if (!mounted) return;
12077 final body = result['body'];
12078 final raw = body is Map ? body['reconciles'] : null;
12079 setState(() {
12080 _reconciles = [
12081 if (raw is List)
12082 for (final r in raw)
12083 if (r is Map)
12084 Map<String, dynamic>.from(
12085 r.map((k, v) => MapEntry(k.toString(), v)),
12086 ),
12087 ];
12088 });
12089 }
12090
12091 int _conflictsFor(String package) =>
12092 _reconciles.where((r) => r['package'] == package).length;
12093
12094 final Set<String> _installing = {};
12095
12096 Future<void> _upgrade(_PackageStatus p) async {
12097 final isUpgrade = p.installed;
12098 final confirmed = await showDialog<bool>(
12099 context: context,
12100 builder: (dialogContext) => AlertDialog(
12101 title: Text('${isUpgrade ? 'Upgrade' : 'Install'} ${p.displayName}?'),
12102 content: Text(
12103 isUpgrade
12104 ? 'Objects, schema, and permissions update to the shipped '
12105 'version. Your records are preserved, and anything you '
12106 'customized that also changed upstream is parked as a '
12107 'conflict rather than overwritten.'
12108 : 'Installs ${p.displayName} with its objects, schema, '
12109 'permissions, and seed data.',
12110 ),
12111 actions: [
12112 TextButton(
12113 onPressed: () => Navigator.of(dialogContext).pop(false),
12114 child: const Text('Cancel'),
12115 ),
12116 FilledButton(
12117 onPressed: () => Navigator.of(dialogContext).pop(true),
12118 child: Text(isUpgrade ? 'Upgrade' : 'Install'),
12119 ),
12120 ],
12121 ),
12122 );
12123 if (confirmed != true) return;
12124 setState(() => _installing.add(p.name));
12125 final result = await ScrollAPI().installPackage(p.name);
12126 if (!mounted) return;
12127 setState(() => _installing.remove(p.name));
12128 final code = result['status'];
12129 final ok = code is int && code >= 200 && code < 300;
12130 // Refresh regardless so provenance + any parked conflicts reflect reality.
12131 _provenance.remove(p.name);
12132 await ScrollData().loadAll();
12133 await _loadReconciles();
12134 if (!mounted) return;
12135 setState(() {});
12136 if (ok) {
12137 _showInstallResult(p, result['body']);
12138 } else {
12139 ScaffoldMessenger.of(context).showSnackBar(
12140 SnackBar(
12141 content: Text(
12142 '${isUpgrade ? 'Upgrade' : 'Install'} failed: '
12143 'HTTP ${code ?? result['error']}',
12144 ),
12145 backgroundColor: Colors.red[800],
12146 ),
12147 );
12148 }
12149 }
12150
12151 /// Flatten the per-artifact install result into (label, status) rows from
12152 /// whatever shape the server returns.
12153 List<(String, String)> _installArtifacts(dynamic body) {
12154 final root = body is Map ? (body['install'] ?? body['result'] ?? body) : {};
12155 final rows = <(String, String)>[];
12156 void collect(dynamic list, String kind) {
12157 if (list is! List) return;
12158 for (final item in list) {
12159 if (item is Map) {
12160 final name =
12161 (item['id'] ?? item['collection'] ?? item['name'] ?? kind)
12162 .toString();
12163 final status = (item['status'] ?? item['state'] ?? '?').toString();
12164 rows.add(('$kind: $name', status));
12165 }
12166 }
12167 }
12168
12169 if (root is Map) {
12170 collect(root['objects'], 'object');
12171 collect(root['schemas'], 'schema');
12172 collect(root['artifacts'], 'artifact');
12173 }
12174 return rows;
12175 }
12176
12177 void _showInstallResult(_PackageStatus p, dynamic body) {
12178 final artifacts = _installArtifacts(body);
12179 final reconciles = _conflictsFor(p.name);
12180 Color statusColor(String s) => switch (s) {
12181 'written' || 'updated' => Colors.green,
12182 'kept' => Colors.blue,
12183 'unchanged' => Colors.white54,
12184 'conflict' => Colors.orange,
12185 _ => Colors.white54,
12186 };
12187 showDialog<void>(
12188 context: context,
12189 builder: (dialogContext) => AlertDialog(
12190 title: Text('${p.displayName} upgraded'),
12191 content: SizedBox(
12192 width: 460,
12193 child: Column(
12194 mainAxisSize: MainAxisSize.min,
12195 crossAxisAlignment: CrossAxisAlignment.start,
12196 children: [
12197 if (reconciles > 0)
12198 Container(
12199 width: double.infinity,
12200 margin: const EdgeInsets.only(bottom: 12),
12201 padding: const EdgeInsets.all(10),
12202 decoration: BoxDecoration(
12203 color: Colors.orange.withValues(alpha: 0.12),
12204 borderRadius: BorderRadius.circular(8),
12205 ),
12206 child: Text(
12207 '$reconciles conflict${reconciles == 1 ? '' : 's'} '
12208 'parked — your customizations are safe. Resolve them in '
12209 'the conflicts banner on the Package Manager.',
12210 style: TextStyle(fontSize: 12, color: Colors.orange[200]),
12211 ),
12212 ),
12213 if (artifacts.isEmpty)
12214 Text(
12215 'Upgrade completed. Records preserved.',
12216 style: TextStyle(fontSize: 13, color: Colors.white70),
12217 )
12218 else
12219 for (final (label, status) in artifacts)
12220 Padding(
12221 padding: const EdgeInsets.only(bottom: 5),
12222 child: Row(
12223 children: [
12224 Expanded(
12225 child: Text(
12226 label,
12227 overflow: TextOverflow.ellipsis,
12228 style: const TextStyle(
12229 fontSize: 12,
12230 fontFamily: 'monospace',
12231 ),
12232 ),
12233 ),
12234 _packageChip(status.toUpperCase(), statusColor(status)),
12235 ],
12236 ),
12237 ),
12238 ],
12239 ),
12240 ),
12241 actions: [
12242 TextButton(
12243 onPressed: () => Navigator.of(dialogContext).pop(),
12244 child: const Text('Close'),
12245 ),
12246 ],
12247 ),
12248 );
12249 }
12250
12251 Future<void> _resolve(Map<String, dynamic> reconcile, String choice) async {
12252 final id = reconcile['id']?.toString();
12253 if (id == null) return;
12254 final result = await ScrollAPI().resolveReconcile(id, choice);
12255 final code = result['status'];
12256 final ok = code is int && code >= 200 && code < 300;
12257 if (!mounted) return;
12258 if (ok) {
12259 // Drop it locally and clear cached provenance so the badge updates.
12260 setState(() => _reconciles.removeWhere((r) => r['id'] == id));
12261 _provenance.remove(reconcile['package']?.toString());
12262 ScaffoldMessenger.of(context).showSnackBar(
12263 SnackBar(
12264 content: Text(
12265 choice == 'take_theirs'
12266 ? 'Took the shipped version.'
12267 : 'Kept your version.',
12268 ),
12269 backgroundColor: Colors.green[800],
12270 ),
12271 );
12272 } else {
12273 ScaffoldMessenger.of(context).showSnackBar(
12274 SnackBar(
12275 content: Text('Resolve failed: HTTP ${code ?? result['error']}'),
12276 backgroundColor: Colors.red[800],
12277 ),
12278 );
12279 }
12280 }
12281
12282 /// LCS unified line diff of live ("mine") vs shipped ("theirs").
12283 List<(String, String)> _unifiedDiff(String mine, String theirs) {
12284 final a = mine.split('\n');
12285 final b = theirs.split('\n');
12286 final n = a.length, m = b.length;
12287 // Guard against pathologically large sources (O(n*m) table).
12288 if (n > 1500 || m > 1500) {
12289 return [
12290 for (final line in a) ('remove', line),
12291 for (final line in b) ('add', line),
12292 ];
12293 }
12294 final dp = List.generate(n + 1, (_) => List<int>.filled(m + 1, 0));
12295 for (var i = n - 1; i >= 0; i--) {
12296 for (var j = m - 1; j >= 0; j--) {
12297 dp[i][j] = a[i] == b[j]
12298 ? dp[i + 1][j + 1] + 1
12299 : (dp[i + 1][j] >= dp[i][j + 1] ? dp[i + 1][j] : dp[i][j + 1]);
12300 }
12301 }
12302 final out = <(String, String)>[];
12303 var i = 0, j = 0;
12304 while (i < n && j < m) {
12305 if (a[i] == b[j]) {
12306 out.add(('same', a[i]));
12307 i++;
12308 j++;
12309 } else if (dp[i + 1][j] >= dp[i][j + 1]) {
12310 out.add(('remove', a[i]));
12311 i++;
12312 } else {
12313 out.add(('add', b[j]));
12314 j++;
12315 }
12316 }
12317 while (i < n) {
12318 out.add(('remove', a[i++]));
12319 }
12320 while (j < m) {
12321 out.add(('add', b[j++]));
12322 }
12323 return out;
12324 }
12325
12326 void _showReconcileDialog(Map<String, dynamic> reconcile) {
12327 final artifact = reconcile['artifact'];
12328 final artifactLabel = artifact is Map
12329 ? '${artifact['kind']}: ${artifact['id'] ?? artifact['collection'] ?? ''}'
12330 : 'artifact';
12331 final mine = reconcile['mine']?.toString() ?? '';
12332 final theirs = reconcile['theirs']?.toString() ?? '';
12333 final diff = _unifiedDiff(mine, theirs);
12334 // Phase 4a: schema conflicts name the exact clashing fields.
12335 final collisions = reconcile['collisions'] is List
12336 ? (reconcile['collisions'] as List).map((c) => c.toString()).toList()
12337 : const <String>[];
12338 showDialog<void>(
12339 context: context,
12340 builder: (dialogContext) => AlertDialog(
12341 title: Text('${reconcile['package']} — $artifactLabel'),
12342 content: SizedBox(
12343 width: 640,
12344 height: 460,
12345 child: Column(
12346 crossAxisAlignment: CrossAxisAlignment.start,
12347 children: [
12348 Text(
12349 'Your version (v${reconcile['baseline_version'] ?? '?'}) '
12350 'vs shipped (v${reconcile['target_version'] ?? '?'}). '
12351 '− red is yours (keep mine), + green is shipped (take theirs).',
12352 style: TextStyle(fontSize: 12, color: Colors.white54),
12353 ),
12354 if (collisions.isNotEmpty)
12355 Padding(
12356 padding: const EdgeInsets.only(top: 8),
12357 child: Wrap(
12358 spacing: 6,
12359 runSpacing: 6,
12360 crossAxisAlignment: WrapCrossAlignment.center,
12361 children: [
12362 Text(
12363 'Conflicting fields:',
12364 style: TextStyle(
12365 fontSize: 12,
12366 color: Colors.orange[200],
12367 ),
12368 ),
12369 for (final field in collisions)
12370 _packageChip(field, Colors.orange),
12371 ],
12372 ),
12373 ),
12374 const SizedBox(height: 10),
12375 Expanded(
12376 child: Container(
12377 width: double.infinity,
12378 padding: const EdgeInsets.all(10),
12379 decoration: BoxDecoration(
12380 color: Colors.black26,
12381 borderRadius: BorderRadius.circular(8),
12382 border: Border.all(color: Colors.white10),
12383 ),
12384 child: SingleChildScrollView(
12385 child: SelectableText.rich(
12386 TextSpan(
12387 children: [
12388 for (final (type, line) in diff)
12389 TextSpan(
12390 text:
12391 '${switch (type) {
12392 'add' => '+',
12393 'remove' => '-',
12394 _ => ' ',
12395 }} $line\n',
12396 style: TextStyle(
12397 fontFamily: 'monospace',
12398 fontSize: 11.5,
12399 height: 1.4,
12400 color: switch (type) {
12401 'add' => Colors.green[300],
12402 'remove' => Colors.red[300],
12403 _ => Colors.white38,
12404 },
12405 ),
12406 ),
12407 ],
12408 ),
12409 ),
12410 ),
12411 ),
12412 ),
12413 ],
12414 ),
12415 ),
12416 actions: [
12417 TextButton(
12418 onPressed: () => Navigator.of(dialogContext).pop(),
12419 child: const Text('Cancel'),
12420 ),
12421 OutlinedButton(
12422 onPressed: () {
12423 Navigator.of(dialogContext).pop();
12424 _resolve(reconcile, 'keep_mine');
12425 },
12426 child: const Text('Keep Mine'),
12427 ),
12428 FilledButton(
12429 onPressed: () {
12430 Navigator.of(dialogContext).pop();
12431 _resolve(reconcile, 'take_theirs');
12432 },
12433 child: const Text('Take Theirs'),
12434 ),
12435 ],
12436 ),
12437 );
12438 }
12439
12440 /// Lazily fetch a package's provenance (GET /packages/{id}) on first
12441 /// expand — the /admin/status list doesn't carry per-artifact baselines.
12442 Future<void> _toggleProvenance(String id) async {
12443 if (_expanded.contains(id)) {
12444 setState(() => _expanded.remove(id));
12445 return;
12446 }
12447 setState(() => _expanded.add(id));
12448 if (_provenance.containsKey(id) || _loadingProv.contains(id)) return;
12449 setState(() => _loadingProv.add(id));
12450 final result = await ScrollAPI().getPackage(id);
12451 if (!mounted) return;
12452 setState(() {
12453 _loadingProv.remove(id);
12454 if (result != null) _provenance[id] = result;
12455 });
12456 }
12457
12458 @override
12459 Widget build(BuildContext context) {
12460 final data = ScrollData();
12461 final allPackages = data.adminPackages.map(_PackageStatus.fromMap).toList();
12462 final query = _searchController.text.trim().toLowerCase();
12463 final packages = allPackages.where((package) {
12464 if (query.isEmpty) return true;
12465 return package.name.toLowerCase().contains(query) ||
12466 package.status.toLowerCase().contains(query) ||
12467 package.source.toLowerCase().contains(query);
12468 }).toList();
12469
12470 return Padding(
12471 padding: const EdgeInsets.all(24),
12472 child: Column(
12473 crossAxisAlignment: CrossAxisAlignment.start,
12474 children: [
12475 Row(
12476 children: [
12477 Text(
12478 'Package Manager',
12479 style: Theme.of(context).textTheme.titleLarge,
12480 ),
12481 const SizedBox(width: 12),
12482 Text(
12483 data.hasAdminStatus ? data.packageSummary : '/admin/status',
12484 style: TextStyle(fontSize: 12, color: Colors.white38),
12485 ),
12486 const Spacer(),
12487 IconButton(
12488 onPressed: _refreshing ? null : _refresh,
12489 icon: _refreshing
12490 ? const SizedBox(
12491 width: 16,
12492 height: 16,
12493 child: CircularProgressIndicator(strokeWidth: 2),
12494 )
12495 : const Icon(Icons.refresh, size: 18),
12496 tooltip: 'Refresh packages',
12497 ),
12498 const SizedBox(width: 8),
12499 SizedBox(
12500 width: 250,
12501 height: 36,
12502 child: TextField(
12503 controller: _searchController,
12504 onChanged: (_) => setState(() {}),
12505 decoration: InputDecoration(
12506 hintText: 'Search packages...',
12507 hintStyle: const TextStyle(fontSize: 12),
12508 prefixIcon: const Icon(Icons.search, size: 18),
12509 isDense: true,
12510 contentPadding: const EdgeInsets.symmetric(vertical: 8),
12511 border: OutlineInputBorder(
12512 borderRadius: BorderRadius.circular(8),
12513 ),
12514 ),
12515 style: const TextStyle(fontSize: 13),
12516 ),
12517 ),
12518 ],
12519 ),
12520 const SizedBox(height: 8),
12521 Text(
12522 data.hasAdminStatus
12523 ? 'Package posture from the connected object server. Installs stay disabled on public staging unless explicitly enabled.'
12524 : 'Package status is unavailable until /admin/status returns an authenticated response.',
12525 style: TextStyle(fontSize: 12, color: Colors.white38),
12526 ),
12527 if (_reconciles.isNotEmpty) ...[
12528 const SizedBox(height: 12),
12529 _conflictsBanner(context),
12530 ],
12531 const SizedBox(height: 16),
12532 Expanded(
12533 child: packages.isEmpty
12534 ? _emptyPackages(context, data.hasAdminStatus)
12535 : ListView.separated(
12536 itemCount: packages.length,
12537 separatorBuilder: (_, __) => const SizedBox(height: 8),
12538 itemBuilder: (context, i) {
12539 final p = packages[i];
12540 final color = _statusColor(p.status);
12541 final expanded = _expanded.contains(p.name);
12542 final loadingProv = _loadingProv.contains(p.name);
12543 final prov = _provenance[p.name];
12544 return Container(
12545 decoration: BoxDecoration(
12546 color: Theme.of(
12547 context,
12548 ).colorScheme.surfaceContainerLow,
12549 borderRadius: BorderRadius.circular(8),
12550 border: Border.all(color: Colors.white10),
12551 ),
12552 child: Column(
12553 crossAxisAlignment: CrossAxisAlignment.stretch,
12554 children: [
12555 InkWell(
12556 onTap: p.installed
12557 ? () => _toggleProvenance(p.name)
12558 : null,
12559 borderRadius: BorderRadius.circular(8),
12560 child: Padding(
12561 padding: const EdgeInsets.all(14),
12562 child: Row(
12563 children: [
12564 Container(
12565 width: 38,
12566 height: 38,
12567 decoration: BoxDecoration(
12568 color: color.withValues(alpha: 0.14),
12569 shape: BoxShape.circle,
12570 ),
12571 child: Icon(
12572 p.installed
12573 ? Icons.check
12574 : Icons.extension_outlined,
12575 size: 20,
12576 color: color,
12577 ),
12578 ),
12579 const SizedBox(width: 14),
12580 Expanded(
12581 child: Column(
12582 crossAxisAlignment:
12583 CrossAxisAlignment.start,
12584 children: [
12585 Row(
12586 children: [
12587 Flexible(
12588 child: Text(
12589 p.displayName,
12590 overflow:
12591 TextOverflow.ellipsis,
12592 style: const TextStyle(
12593 fontSize: 15,
12594 fontWeight: FontWeight.w600,
12595 ),
12596 ),
12597 ),
12598 if (p.version.isNotEmpty) ...[
12599 const SizedBox(width: 8),
12600 Text(
12601 'v${p.version}',
12602 style: TextStyle(
12603 fontSize: 11,
12604 color: Colors.white38,
12605 ),
12606 ),
12607 ],
12608 const SizedBox(width: 8),
12609 _packageChip(
12610 p.source,
12611 Colors.blue,
12612 ),
12613 if (_conflictsFor(p.name) >
12614 0) ...[
12615 const SizedBox(width: 8),
12616 _packageChip(
12617 '${_conflictsFor(p.name)} '
12618 'conflict'
12619 '${_conflictsFor(p.name) == 1 ? '' : 's'}',
12620 Colors.orange,
12621 ),
12622 ],
12623 ],
12624 ),
12625 const SizedBox(height: 3),
12626 Text(
12627 p.description,
12628 maxLines: 2,
12629 overflow: TextOverflow.ellipsis,
12630 style: TextStyle(
12631 fontSize: 12,
12632 color: Colors.white54,
12633 ),
12634 ),
12635 ],
12636 ),
12637 ),
12638 const SizedBox(width: 16),
12639 Column(
12640 crossAxisAlignment:
12641 CrossAxisAlignment.end,
12642 mainAxisSize: MainAxisSize.min,
12643 children: [
12644 _packageChip(p.statusLabel, color),
12645 const SizedBox(height: 8),
12646 if (p.installed)
12647 Row(
12648 mainAxisSize: MainAxisSize.min,
12649 children: [
12650 if (data.packagesCanInstall) ...[
12651 _upgradeButton(p, 'Upgrade'),
12652 const SizedBox(width: 8),
12653 ],
12654 Text(
12655 'Provenance',
12656 style: TextStyle(
12657 fontSize: 11,
12658 color: Colors.white38,
12659 ),
12660 ),
12661 Icon(
12662 expanded
12663 ? Icons.expand_less
12664 : Icons.expand_more,
12665 size: 18,
12666 color: Colors.white38,
12667 ),
12668 ],
12669 )
12670 else if (data.packagesCanInstall)
12671 _upgradeButton(p, 'Install')
12672 else
12673 Tooltip(
12674 message:
12675 'Package installs are disabled on this server',
12676 child: OutlinedButton.icon(
12677 onPressed: null,
12678 icon: const Icon(
12679 Icons.lock,
12680 size: 14,
12681 ),
12682 label: const Text(
12683 'Install locked',
12684 ),
12685 ),
12686 ),
12687 ],
12688 ),
12689 ],
12690 ),
12691 ),
12692 ),
12693 if (expanded)
12694 Padding(
12695 padding: const EdgeInsets.fromLTRB(
12696 14,
12697 0,
12698 14,
12699 14,
12700 ),
12701 child: loadingProv
12702 ? const Padding(
12703 padding: EdgeInsets.all(8),
12704 child: SizedBox(
12705 width: 16,
12706 height: 16,
12707 child: CircularProgressIndicator(
12708 strokeWidth: 2,
12709 ),
12710 ),
12711 )
12712 : _provenancePanel(context, prov),
12713 ),
12714 ],
12715 ),
12716 );
12717 },
12718 ),
12719 ),
12720 ],
12721 ),
12722 );
12723 }
12724
12725 Widget _emptyPackages(BuildContext context, bool hasAdminStatus) {
12726 return Center(
12727 child: Container(
12728 constraints: const BoxConstraints(maxWidth: 420),
12729 padding: const EdgeInsets.all(20),
12730 decoration: BoxDecoration(
12731 color: Theme.of(context).colorScheme.surfaceContainerLow,
12732 borderRadius: BorderRadius.circular(8),
12733 border: Border.all(color: Colors.white10),
12734 ),
12735 child: Column(
12736 mainAxisSize: MainAxisSize.min,
12737 children: [
12738 Icon(
12739 hasAdminStatus ? Icons.search_off : Icons.lock_outline,
12740 size: 32,
12741 color: Colors.white38,
12742 ),
12743 const SizedBox(height: 10),
12744 Text(
12745 hasAdminStatus
12746 ? 'No packages match this search'
12747 : 'Package posture unavailable',
12748 style: const TextStyle(fontWeight: FontWeight.w600),
12749 ),
12750 const SizedBox(height: 4),
12751 Text(
12752 hasAdminStatus
12753 ? 'Clear the search filter to see reported packages.'
12754 : 'Connect with an admin Bearer token so /admin/status can report package state.',
12755 textAlign: TextAlign.center,
12756 style: TextStyle(fontSize: 12, color: Colors.white38),
12757 ),
12758 ],
12759 ),
12760 ),
12761 );
12762 }
12763
12764 Widget _upgradeButton(_PackageStatus p, String label) {
12765 final busy = _installing.contains(p.name);
12766 return OutlinedButton.icon(
12767 onPressed: busy ? null : () => _upgrade(p),
12768 icon: busy
12769 ? const SizedBox(
12770 width: 13,
12771 height: 13,
12772 child: CircularProgressIndicator(strokeWidth: 2),
12773 )
12774 : Icon(label == 'Upgrade' ? Icons.upgrade : Icons.download, size: 14),
12775 label: Text(label == 'Upgrade' ? 'Upgrade (keep data)' : label),
12776 style: OutlinedButton.styleFrom(visualDensity: VisualDensity.compact),
12777 );
12778 }
12779
12780 Widget _packageChip(String label, Color color) {
12781 return Container(
12782 padding: const EdgeInsets.symmetric(horizontal: 7, vertical: 2),
12783 decoration: BoxDecoration(
12784 color: color.withValues(alpha: 0.12),
12785 borderRadius: BorderRadius.circular(4),
12786 border: Border.all(color: color.withValues(alpha: 0.16)),
12787 ),
12788 child: Text(
12789 label,
12790 overflow: TextOverflow.ellipsis,
12791 style: TextStyle(
12792 fontSize: 10,
12793 color: color,
12794 fontWeight: FontWeight.bold,
12795 ),
12796 ),
12797 );
12798 }
12799
12800 /// Parked upgrade conflicts across all packages — each opens a mine-vs-
12801 /// theirs diff with keep-mine / take-theirs.
12802 Widget _conflictsBanner(BuildContext context) {
12803 return Container(
12804 width: double.infinity,
12805 padding: const EdgeInsets.all(14),
12806 decoration: BoxDecoration(
12807 color: Colors.orange.withValues(alpha: 0.10),
12808 borderRadius: BorderRadius.circular(8),
12809 border: Border.all(color: Colors.orange.withValues(alpha: 0.3)),
12810 ),
12811 child: Column(
12812 crossAxisAlignment: CrossAxisAlignment.start,
12813 children: [
12814 Row(
12815 children: [
12816 Icon(Icons.merge_type, size: 18, color: Colors.orange[300]),
12817 const SizedBox(width: 8),
12818 Text(
12819 '${_reconciles.length} pending '
12820 'conflict${_reconciles.length == 1 ? '' : 's'}',
12821 style: TextStyle(
12822 fontSize: 13,
12823 fontWeight: FontWeight.w700,
12824 color: Colors.orange[200],
12825 ),
12826 ),
12827 const SizedBox(width: 8),
12828 Expanded(
12829 child: Text(
12830 'An upgrade changed something you had customized — your '
12831 'version is preserved until you resolve it.',
12832 style: TextStyle(fontSize: 12, color: Colors.white54),
12833 ),
12834 ),
12835 ],
12836 ),
12837 const SizedBox(height: 10),
12838 for (final reconcile in _reconciles)
12839 _conflictCard(context, reconcile),
12840 ],
12841 ),
12842 );
12843 }
12844
12845 Widget _conflictCard(BuildContext context, Map<String, dynamic> reconcile) {
12846 final artifact = reconcile['artifact'];
12847 final artifactLabel = artifact is Map
12848 ? '${artifact['kind']}: ${artifact['id'] ?? artifact['collection'] ?? ''}'
12849 : 'artifact';
12850 return Padding(
12851 padding: const EdgeInsets.only(bottom: 6),
12852 child: Row(
12853 children: [
12854 _packageChip(reconcile['package']?.toString() ?? '?', Colors.orange),
12855 const SizedBox(width: 10),
12856 Expanded(
12857 child: Text(
12858 artifactLabel,
12859 overflow: TextOverflow.ellipsis,
12860 style: const TextStyle(fontSize: 12, fontFamily: 'monospace'),
12861 ),
12862 ),
12863 const SizedBox(width: 8),
12864 Text(
12865 'v${reconcile['baseline_version'] ?? '?'} → '
12866 'v${reconcile['target_version'] ?? '?'}',
12867 style: TextStyle(fontSize: 11, color: Colors.white38),
12868 ),
12869 const SizedBox(width: 10),
12870 FilledButton.tonal(
12871 onPressed: () => _showReconcileDialog(reconcile),
12872 style: FilledButton.styleFrom(visualDensity: VisualDensity.compact),
12873 child: const Text('Review'),
12874 ),
12875 ],
12876 ),
12877 );
12878 }
12879
12880 /// Renders the provenance block from GET /packages/{id}: whether the
12881 /// package diverges from its shipped baseline, and each artifact's state.
12882 Widget _provenancePanel(BuildContext context, Map<String, dynamic>? pkg) {
12883 final prov = pkg?['provenance'];
12884 if (prov is! Map) {
12885 return Text(
12886 'Provenance unavailable for this session.',
12887 style: TextStyle(fontSize: 12, color: Colors.white38),
12888 );
12889 }
12890 final installed = prov['installed'] == true;
12891 final customized = prov['customized'] == true;
12892 final installedVersion = prov['installed_version']?.toString();
12893 final artifacts = prov['artifacts'];
12894 return Column(
12895 crossAxisAlignment: CrossAxisAlignment.start,
12896 children: [
12897 const Divider(height: 1, color: Colors.white10),
12898 const SizedBox(height: 10),
12899 Wrap(
12900 spacing: 8,
12901 runSpacing: 6,
12902 crossAxisAlignment: WrapCrossAlignment.center,
12903 children: [
12904 if (!installed)
12905 _packageChip('NO BASELINE', Colors.white54)
12906 else
12907 _packageChip(
12908 customized ? 'CUSTOMIZED' : 'PRISTINE',
12909 customized ? Colors.orange : Colors.green,
12910 ),
12911 if (installedVersion != null && installedVersion.isNotEmpty)
12912 Text(
12913 'baseline v$installedVersion',
12914 style: TextStyle(fontSize: 11, color: Colors.white38),
12915 ),
12916 if (installed && customized)
12917 Text(
12918 'diverges from the shipped version',
12919 style: TextStyle(fontSize: 11, color: Colors.orange[200]),
12920 ),
12921 ],
12922 ),
12923 if (artifacts is List && artifacts.isNotEmpty) ...[
12924 const SizedBox(height: 10),
12925 for (final artifact in artifacts)
12926 if (artifact is Map) _artifactRow(artifact),
12927 ],
12928 ],
12929 );
12930 }
12931
12932 Widget _artifactRow(Map artifact) {
12933 final kind = artifact['kind']?.toString() ?? 'artifact';
12934 final name =
12935 (artifact['id'] ?? artifact['collection'] ?? artifact['name'] ?? '?')
12936 .toString();
12937 // Phase 3: an overridden object is customized safely (upgrade-proof),
12938 // so it reads as its own good state rather than "customized".
12939 final overridden = artifact['overridden'] == true;
12940 final state = overridden
12941 ? 'overridden'
12942 : (artifact['state']?.toString() ?? 'unknown');
12943 final color = switch (state) {
12944 'pristine' => Colors.green,
12945 'overridden' => Colors.teal,
12946 'customized' => Colors.orange,
12947 'removed' => Colors.red,
12948 _ => Colors.white54,
12949 };
12950 return Padding(
12951 padding: const EdgeInsets.only(bottom: 5),
12952 child: Row(
12953 children: [
12954 SizedBox(
12955 width: 68,
12956 child: Text(
12957 kind,
12958 style: TextStyle(fontSize: 11, color: Colors.white38),
12959 ),
12960 ),
12961 Expanded(
12962 child: Text(
12963 name,
12964 overflow: TextOverflow.ellipsis,
12965 style: const TextStyle(fontSize: 12, fontFamily: 'monospace'),
12966 ),
12967 ),
12968 const SizedBox(width: 8),
12969 _packageChip(state.toUpperCase(), color),
12970 ],
12971 ),
12972 );
12973 }
12974
12975 Color _statusColor(String status) {
12976 final normalized = status.toLowerCase();
12977 if (normalized == 'installed') return Colors.green;
12978 if (normalized == 'available') return Theme.of(context).colorScheme.primary;
12979 if (normalized == 'disabled' || normalized == 'blocked') {
12980 return Colors.orange;
12981 }
12982 return Colors.white54;
12983 }
12984}
12985
12986class _PackageStatus {
12987 final String name;
12988 final String displayName;
12989 final String description;
12990 final String source;
12991 final String version;
12992 final String status;
12993
12994 const _PackageStatus({
12995 required this.name,
12996 required this.displayName,
12997 required this.description,
12998 required this.source,
12999 required this.version,
13000 required this.status,
13001 });
13002
13003 bool get installed => status.toLowerCase() == 'installed';
13004 String get statusLabel => _titleCase(status);
13005
13006 factory _PackageStatus.fromMap(Map<String, dynamic> data) {
13007 final name =
13008 data['name']?.toString() ??
13009 data['id']?.toString() ??
13010 data['package']?.toString() ??
13011 'package';
13012 final status =
13013 data['status']?.toString() ??
13014 data['state']?.toString() ??
13015 data['value']?.toString() ??
13016 (data['installed'] == true ? 'installed' : 'available');
13017 final source =
13018 data['source']?.toString() ??
13019 data['author']?.toString() ??
13020 data['publisher']?.toString() ??
13021 'object-server';
13022 final version = data['version']?.toString() ?? '';
13023 final description =
13024 data['description']?.toString() ?? _defaultDescription(name, status);
13025 return _PackageStatus(
13026 name: name,
13027 displayName: _titleCase(name),
13028 description: description,
13029 source: source,
13030 version: version,
13031 status: status,
13032 );
13033 }
13034
13035 static String _defaultDescription(String name, String status) {
13036 final normalized = status.toLowerCase();
13037 if (normalized == 'installed') {
13038 return 'Installed package reported by the connected object server.';
13039 }
13040 return 'Available package reported by the connected object server.';
13041 }
13042
13043 static String _titleCase(String value) {
13044 return value
13045 .replaceAll('_', ' ')
13046 .replaceAll('-', ' ')
13047 .split(' ')
13048 .where((part) => part.isNotEmpty)
13049 .map((part) => '${part[0].toUpperCase()}${part.substring(1)}')
13050 .join(' ');
13051 }
13052}
13053
13054// ---------------------------------------------------------------------------
13055// Placeholder
13056// ---------------------------------------------------------------------------
13057
13058// ---------------------------------------------------------------------------
13059// Visual Diagram — ER/UML style relationships between collections
13060// ---------------------------------------------------------------------------
13061
13062class DiagramView extends StatelessWidget {
13063 const DiagramView({super.key});
13064
13065 @override
13066 Widget build(BuildContext context) {
13067 return Stack(
13068 children: [
13069 // Background grid
13070 CustomPaint(size: Size.infinite, painter: _GridPainter()),
13071 // Connection lines (drawn behind boxes)
13072 CustomPaint(size: Size.infinite, painter: _RelationPainter()),
13073 // Collection boxes
13074 _collectionBox(
13075 context,
13076 'Contacts',
13077 [
13078 'first_name',
13079 'last_name',
13080 'email',
13081 'phone',
13082 'organization_id → Orgs',
13083 'lead_status',
13084 ],
13085 left: 60,
13086 top: 40,
13087 color: Colors.blue,
13088 ),
13089 _collectionBox(
13090 context,
13091 'Organizations',
13092 ['name', 'website', 'industry', 'address', 'phone'],
13093 left: 380,
13094 top: 20,
13095 color: Colors.teal,
13096 ),
13097 _collectionBox(
13098 context,
13099 'Invoices',
13100 [
13101 'customer_id → Contacts',
13102 'invoice_date',
13103 'due_date',
13104 'status',
13105 'line_items → Products',
13106 'total (computed)',
13107 ],
13108 left: 60,
13109 top: 320,
13110 color: Colors.purple,
13111 ),
13112 _collectionBox(
13113 context,
13114 'Products',
13115 ['name', 'description', 'price', 'sku', 'stock', 'category'],
13116 left: 380,
13117 top: 280,
13118 color: Colors.orange,
13119 ),
13120 _collectionBox(
13121 context,
13122 'Orders',
13123 [
13124 'customer_id → Contacts',
13125 'order_date',
13126 'status',
13127 'items → Products',
13128 'shipping_address',
13129 'total (computed)',
13130 ],
13131 left: 680,
13132 top: 140,
13133 color: Colors.green,
13134 ),
13135 _collectionBox(
13136 context,
13137 'Tasks',
13138 [
13139 'title',
13140 'description',
13141 'project_id → Projects',
13142 'assignee_id → Users',
13143 'status',
13144 'due_date',
13145 ],
13146 left: 680,
13147 top: 420,
13148 color: Colors.red,
13149 ),
13150 _collectionBox(
13151 context,
13152 'Projects',
13153 ['name', 'description', 'status', 'owner_id → Users'],
13154 left: 380,
13155 top: 510,
13156 color: Colors.indigo,
13157 ),
13158 // Toolbar
13159 Positioned(
13160 top: 12,
13161 right: 12,
13162 child: Container(
13163 padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
13164 decoration: BoxDecoration(
13165 color: Theme.of(context).colorScheme.surfaceContainerLow,
13166 borderRadius: BorderRadius.circular(8),
13167 border: Border.all(color: Colors.white10),
13168 ),
13169 child: Row(
13170 mainAxisSize: MainAxisSize.min,
13171 children: [
13172 IconButton(
13173 onPressed: () {},
13174 icon: const Icon(Icons.zoom_in, size: 18),
13175 visualDensity: VisualDensity.compact,
13176 tooltip: 'Zoom In',
13177 ),
13178 IconButton(
13179 onPressed: () {},
13180 icon: const Icon(Icons.zoom_out, size: 18),
13181 visualDensity: VisualDensity.compact,
13182 tooltip: 'Zoom Out',
13183 ),
13184 IconButton(
13185 onPressed: () {},
13186 icon: const Icon(Icons.fit_screen, size: 18),
13187 visualDensity: VisualDensity.compact,
13188 tooltip: 'Fit to Screen',
13189 ),
13190 const SizedBox(width: 8),
13191 IconButton(
13192 onPressed: () {},
13193 icon: const Icon(Icons.add, size: 18),
13194 visualDensity: VisualDensity.compact,
13195 tooltip: 'Add Collection',
13196 ),
13197 IconButton(
13198 onPressed: () {},
13199 icon: const Icon(Icons.image_outlined, size: 18),
13200 visualDensity: VisualDensity.compact,
13201 tooltip: 'Export Image',
13202 ),
13203 ],
13204 ),
13205 ),
13206 ),
13207 ],
13208 );
13209 }
13210
13211 Widget _collectionBox(
13212 BuildContext context,
13213 String name,
13214 List<String> fields, {
13215 required double left,
13216 required double top,
13217 required Color color,
13218 }) {
13219 return Positioned(
13220 left: left,
13221 top: top,
13222 child: Container(
13223 width: 260,
13224 decoration: BoxDecoration(
13225 color: Theme.of(context).colorScheme.surfaceContainerLow,
13226 borderRadius: BorderRadius.circular(8),
13227 border: Border.all(color: color.withOpacity(0.4)),
13228 boxShadow: [
13229 BoxShadow(
13230 color: Colors.black26,
13231 blurRadius: 8,
13232 offset: const Offset(0, 2),
13233 ),
13234 ],
13235 ),
13236 child: Column(
13237 crossAxisAlignment: CrossAxisAlignment.start,
13238 children: [
13239 // Header
13240 Container(
13241 padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
13242 decoration: BoxDecoration(
13243 color: color.withOpacity(0.15),
13244 borderRadius: const BorderRadius.vertical(
13245 top: Radius.circular(7),
13246 ),
13247 ),
13248 child: Row(
13249 children: [
13250 Icon(Icons.storage, size: 14, color: color),
13251 const SizedBox(width: 6),
13252 Text(
13253 name,
13254 style: TextStyle(
13255 fontWeight: FontWeight.bold,
13256 fontSize: 13,
13257 color: color,
13258 ),
13259 ),
13260 const Spacer(),
13261 Text(
13262 '${fields.length}',
13263 style: TextStyle(fontSize: 11, color: Colors.white38),
13264 ),
13265 ],
13266 ),
13267 ),
13268 // Fields
13269 ...fields.map((f) {
13270 final isRelation = f.contains('→');
13271 final isComputed = f.contains('(computed)');
13272 return Padding(
13273 padding: const EdgeInsets.symmetric(
13274 horizontal: 12,
13275 vertical: 3,
13276 ),
13277 child: Row(
13278 children: [
13279 Icon(
13280 isRelation
13281 ? Icons.link
13282 : (isComputed ? Icons.functions : Icons.remove),
13283 size: 12,
13284 color: isRelation
13285 ? Colors.blue
13286 : (isComputed ? Colors.purple : Colors.white24),
13287 ),
13288 const SizedBox(width: 6),
13289 Expanded(
13290 child: Text(
13291 f,
13292 style: TextStyle(
13293 fontSize: 11,
13294 fontFamily: 'monospace',
13295 color: isRelation
13296 ? Colors.blue[200]
13297 : (isComputed
13298 ? Colors.purple[200]
13299 : Colors.white54),
13300 ),
13301 ),
13302 ),
13303 ],
13304 ),
13305 );
13306 }),
13307 const SizedBox(height: 6),
13308 ],
13309 ),
13310 ),
13311 );
13312 }
13313}
13314
13315class _GridPainter extends CustomPainter {
13316 @override
13317 void paint(Canvas canvas, Size size) {
13318 final paint = Paint()
13319 ..color = Colors.white.withOpacity(0.03)
13320 ..strokeWidth = 1;
13321 for (double x = 0; x < size.width; x += 40) {
13322 canvas.drawLine(Offset(x, 0), Offset(x, size.height), paint);
13323 }
13324 for (double y = 0; y < size.height; y += 40) {
13325 canvas.drawLine(Offset(0, y), Offset(size.width, y), paint);
13326 }
13327 }
13328
13329 @override
13330 bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
13331}
13332
13333class _RelationPainter extends CustomPainter {
13334 @override
13335 void paint(Canvas canvas, Size size) {
13336 final paint = Paint()
13337 ..color = Colors.blue.withOpacity(0.3)
13338 ..strokeWidth = 1.5
13339 ..style = PaintingStyle.stroke;
13340
13341 // Contacts → Organizations
13342 _drawArrow(canvas, paint, const Offset(320, 100), const Offset(380, 60));
13343 // Invoices → Contacts
13344 _drawArrow(canvas, paint, const Offset(150, 320), const Offset(150, 260));
13345 // Invoices → Products
13346 _drawArrow(canvas, paint, const Offset(320, 400), const Offset(380, 360));
13347 // Orders → Contacts
13348 paint.color = Colors.green.withOpacity(0.3);
13349 _drawArrow(canvas, paint, const Offset(680, 200), const Offset(320, 120));
13350 // Orders → Products
13351 _drawArrow(canvas, paint, const Offset(680, 240), const Offset(640, 340));
13352 // Tasks → Projects
13353 paint.color = Colors.red.withOpacity(0.3);
13354 _drawArrow(canvas, paint, const Offset(680, 500), const Offset(640, 540));
13355 }
13356
13357 void _drawArrow(Canvas canvas, Paint paint, Offset from, Offset to) {
13358 canvas.drawLine(from, to, paint);
13359 // Arrowhead
13360 final angle = (to - from).direction;
13361 final arrowSize = 8.0;
13362 canvas.drawLine(
13363 to,
13364 Offset(
13365 to.dx -
13366 arrowSize * (to - from).normalized.dx +
13367 arrowSize * 0.4 * (to - from).normalized.dy,
13368 to.dy -
13369 arrowSize * (to - from).normalized.dy -
13370 arrowSize * 0.4 * (to - from).normalized.dx,
13371 ),
13372 paint,
13373 );
13374 }
13375
13376 @override
13377 bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
13378}
13379
13380extension on Offset {
13381 Offset get normalized {
13382 final d = distance;
13383 return d == 0 ? this : Offset(dx / d, dy / d);
13384 }
13385}
13386
13387// ---------------------------------------------------------------------------
13388// Identity registry (admin)
13389// ---------------------------------------------------------------------------
13390
13391enum _IdentitySection { users, accounts, sessions }
13392
13393class IdentityRegistryView extends StatefulWidget {
13394 const IdentityRegistryView({super.key});
13395
13396 @override
13397 State<IdentityRegistryView> createState() => _IdentityRegistryViewState();
13398}
13399
13400class _IdentityRegistryViewState extends State<IdentityRegistryView> {
13401 _IdentitySection _section = _IdentitySection.users;
13402 List<Map<String, dynamic>> _accounts = [];
13403 List<Map<String, dynamic>> _users = [];
13404 List<Map<String, dynamic>> _sessions = [];
13405 Map<String, dynamic>? _selectedRow;
13406 Map<String, dynamic>? _selectedDetail;
13407 String? _selectedId;
13408 String? _accountFilter;
13409 bool _loading = true;
13410 bool _listLoading = false;
13411 bool _detailLoading = false;
13412 bool _passwordWriting = false;
13413 Map<String, dynamic>? _passwordResponse;
13414 String? _error;
13415
13416 @override
13417 void initState() {
13418 super.initState();
13419 _loadIdentity();
13420 }
13421
13422 Future<void> _loadIdentity() async {
13423 setState(() {
13424 _loading = true;
13425 _error = null;
13426 });
13427 try {
13428 final api = ScrollAPI();
13429 final responses = await Future.wait<dynamic>([
13430 api.listAdminIdentityAccounts(),
13431 api.listAdminIdentityUsers(accountId: _accountFilter),
13432 api.listAdminIdentitySessions(),
13433 ]);
13434 final accounts = _mapsFromList(responses[0]);
13435 final normalizedFilter =
13436 _accountFilter != null &&
13437 accounts.any((account) {
13438 return _identityId(account, _IdentitySection.accounts) ==
13439 _accountFilter;
13440 })
13441 ? _accountFilter
13442 : null;
13443 final users = normalizedFilter == _accountFilter
13444 ? _mapsFromList(responses[1])
13445 : _mapsFromList(await api.listAdminIdentityUsers());
13446 final sessions = _mapsFromList(responses[2]);
13447 final rows = _rowsFor(
13448 _section,
13449 accounts: accounts,
13450 users: users,
13451 sessions: sessions,
13452 );
13453 final selected = _selectedForRows(rows);
13454 if (!mounted) return;
13455 setState(() {
13456 _accounts = accounts;
13457 _users = users;
13458 _sessions = sessions;
13459 _accountFilter = normalizedFilter;
13460 _selectedRow = selected;
13461 _selectedId = selected == null ? null : _identityId(selected, _section);
13462 _selectedDetail = null;
13463 _loading = false;
13464 });
13465 if (selected != null) await _loadDetail(_section, selected);
13466 } catch (e) {
13467 if (!mounted) return;
13468 setState(() {
13469 _loading = false;
13470 _error = e.toString();
13471 });
13472 }
13473 }
13474
13475 Future<void> _reloadUsersForFilter(String? accountId) async {
13476 setState(() {
13477 _section = _IdentitySection.users;
13478 _accountFilter = accountId;
13479 _listLoading = true;
13480 _selectedRow = null;
13481 _selectedId = null;
13482 _selectedDetail = null;
13483 _error = null;
13484 });
13485 try {
13486 final raw = await ScrollAPI().listAdminIdentityUsers(
13487 accountId: accountId,
13488 );
13489 final users = _mapsFromList(raw);
13490 final selected = users.isEmpty ? null : users.first;
13491 if (!mounted) return;
13492 setState(() {
13493 _users = users;
13494 _selectedRow = selected;
13495 _selectedId = selected == null
13496 ? null
13497 : _identityId(selected, _IdentitySection.users);
13498 _listLoading = false;
13499 });
13500 if (selected != null) {
13501 await _loadDetail(_IdentitySection.users, selected);
13502 }
13503 } catch (e) {
13504 if (!mounted) return;
13505 setState(() {
13506 _listLoading = false;
13507 _error = e.toString();
13508 });
13509 }
13510 }
13511
13512 Future<void> _setSection(_IdentitySection section) async {
13513 final rows = _rowsFor(section);
13514 final selected = rows.isEmpty ? null : rows.first;
13515 setState(() {
13516 _section = section;
13517 _selectedRow = selected;
13518 _selectedId = selected == null ? null : _identityId(selected, section);
13519 _selectedDetail = null;
13520 });
13521 if (selected != null) await _loadDetail(section, selected);
13522 }
13523
13524 Future<void> _selectRow(Map<String, dynamic> row) async {
13525 setState(() {
13526 _selectedRow = row;
13527 _selectedId = _identityId(row, _section);
13528 _selectedDetail = null;
13529 });
13530 await _loadDetail(_section, row);
13531 }
13532
13533 Future<void> _loadDetail(
13534 _IdentitySection section,
13535 Map<String, dynamic> row,
13536 ) async {
13537 final id = _identityId(row, section);
13538 if (id.isEmpty) return;
13539 setState(() => _detailLoading = true);
13540 final api = ScrollAPI();
13541 final result = switch (section) {
13542 _IdentitySection.accounts => await api.getAdminIdentityAccount(id),
13543 _IdentitySection.users => await api.getAdminIdentityUser(id),
13544 _IdentitySection.sessions => await api.getAdminIdentitySession(id),
13545 };
13546 if (!mounted || _section != section || _selectedId != id) return;
13547 setState(() {
13548 _selectedDetail = result;
13549 _detailLoading = false;
13550 });
13551 }
13552
13553 Future<void> _showSetPasswordDialog() async {
13554 final userId = _selectedUserId;
13555 if (userId == null) return;
13556 final passwordController = TextEditingController();
13557 final confirmController = TextEditingController();
13558 String? validationError;
13559 final submitted = await showDialog<bool>(
13560 context: context,
13561 builder: (dialogContext) {
13562 return StatefulBuilder(
13563 builder: (dialogContext, setDialogState) {
13564 return AlertDialog(
13565 title: Text('Set password for $userId'),
13566 content: SizedBox(
13567 width: 420,
13568 child: Column(
13569 mainAxisSize: MainAxisSize.min,
13570 children: [
13571 TextField(
13572 controller: passwordController,
13573 obscureText: true,
13574 autofocus: true,
13575 decoration: const InputDecoration(
13576 border: OutlineInputBorder(),
13577 labelText: 'New password',
13578 helperText: '8-1024 characters',
13579 ),
13580 ),
13581 const SizedBox(height: 12),
13582 TextField(
13583 controller: confirmController,
13584 obscureText: true,
13585 decoration: const InputDecoration(
13586 border: OutlineInputBorder(),
13587 labelText: 'Confirm password',
13588 ),
13589 ),
13590 if (validationError != null) ...[
13591 const SizedBox(height: 8),
13592 Align(
13593 alignment: Alignment.centerLeft,
13594 child: Text(
13595 validationError!,
13596 style: TextStyle(
13597 fontSize: 12,
13598 color: Colors.red[300],
13599 ),
13600 ),
13601 ),
13602 ],
13603 ],
13604 ),
13605 ),
13606 actions: [
13607 TextButton(
13608 onPressed: () => Navigator.of(dialogContext).pop(false),
13609 child: const Text('Cancel'),
13610 ),
13611 FilledButton.icon(
13612 onPressed: () {
13613 final password = passwordController.text;
13614 if (password.length < 8) {
13615 setDialogState(
13616 () => validationError =
13617 'Password must be at least 8 characters',
13618 );
13619 return;
13620 }
13621 if (password != confirmController.text) {
13622 setDialogState(
13623 () => validationError = 'Passwords do not match',
13624 );
13625 return;
13626 }
13627 Navigator.of(dialogContext).pop(true);
13628 },
13629 icon: const Icon(Icons.password_outlined, size: 16),
13630 label: const Text('Set Password'),
13631 ),
13632 ],
13633 );
13634 },
13635 );
13636 },
13637 );
13638 final password = passwordController.text;
13639 passwordController.dispose();
13640 confirmController.dispose();
13641 if (submitted != true || !mounted) return;
13642 setState(() {
13643 _passwordWriting = true;
13644 _passwordResponse = null;
13645 });
13646 final result = await ScrollAPI().setAdminUserPassword(userId, password);
13647 if (!mounted) return;
13648 setState(() {
13649 _passwordWriting = false;
13650 _passwordResponse = result;
13651 });
13652 }
13653
13654 Future<void> _confirmRemovePassword() async {
13655 final userId = _selectedUserId;
13656 if (userId == null) return;
13657 final confirmed = await showDialog<bool>(
13658 context: context,
13659 builder: (dialogContext) {
13660 return AlertDialog(
13661 title: const Text('Remove password?'),
13662 content: Text(
13663 'DELETE /admin/identity/users/$userId/password\n\n'
13664 'The user can no longer sign in with a password until a new one is set.',
13665 ),
13666 actions: [
13667 TextButton(
13668 onPressed: () => Navigator.of(dialogContext).pop(false),
13669 child: const Text('Cancel'),
13670 ),
13671 FilledButton.icon(
13672 style: FilledButton.styleFrom(backgroundColor: Colors.red[700]),
13673 onPressed: () => Navigator.of(dialogContext).pop(true),
13674 icon: const Icon(Icons.key_off_outlined, size: 16),
13675 label: const Text('Remove Password'),
13676 ),
13677 ],
13678 );
13679 },
13680 );
13681 if (confirmed != true || !mounted) return;
13682 setState(() {
13683 _passwordWriting = true;
13684 _passwordResponse = null;
13685 });
13686 final result = await ScrollAPI().removeAdminUserPassword(userId);
13687 if (!mounted) return;
13688 setState(() {
13689 _passwordWriting = false;
13690 _passwordResponse = result;
13691 });
13692 }
13693
13694 String? get _selectedUserId {
13695 if (_section != _IdentitySection.users) return null;
13696 final row = _selectedRow;
13697 if (row == null) return null;
13698 final id = _identityId(row, _IdentitySection.users);
13699 return id.isEmpty ? null : id;
13700 }
13701
13702 @override
13703 Widget build(BuildContext context) {
13704 return Row(
13705 children: [
13706 Container(
13707 width: 280,
13708 color: Theme.of(context).colorScheme.surfaceContainerLow,
13709 child: Column(
13710 crossAxisAlignment: CrossAxisAlignment.start,
13711 children: [
13712 Padding(
13713 padding: const EdgeInsets.fromLTRB(16, 12, 8, 8),
13714 child: Row(
13715 children: [
13716 Text(
13717 'IDENTITY',
13718 style: TextStyle(
13719 fontSize: 10,
13720 fontWeight: FontWeight.bold,
13721 color: Colors.white38,
13722 letterSpacing: 1,
13723 ),
13724 ),
13725 const Spacer(),
13726 Text(
13727 '${_rowsFor(_section).length}',
13728 style: TextStyle(fontSize: 11, color: Colors.white38),
13729 ),
13730 IconButton(
13731 onPressed: _loading ? null : _loadIdentity,
13732 icon: const Icon(Icons.refresh, size: 16),
13733 tooltip: 'Refresh',
13734 visualDensity: VisualDensity.compact,
13735 ),
13736 ],
13737 ),
13738 ),
13739 _sectionTile(
13740 context,
13741 _IdentitySection.users,
13742 Icons.manage_accounts_outlined,
13743 'Users',
13744 _users.length,
13745 Colors.blue,
13746 ),
13747 _sectionTile(
13748 context,
13749 _IdentitySection.accounts,
13750 Icons.business_outlined,
13751 'Accounts',
13752 _accounts.length,
13753 Colors.teal,
13754 ),
13755 _sectionTile(
13756 context,
13757 _IdentitySection.sessions,
13758 Icons.vpn_key_outlined,
13759 'Sessions',
13760 _sessions.length,
13761 Colors.purple,
13762 ),
13763 const Divider(indent: 16, endIndent: 16),
13764 if (_section == _IdentitySection.users)
13765 Padding(
13766 padding: const EdgeInsets.fromLTRB(12, 4, 12, 8),
13767 child: _accountFilterMenu(context),
13768 ),
13769 Expanded(
13770 child: _loading
13771 ? const Center(child: CircularProgressIndicator())
13772 : _error != null
13773 ? Center(
13774 child: Padding(
13775 padding: const EdgeInsets.all(16),
13776 child: Text(
13777 'Failed to load identity registry',
13778 style: TextStyle(color: Colors.red[300]),
13779 ),
13780 ),
13781 )
13782 : _listLoading
13783 ? const Center(child: CircularProgressIndicator())
13784 : _identityList(context),
13785 ),
13786 ],
13787 ),
13788 ),
13789 Container(width: 1, color: Colors.white10),
13790 Expanded(child: _buildDetail(context)),
13791 ],
13792 );
13793 }
13794
13795 Widget _sectionTile(
13796 BuildContext context,
13797 _IdentitySection section,
13798 IconData icon,
13799 String label,
13800 int count,
13801 Color color,
13802 ) {
13803 final selected = _section == section;
13804 return ListTile(
13805 dense: true,
13806 selected: selected,
13807 selectedTileColor: Theme.of(
13808 context,
13809 ).colorScheme.primaryContainer.withValues(alpha: 0.2),
13810 leading: Icon(
13811 icon,
13812 size: 18,
13813 color: selected ? Theme.of(context).colorScheme.primary : color,
13814 ),
13815 title: Text(label, style: const TextStyle(fontSize: 13)),
13816 trailing: _chip(
13817 '$count',
13818 selected ? Theme.of(context).colorScheme.primary : color,
13819 ),
13820 onTap: () => _setSection(section),
13821 );
13822 }
13823
13824 Widget _accountFilterMenu(BuildContext context) {
13825 final value = _accountFilter ?? '';
13826 final accountsWithIds = _accounts.where((account) {
13827 return _identityId(account, _IdentitySection.accounts).isNotEmpty;
13828 });
13829 return Container(
13830 height: 36,
13831 padding: const EdgeInsets.symmetric(horizontal: 10),
13832 decoration: BoxDecoration(
13833 color: Colors.white.withValues(alpha: 0.04),
13834 borderRadius: BorderRadius.circular(6),
13835 border: Border.all(color: Colors.white10),
13836 ),
13837 child: DropdownButtonHideUnderline(
13838 child: DropdownButton<String>(
13839 value: value,
13840 isExpanded: true,
13841 dropdownColor: Theme.of(context).colorScheme.surfaceContainer,
13842 icon: const Icon(Icons.expand_more, size: 16),
13843 style: const TextStyle(fontSize: 12, color: Colors.white70),
13844 items: [
13845 const DropdownMenuItem(value: '', child: Text('All accounts')),
13846 ...accountsWithIds.map((account) {
13847 final id = _identityId(account, _IdentitySection.accounts);
13848 final label = _identityTitle(account, _IdentitySection.accounts);
13849 return DropdownMenuItem(
13850 value: id,
13851 child: Text(_short(label, 28)),
13852 );
13853 }),
13854 ],
13855 onChanged: _listLoading
13856 ? null
13857 : (next) => _reloadUsersForFilter(
13858 next == null || next.isEmpty ? null : next,
13859 ),
13860 ),
13861 ),
13862 );
13863 }
13864
13865 Widget _identityList(BuildContext context) {
13866 final rows = _rowsFor(_section);
13867 if (rows.isEmpty) {
13868 return Center(
13869 child: Text(
13870 'No ${_sectionLabel(_section).toLowerCase()}',
13871 style: TextStyle(color: Colors.white38),
13872 ),
13873 );
13874 }
13875 return ListView.separated(
13876 padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 4),
13877 itemCount: rows.length,
13878 separatorBuilder: (_, __) => const SizedBox(height: 4),
13879 itemBuilder: (context, index) {
13880 final row = rows[index];
13881 final id = _identityId(row, _section);
13882 final selected = id.isNotEmpty && id == _selectedId;
13883 final status = _identityStatus(row);
13884 final statusColor = _statusColor(status);
13885 return ListTile(
13886 dense: true,
13887 selected: selected,
13888 selectedTileColor: Theme.of(
13889 context,
13890 ).colorScheme.primaryContainer.withValues(alpha: 0.2),
13891 leading: Icon(
13892 _sectionIcon(_section),
13893 size: 18,
13894 color: selected
13895 ? Theme.of(context).colorScheme.primary
13896 : _sectionColor(_section),
13897 ),
13898 title: Text(
13899 _identityTitle(row, _section),
13900 overflow: TextOverflow.ellipsis,
13901 style: TextStyle(
13902 fontSize: 13,
13903 fontFamily: id == _identityTitle(row, _section)
13904 ? 'monospace'
13905 : null,
13906 ),
13907 ),
13908 subtitle: Text(
13909 _identitySubtitle(row, _section),
13910 maxLines: 1,
13911 overflow: TextOverflow.ellipsis,
13912 style: TextStyle(fontSize: 11, color: Colors.white38),
13913 ),
13914 trailing: status.isEmpty ? null : _chip(status, statusColor),
13915 onTap: () => _selectRow(row),
13916 );
13917 },
13918 );
13919 }
13920
13921 Widget _buildDetail(BuildContext context) {
13922 final color = _sectionColor(_section);
13923 return Column(
13924 children: [
13925 Container(
13926 height: 52,
13927 padding: const EdgeInsets.symmetric(horizontal: 16),
13928 decoration: BoxDecoration(
13929 border: Border(bottom: BorderSide(color: Colors.white10)),
13930 ),
13931 child: Row(
13932 children: [
13933 Icon(_sectionIcon(_section), size: 18, color: color),
13934 const SizedBox(width: 8),
13935 Text(
13936 _sectionLabel(_section),
13937 style: const TextStyle(
13938 fontSize: 15,
13939 fontWeight: FontWeight.bold,
13940 ),
13941 ),
13942 const SizedBox(width: 10),
13943 if (_section == _IdentitySection.users &&
13944 ScrollData().passwordLoginEnabled)
13945 _chip('PASSWORD WRITES ADMIN', Colors.orange)
13946 else
13947 _chip('READ ONLY', Colors.green),
13948 const Spacer(),
13949 OutlinedButton.icon(
13950 onPressed: _loading ? null : _loadIdentity,
13951 icon: const Icon(Icons.refresh, size: 16),
13952 label: const Text('Refresh'),
13953 ),
13954 ],
13955 ),
13956 ),
13957 Expanded(
13958 child: _loading
13959 ? const Center(child: CircularProgressIndicator())
13960 : SingleChildScrollView(
13961 padding: const EdgeInsets.all(16),
13962 child: Column(
13963 crossAxisAlignment: CrossAxisAlignment.start,
13964 children: [
13965 Wrap(
13966 spacing: 12,
13967 runSpacing: 12,
13968 children: [
13969 _metric(
13970 Icons.business_outlined,
13971 'Accounts',
13972 '${_accounts.length}',
13973 Colors.teal,
13974 ),
13975 _metric(
13976 Icons.manage_accounts_outlined,
13977 'Users',
13978 '${_users.length}',
13979 Colors.blue,
13980 ),
13981 _metric(
13982 Icons.vpn_key_outlined,
13983 'Sessions',
13984 '${_sessions.length}',
13985 Colors.purple,
13986 ),
13987 ],
13988 ),
13989 const SizedBox(height: 16),
13990 LayoutBuilder(
13991 builder: (context, constraints) {
13992 final overview = _overviewCard(context);
13993 final detail = _detailCard(context);
13994 if (constraints.maxWidth < 900) {
13995 return Column(
13996 children: [
13997 overview,
13998 const SizedBox(height: 12),
13999 detail,
14000 ],
14001 );
14002 }
14003 return Row(
14004 crossAxisAlignment: CrossAxisAlignment.start,
14005 children: [
14006 Expanded(child: overview),
14007 const SizedBox(width: 12),
14008 Expanded(child: detail),
14009 ],
14010 );
14011 },
14012 ),
14013 const SizedBox(height: 16),
14014 _rawPanel('Raw identity payload', {
14015 'section': _sectionLabel(_section).toLowerCase(),
14016 if (_accountFilter != null)
14017 'account_filter': _accountFilter,
14018 'list_row': _selectedRow,
14019 'detail': _selectedDetail,
14020 }),
14021 ],
14022 ),
14023 ),
14024 ),
14025 ],
14026 );
14027 }
14028
14029 Widget _overviewCard(BuildContext context) {
14030 final rows = _rowsFor(_section);
14031 final selected = _selectedRow ?? const <String, dynamic>{};
14032 return _framed(
14033 context,
14034 title: '${_sectionLabel(_section)} List Row',
14035 icon: Icons.list_alt_outlined,
14036 color: _sectionColor(_section),
14037 trailing: _chip(
14038 rows.isEmpty ? 'EMPTY' : '${rows.length}',
14039 _sectionColor(_section),
14040 ),
14041 expandChild: false,
14042 child: rows.isEmpty
14043 ? Text('Not reported', style: TextStyle(color: Colors.white38))
14044 : Column(
14045 children: _orderedRows(selected).map((entry) {
14046 return _infoRow(entry.key, entry.value);
14047 }).toList(),
14048 ),
14049 );
14050 }
14051
14052 Widget _detailCard(BuildContext context) {
14053 final row = _selectedRow;
14054 final detail = {
14055 if (row != null) ...row,
14056 if (_selectedDetail != null) ..._selectedDetail!,
14057 };
14058 return _framed(
14059 context,
14060 title: '${_singularLabel(_section)} Detail',
14061 icon: Icons.info_outline,
14062 color: Colors.blue,
14063 trailing: _section == _IdentitySection.users
14064 ? _passwordActions()
14065 : _chip('READ ONLY', Colors.green),
14066 expandChild: false,
14067 child: _detailLoading
14068 ? const Center(child: CircularProgressIndicator())
14069 : detail.isEmpty
14070 ? Text(
14071 'No ${_sectionLabel(_section).toLowerCase()} selected',
14072 style: TextStyle(color: Colors.white38),
14073 )
14074 : Column(
14075 children: [
14076 ..._orderedRows(detail).map((entry) {
14077 return _infoRow(entry.key, entry.value);
14078 }),
14079 if (_passwordResponse != null) _passwordResponsePanel(),
14080 ],
14081 ),
14082 );
14083 }
14084
14085 Widget _passwordActions() {
14086 final enabled = ScrollData().passwordLoginEnabled;
14087 final canWrite = enabled && !_passwordWriting && _selectedUserId != null;
14088 return Row(
14089 mainAxisSize: MainAxisSize.min,
14090 children: [
14091 Tooltip(
14092 message: enabled
14093 ? 'Set through POST /admin/identity/users/{user_id}/password'
14094 : 'Password writes are locked: /admin/status.capabilities.identity.password_login_enabled is false',
14095 child: OutlinedButton.icon(
14096 onPressed: canWrite ? _showSetPasswordDialog : null,
14097 icon: const Icon(Icons.password_outlined, size: 14),
14098 label: Text(enabled ? 'Set Password' : 'Password locked'),
14099 ),
14100 ),
14101 const SizedBox(width: 8),
14102 Tooltip(
14103 message: enabled
14104 ? 'Remove through DELETE /admin/identity/users/{user_id}/password'
14105 : 'Password writes are locked: /admin/status.capabilities.identity.password_login_enabled is false',
14106 child: OutlinedButton.icon(
14107 style: OutlinedButton.styleFrom(foregroundColor: Colors.red),
14108 onPressed: canWrite ? _confirmRemovePassword : null,
14109 icon: const Icon(Icons.key_off_outlined, size: 14),
14110 label: const Text('Remove'),
14111 ),
14112 ),
14113 ],
14114 );
14115 }
14116
14117 Widget _passwordResponsePanel() {
14118 final response = _passwordResponse ?? const <String, dynamic>{};
14119 final status = response['status'];
14120 final ok = status is int && status >= 200 && status < 300;
14121 final color = ok ? Colors.green : Colors.red;
14122 return Container(
14123 width: double.infinity,
14124 margin: const EdgeInsets.only(top: 10),
14125 padding: const EdgeInsets.all(10),
14126 decoration: BoxDecoration(
14127 color: color.withValues(alpha: 0.06),
14128 borderRadius: BorderRadius.circular(8),
14129 border: Border.all(color: color.withValues(alpha: 0.18)),
14130 ),
14131 child: Row(
14132 crossAxisAlignment: CrossAxisAlignment.start,
14133 children: [
14134 Expanded(
14135 child: SelectableText(
14136 const JsonEncoder.withIndent(' ').convert(response),
14137 maxLines: 6,
14138 style: const TextStyle(
14139 fontFamily: 'monospace',
14140 fontSize: 11,
14141 height: 1.3,
14142 ),
14143 ),
14144 ),
14145 IconButton(
14146 onPressed: () => setState(() => _passwordResponse = null),
14147 icon: const Icon(Icons.close, size: 14),
14148 tooltip: 'Dismiss',
14149 visualDensity: VisualDensity.compact,
14150 ),
14151 ],
14152 ),
14153 );
14154 }
14155
14156 Widget _metric(IconData icon, String label, String value, Color color) {
14157 return Container(
14158 width: 150,
14159 padding: const EdgeInsets.all(12),
14160 decoration: BoxDecoration(
14161 color: color.withValues(alpha: 0.08),
14162 borderRadius: BorderRadius.circular(8),
14163 border: Border.all(color: color.withValues(alpha: 0.2)),
14164 ),
14165 child: Row(
14166 children: [
14167 Icon(icon, size: 18, color: color),
14168 const SizedBox(width: 8),
14169 Expanded(
14170 child: Column(
14171 crossAxisAlignment: CrossAxisAlignment.start,
14172 children: [
14173 Text(
14174 label,
14175 overflow: TextOverflow.ellipsis,
14176 style: TextStyle(fontSize: 11, color: Colors.white38),
14177 ),
14178 Text(
14179 value,
14180 overflow: TextOverflow.ellipsis,
14181 style: const TextStyle(
14182 fontSize: 15,
14183 fontWeight: FontWeight.w600,
14184 ),
14185 ),
14186 ],
14187 ),
14188 ),
14189 ],
14190 ),
14191 );
14192 }
14193
14194 Widget _framed(
14195 BuildContext context, {
14196 required String title,
14197 required IconData icon,
14198 required Color color,
14199 required Widget child,
14200 Widget? trailing,
14201 bool expandChild = true,
14202 }) {
14203 return Container(
14204 padding: const EdgeInsets.all(14),
14205 decoration: BoxDecoration(
14206 color: Theme.of(context).colorScheme.surfaceContainerLow,
14207 borderRadius: BorderRadius.circular(8),
14208 border: Border.all(color: Colors.white10),
14209 ),
14210 child: Column(
14211 crossAxisAlignment: CrossAxisAlignment.start,
14212 children: [
14213 Row(
14214 children: [
14215 Icon(icon, size: 18, color: color),
14216 const SizedBox(width: 8),
14217 Text(
14218 title,
14219 style: const TextStyle(
14220 fontSize: 13,
14221 fontWeight: FontWeight.w700,
14222 ),
14223 ),
14224 const Spacer(),
14225 if (trailing != null) trailing,
14226 ],
14227 ),
14228 const SizedBox(height: 12),
14229 if (expandChild) Expanded(child: child) else child,
14230 ],
14231 ),
14232 );
14233 }
14234
14235 Widget _infoRow(String label, dynamic value) {
14236 return Padding(
14237 padding: const EdgeInsets.only(bottom: 7),
14238 child: Row(
14239 crossAxisAlignment: CrossAxisAlignment.start,
14240 children: [
14241 Expanded(
14242 flex: 5,
14243 child: Text(
14244 _titleCase(label),
14245 overflow: TextOverflow.ellipsis,
14246 style: TextStyle(fontSize: 12, color: Colors.white54),
14247 ),
14248 ),
14249 const SizedBox(width: 10),
14250 Expanded(
14251 flex: 7,
14252 child: Text(
14253 _valueText(_safeValue(label, value)),
14254 maxLines: 3,
14255 overflow: TextOverflow.ellipsis,
14256 textAlign: TextAlign.right,
14257 style: TextStyle(
14258 fontSize: 12,
14259 color: Colors.white70,
14260 fontWeight: FontWeight.w600,
14261 ),
14262 ),
14263 ),
14264 ],
14265 ),
14266 );
14267 }
14268
14269 Widget _rawPanel(String title, Map<String, dynamic> value) {
14270 return ExpansionTile(
14271 tilePadding: const EdgeInsets.symmetric(horizontal: 4),
14272 title: Text(title, style: TextStyle(fontSize: 12, color: Colors.white54)),
14273 children: [
14274 Container(
14275 width: double.infinity,
14276 padding: const EdgeInsets.all(12),
14277 decoration: BoxDecoration(
14278 color: Colors.black26,
14279 borderRadius: BorderRadius.circular(8),
14280 border: Border.all(color: Colors.white10),
14281 ),
14282 child: SelectableText(
14283 const JsonEncoder.withIndent(' ').convert(_redacted(value)),
14284 style: const TextStyle(
14285 fontFamily: 'monospace',
14286 fontSize: 11,
14287 height: 1.35,
14288 ),
14289 ),
14290 ),
14291 ],
14292 );
14293 }
14294
14295 Widget _chip(String text, Color color) {
14296 return Container(
14297 padding: const EdgeInsets.symmetric(horizontal: 7, vertical: 2),
14298 decoration: BoxDecoration(
14299 color: color.withValues(alpha: 0.1),
14300 borderRadius: BorderRadius.circular(4),
14301 border: Border.all(color: color.withValues(alpha: 0.16)),
14302 ),
14303 child: Text(
14304 _short(text, 44),
14305 overflow: TextOverflow.ellipsis,
14306 style: TextStyle(
14307 fontSize: 10,
14308 color: color,
14309 fontWeight: FontWeight.bold,
14310 ),
14311 ),
14312 );
14313 }
14314
14315 List<Map<String, dynamic>> _mapsFromList(dynamic value) {
14316 if (value is! List) return const [];
14317 return value.map(_mapFromDynamic).toList();
14318 }
14319
14320 List<Map<String, dynamic>> _rowsFor(
14321 _IdentitySection section, {
14322 List<Map<String, dynamic>>? accounts,
14323 List<Map<String, dynamic>>? users,
14324 List<Map<String, dynamic>>? sessions,
14325 }) {
14326 return switch (section) {
14327 _IdentitySection.accounts => accounts ?? _accounts,
14328 _IdentitySection.users => users ?? _users,
14329 _IdentitySection.sessions => sessions ?? _sessions,
14330 };
14331 }
14332
14333 Map<String, dynamic>? _selectedForRows(List<Map<String, dynamic>> rows) {
14334 if (rows.isEmpty) return null;
14335 final current = _selectedId;
14336 if (current != null) {
14337 for (final row in rows) {
14338 if (_identityId(row, _section) == current) return row;
14339 }
14340 }
14341 return rows.first;
14342 }
14343
14344 List<MapEntry<String, dynamic>> _orderedRows(Map<String, dynamic> values) {
14345 final preferred = [
14346 'id',
14347 'account_id',
14348 'user_id',
14349 'session_id',
14350 'email',
14351 'username',
14352 'name',
14353 'role',
14354 'status',
14355 'state',
14356 'active',
14357 'created_at',
14358 'updated_at',
14359 'expires_at',
14360 'revoked_at',
14361 'last_seen_at',
14362 'description',
14363 ];
14364 final rows = <MapEntry<String, dynamic>>[];
14365 final used = <String>{};
14366 for (final key in preferred) {
14367 final value = values[key];
14368 if (_hasValue(value)) {
14369 rows.add(MapEntry(key, value));
14370 used.add(key);
14371 }
14372 }
14373 for (final entry in values.entries) {
14374 if (used.contains(entry.key) || !_hasValue(entry.value)) continue;
14375 rows.add(entry);
14376 }
14377 return rows.take(14).toList();
14378 }
14379
14380 Map<String, dynamic> _mapFromDynamic(dynamic value) {
14381 if (value is Map<String, dynamic>) return value;
14382 if (value is Map) {
14383 return value.map((key, item) => MapEntry(key.toString(), item));
14384 }
14385 if (value is String) return {'id': value};
14386 return {'value': value};
14387 }
14388
14389 String _identityId(Map<String, dynamic> row, _IdentitySection section) {
14390 final keys = switch (section) {
14391 _IdentitySection.accounts => const [
14392 'account_id',
14393 'id',
14394 'account',
14395 'name',
14396 'key',
14397 ],
14398 _IdentitySection.users => const [
14399 'user_id',
14400 'id',
14401 'email',
14402 'username',
14403 'name',
14404 ],
14405 _IdentitySection.sessions => const ['session_id', 'id', 'key', 'name'],
14406 };
14407 for (final key in keys) {
14408 final value = row[key];
14409 if (_hasValue(value)) return value.toString();
14410 }
14411 return '';
14412 }
14413
14414 String _identityTitle(Map<String, dynamic> row, _IdentitySection section) {
14415 final keys = switch (section) {
14416 _IdentitySection.accounts => const ['name', 'slug', 'account_id', 'id'],
14417 _IdentitySection.users => const [
14418 'email',
14419 'username',
14420 'display_name',
14421 'name',
14422 'user_id',
14423 'id',
14424 ],
14425 _IdentitySection.sessions => const [
14426 'session_id',
14427 'id',
14428 'user_id',
14429 'account_id',
14430 ],
14431 };
14432 for (final key in keys) {
14433 final value = row[key];
14434 if (_hasValue(value)) return value.toString();
14435 }
14436 return _singularLabel(section).toLowerCase();
14437 }
14438
14439 String _identitySubtitle(Map<String, dynamic> row, _IdentitySection section) {
14440 final keys = switch (section) {
14441 _IdentitySection.accounts => const ['account_id', 'status', 'created_at'],
14442 _IdentitySection.users => const [
14443 'account_id',
14444 'role',
14445 'status',
14446 'created_at',
14447 ],
14448 _IdentitySection.sessions => const [
14449 'user_id',
14450 'account_id',
14451 'status',
14452 'expires_at',
14453 'revoked_at',
14454 ],
14455 };
14456 final parts = <String>[];
14457 for (final key in keys) {
14458 final value = row[key];
14459 if (!_hasValue(value)) continue;
14460 parts.add('${_titleCase(key)}: ${_valueText(_safeValue(key, value))}');
14461 if (parts.length == 3) break;
14462 }
14463 return parts.isEmpty ? _identityId(row, section) : parts.join(' ');
14464 }
14465
14466 String _identityStatus(Map<String, dynamic> row) {
14467 final value =
14468 row['status'] ??
14469 row['state'] ??
14470 row['active'] ??
14471 row['revoked'] ??
14472 row['enabled'];
14473 if (!_hasValue(value)) return '';
14474 if (value is bool) return value ? 'active' : 'inactive';
14475 return value.toString();
14476 }
14477
14478 IconData _sectionIcon(_IdentitySection section) {
14479 return switch (section) {
14480 _IdentitySection.accounts => Icons.business_outlined,
14481 _IdentitySection.users => Icons.manage_accounts_outlined,
14482 _IdentitySection.sessions => Icons.vpn_key_outlined,
14483 };
14484 }
14485
14486 Color _sectionColor(_IdentitySection section) {
14487 return switch (section) {
14488 _IdentitySection.accounts => Colors.teal,
14489 _IdentitySection.users => Colors.blue,
14490 _IdentitySection.sessions => Colors.purple,
14491 };
14492 }
14493
14494 String _sectionLabel(_IdentitySection section) {
14495 return switch (section) {
14496 _IdentitySection.accounts => 'Accounts',
14497 _IdentitySection.users => 'Users',
14498 _IdentitySection.sessions => 'Sessions',
14499 };
14500 }
14501
14502 String _singularLabel(_IdentitySection section) {
14503 return switch (section) {
14504 _IdentitySection.accounts => 'Account',
14505 _IdentitySection.users => 'User',
14506 _IdentitySection.sessions => 'Session',
14507 };
14508 }
14509
14510 Color _statusColor(String status) {
14511 final normalized = status.toLowerCase();
14512 if (normalized.contains('active') ||
14513 normalized.contains('ok') ||
14514 normalized.contains('enabled')) {
14515 return Colors.green;
14516 }
14517 if (normalized.contains('revoked') ||
14518 normalized.contains('expired') ||
14519 normalized.contains('disabled') ||
14520 normalized.contains('inactive')) {
14521 return Colors.orange;
14522 }
14523 return Colors.white54;
14524 }
14525
14526 dynamic _safeValue(String key, dynamic value) {
14527 if (_shouldRedact(key) && value is! bool && value != null) {
14528 return '[redacted]';
14529 }
14530 return _redacted(value);
14531 }
14532
14533 dynamic _redacted(dynamic value, [String key = '']) {
14534 if (_shouldRedact(key) && value is! bool && value != null) {
14535 return '[redacted]';
14536 }
14537 if (value is Map) {
14538 return value.map((itemKey, itemValue) {
14539 final stringKey = itemKey.toString();
14540 return MapEntry(stringKey, _redacted(itemValue, stringKey));
14541 });
14542 }
14543 if (value is List) {
14544 return value.map((item) => _redacted(item, key)).toList();
14545 }
14546 return value;
14547 }
14548
14549 bool _shouldRedact(String key) {
14550 final normalized = key.toLowerCase();
14551 return normalized.contains('token') ||
14552 normalized.contains('secret') ||
14553 normalized.contains('password') ||
14554 normalized.contains('authorization') ||
14555 normalized.contains('credential') ||
14556 normalized == 'hash' ||
14557 normalized.endsWith('_hash');
14558 }
14559
14560 bool _hasValue(dynamic value) {
14561 if (value == null) return false;
14562 if (value is String) return value.trim().isNotEmpty;
14563 if (value is List) return value.isNotEmpty;
14564 if (value is Map) return value.isNotEmpty;
14565 return true;
14566 }
14567
14568 String _valueText(dynamic value) {
14569 if (value == null) return '?';
14570 if (value is bool) return value ? 'yes' : 'no';
14571 if (value is List) return '${value.length} items';
14572 if (value is Map) {
14573 final entries = value.entries.take(3).map((entry) {
14574 return '${_titleCase(entry.key.toString())}: ${_valueText(entry.value)}';
14575 });
14576 return entries.join(', ');
14577 }
14578 return value.toString();
14579 }
14580
14581 String _titleCase(String value) {
14582 return value
14583 .replaceAll('_', ' ')
14584 .replaceAll('-', ' ')
14585 .split(' ')
14586 .where((part) => part.isNotEmpty)
14587 .map((part) => '${part[0].toUpperCase()}${part.substring(1)}')
14588 .join(' ');
14589 }
14590
14591 String _short(String value, int limit) {
14592 if (value.length <= limit) return value;
14593 return '${value.substring(0, limit)}...';
14594 }
14595}
14596
14597// ---------------------------------------------------------------------------
14598// Changes (admin read-only timeline)
14599// ---------------------------------------------------------------------------
14600
14601// ---------------------------------------------------------------------------
14602// AI CHAT — POST /api/ai/chat. One conversation turn per request, using the
14603// caller's server-stored provider key (Settings → Server AI Keys). Tool
14604// calls dispatch with the caller's own credentials: the AI can do exactly
14605// what this session could, permission-checked and audited.
14606// ---------------------------------------------------------------------------
14607
14608class AIChatView extends StatefulWidget {
14609 const AIChatView({super.key});
14610
14611 @override
14612 State<AIChatView> createState() => _AIChatViewState();
14613}
14614
14615class _ChatTurn {
14616 _ChatTurn({required this.question});
14617
14618 final String question;
14619 String? reply;
14620 List<dynamic> toolCalls = const [];
14621 Map<String, dynamic>? usage;
14622 String? error;
14623 bool pending = true;
14624}
14625
14626class _AIChatViewState extends State<AIChatView> {
14627 final _messageController = TextEditingController();
14628 final _toolsController = TextEditingController(
14629 text: 'global_search, list_collections',
14630 );
14631 final _chatScroll = ScrollController();
14632 final List<_ChatTurn> _turns = [];
14633 String _model = 'anthropic:claude-haiku-4-5';
14634 bool _sending = false;
14635 int _replayedTurns = 0;
14636 bool _prefsRecordExists = false;
14637
14638 static const _models = [
14639 'anthropic:claude-haiku-4-5',
14640 'anthropic:claude-sonnet-5',
14641 'anthropic:claude-opus-4-8',
14642 'openai:gpt-4o-mini',
14643 'openai:gpt-4o',
14644 ];
14645
14646 @override
14647 void initState() {
14648 super.initState();
14649 _loadShellState();
14650 }
14651
14652 @override
14653 void dispose() {
14654 _messageController.dispose();
14655 _toolsController.dispose();
14656 _chatScroll.dispose();
14657 super.dispose();
14658 }
14659
14660 List<String> get _tools => [
14661 for (final tool in _toolsController.text.split(','))
14662 if (tool.trim().isNotEmpty) tool.trim(),
14663 ];
14664
14665 /// Preferences + history live in shell_preferences / shell_commands
14666 /// records shared with the web /shell page, so both surfaces stay in
14667 /// sync and a conversation continues across them.
14668 Future<void> _loadShellState() async {
14669 final api = ScrollAPI();
14670 final userId = api.sessionUserId;
14671 if (userId == null) return;
14672
14673 final prefsResult = await api.getUserCollectionRecord(
14674 'shell_preferences',
14675 userId,
14676 );
14677 if (!mounted) return;
14678 final prefsBody = prefsResult['body'];
14679 final prefs = prefsBody is Map
14680 ? (prefsBody['record'] is Map ? prefsBody['record'] as Map : prefsBody)
14681 : null;
14682 final prefsStatus = prefsResult['status'];
14683 if (prefsStatus is int && prefsStatus >= 200 && prefsStatus < 300) {
14684 _prefsRecordExists = true;
14685 final model = prefs?['model']?.toString();
14686 final tools = prefs?['tools'];
14687 setState(() {
14688 if (model != null && model.isNotEmpty) _model = model;
14689 if (tools is List && tools.isNotEmpty) {
14690 _toolsController.text = tools.join(', ');
14691 } else if (tools is String && tools.trim().isNotEmpty) {
14692 _toolsController.text = tools;
14693 }
14694 });
14695 }
14696
14697 final logResult = await api.listUserCollectionRecords(
14698 'shell_commands',
14699 limit: 200,
14700 );
14701 if (!mounted || _turns.isNotEmpty) return;
14702 final logBody = logResult['body'];
14703 final rows = logBody is Map && logBody['records'] is List
14704 ? (logBody['records'] as List)
14705 : const [];
14706 final aiRows = [
14707 for (final row in rows)
14708 if (row is Map && row['kind']?.toString() == 'ai') row,
14709 ]..sort((a, b) => '${a['created_at']}'.compareTo('${b['created_at']}'));
14710 final replay = aiRows.length > 30
14711 ? aiRows.sublist(aiRows.length - 30)
14712 : aiRows;
14713 final turns = <_ChatTurn>[];
14714 for (final row in replay) {
14715 final question =
14716 (row['input'] ?? row['message'] ?? row['command'] ?? row['text'])
14717 ?.toString();
14718 final reply = (row['reply'] ?? row['response'] ?? row['output'])
14719 ?.toString();
14720 if (question == null || question.isEmpty) continue;
14721 turns.add(
14722 _ChatTurn(question: question)
14723 ..pending = false
14724 ..reply = reply,
14725 );
14726 }
14727 if (turns.isEmpty) return;
14728 setState(() {
14729 _turns.addAll(turns);
14730 _replayedTurns = turns.length;
14731 });
14732 _scrollToEnd();
14733 }
14734
14735 Future<void> _persistPreferences() async {
14736 final api = ScrollAPI();
14737 final userId = api.sessionUserId;
14738 if (userId == null) return;
14739 final changes = {'model': _model, 'tools': _tools};
14740 final result = _prefsRecordExists
14741 ? await api.putUserCollectionRecord(
14742 'shell_preferences',
14743 userId,
14744 changes,
14745 )
14746 : await api.createUserCollectionRecord('shell_preferences', {
14747 'id': userId,
14748 ...changes,
14749 });
14750 final status = result['status'];
14751 if (status is int && status >= 200 && status < 300) {
14752 _prefsRecordExists = true;
14753 }
14754 }
14755
14756 /// Prior completed turns as [{role, content}] — the server caps history
14757 /// at 40 entries, so send at most the last 20 exchanges.
14758 List<Map<String, String>> _historyPayload() {
14759 final history = <Map<String, String>>[];
14760 for (final turn in _turns) {
14761 if (turn.pending || turn.reply == null) continue;
14762 history.add({'role': 'user', 'content': turn.question});
14763 history.add({'role': 'assistant', 'content': turn.reply!});
14764 }
14765 return history.length > 40 ? history.sublist(history.length - 40) : history;
14766 }
14767
14768 Future<void> _send() async {
14769 final message = _messageController.text.trim();
14770 if (message.isEmpty || _sending) return;
14771 final history = _historyPayload();
14772 final turn = _ChatTurn(question: message);
14773 setState(() {
14774 _turns.add(turn);
14775 _sending = true;
14776 _messageController.clear();
14777 });
14778 _scrollToEnd();
14779 final result = await ScrollAPI().aiChat(
14780 message: message,
14781 model: _model,
14782 tools: _tools,
14783 history: history,
14784 );
14785 if (!mounted) return;
14786 final status = result['status'];
14787 final body = result['body'];
14788 setState(() {
14789 turn.pending = false;
14790 _sending = false;
14791 if (status is int && status >= 200 && status < 300 && body is Map) {
14792 turn.reply = (body['reply'] ?? body['message'] ?? body['content'])
14793 ?.toString();
14794 turn.toolCalls = body['tool_calls'] is List
14795 ? body['tool_calls'] as List
14796 : const [];
14797 turn.usage = body['usage'] is Map
14798 ? Map<String, dynamic>.from(body['usage'] as Map)
14799 : null;
14800 if (turn.reply == null) {
14801 turn.error = 'No reply in response: ${jsonEncode(body)}';
14802 }
14803 } else {
14804 final detail = body is Map && body['error'] != null
14805 ? body['error'].toString()
14806 : (result['error']?.toString() ?? jsonEncode(body));
14807 turn.error = 'HTTP ${status ?? '?'} — $detail';
14808 }
14809 });
14810 _scrollToEnd();
14811 }
14812
14813 void _scrollToEnd() {
14814 WidgetsBinding.instance.addPostFrameCallback((_) {
14815 if (_chatScroll.hasClients) {
14816 _chatScroll.animateTo(
14817 _chatScroll.position.maxScrollExtent,
14818 duration: const Duration(milliseconds: 200),
14819 curve: Curves.easeOut,
14820 );
14821 }
14822 });
14823 }
14824
14825 @override
14826 Widget build(BuildContext context) {
14827 final needsUser = ScrollAPI().sessionUserId == null;
14828 return Padding(
14829 padding: const EdgeInsets.all(16),
14830 child: Column(
14831 crossAxisAlignment: CrossAxisAlignment.start,
14832 children: [
14833 Row(
14834 children: [
14835 Text('AI Chat', style: Theme.of(context).textTheme.titleLarge),
14836 const SizedBox(width: 8),
14837 _chatChip('POST /api/ai/chat', Colors.blue),
14838 const SizedBox(width: 8),
14839 _chatChip('CALLER-SCOPED TOOLS', Colors.green),
14840 const Spacer(),
14841 DropdownButton<String>(
14842 value: _model,
14843 style: const TextStyle(fontSize: 12, color: Colors.white70),
14844 dropdownColor: Theme.of(context).colorScheme.surfaceContainer,
14845 items: {..._models, _model}
14846 .map(
14847 (model) =>
14848 DropdownMenuItem(value: model, child: Text(model)),
14849 )
14850 .toList(),
14851 onChanged: (value) {
14852 if (value == null) return;
14853 setState(() => _model = value);
14854 _persistPreferences();
14855 },
14856 ),
14857 ],
14858 ),
14859 const SizedBox(height: 8),
14860 TextField(
14861 controller: _toolsController,
14862 onSubmitted: (_) => _persistPreferences(),
14863 onEditingComplete: _persistPreferences,
14864 decoration: const InputDecoration(
14865 labelText: 'Tools (comma-separated MCP tool names)',
14866 helperText:
14867 'Any subset of the server\'s MCP catalog — a small list '
14868 'keeps fast models fast. Empty = no tools. Model + tools '
14869 'sync with the web /shell via shell_preferences.',
14870 border: OutlineInputBorder(),
14871 isDense: true,
14872 ),
14873 style: const TextStyle(fontSize: 12, fontFamily: 'monospace'),
14874 ),
14875 if (needsUser)
14876 Padding(
14877 padding: const EdgeInsets.only(top: 8),
14878 child: Text(
14879 'Chat uses a provider key stored for YOUR user on the '
14880 'server (Settings → Server AI Keys). Sign in with email + '
14881 'password first — a deployment token has no user to hold '
14882 'a key.',
14883 style: TextStyle(fontSize: 12, color: Colors.amber[300]),
14884 ),
14885 ),
14886 const SizedBox(height: 12),
14887 Expanded(
14888 child: _turns.isEmpty
14889 ? const Center(
14890 child: Text(
14891 'Ask the server\'s AI anything — it can call the MCP '
14892 'tools above with your session\'s permissions.\n'
14893 'Conversations continue across Scroll and the web '
14894 '/shell page.',
14895 textAlign: TextAlign.center,
14896 style: TextStyle(color: Colors.white38, fontSize: 13),
14897 ),
14898 )
14899 : ListView(
14900 controller: _chatScroll,
14901 children: [
14902 if (_replayedTurns > 0)
14903 Padding(
14904 padding: const EdgeInsets.only(bottom: 4),
14905 child: Text(
14906 '↺ resumed $_replayedTurns turn'
14907 '${_replayedTurns == 1 ? '' : 's'} from the '
14908 'shell log',
14909 style: const TextStyle(
14910 fontSize: 11,
14911 color: Colors.white30,
14912 ),
14913 ),
14914 ),
14915 for (final turn in _turns) _turnWidget(turn),
14916 ],
14917 ),
14918 ),
14919 const SizedBox(height: 12),
14920 Row(
14921 children: [
14922 Expanded(
14923 child: TextField(
14924 controller: _messageController,
14925 onSubmitted: (_) => _send(),
14926 decoration: InputDecoration(
14927 hintText: 'Message the server\'s AI...',
14928 border: OutlineInputBorder(
14929 borderRadius: BorderRadius.circular(8),
14930 ),
14931 isDense: true,
14932 ),
14933 style: const TextStyle(fontSize: 13),
14934 ),
14935 ),
14936 const SizedBox(width: 10),
14937 FilledButton.icon(
14938 onPressed: _sending ? null : _send,
14939 icon: _sending
14940 ? const SizedBox(
14941 width: 14,
14942 height: 14,
14943 child: CircularProgressIndicator(strokeWidth: 2),
14944 )
14945 : const Icon(Icons.send, size: 16),
14946 label: const Text('Send'),
14947 ),
14948 ],
14949 ),
14950 ],
14951 ),
14952 );
14953 }
14954
14955 Widget _turnWidget(_ChatTurn turn) {
14956 return Column(
14957 crossAxisAlignment: CrossAxisAlignment.start,
14958 children: [
14959 Align(
14960 alignment: Alignment.centerRight,
14961 child: Container(
14962 margin: const EdgeInsets.only(top: 10, bottom: 6, left: 80),
14963 padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
14964 decoration: BoxDecoration(
14965 color: Colors.blue.withValues(alpha: 0.15),
14966 borderRadius: BorderRadius.circular(10),
14967 ),
14968 child: SelectableText(
14969 turn.question,
14970 style: const TextStyle(fontSize: 13),
14971 ),
14972 ),
14973 ),
14974 if (turn.pending)
14975 const Padding(
14976 padding: EdgeInsets.symmetric(vertical: 8),
14977 child: SizedBox(
14978 width: 16,
14979 height: 16,
14980 child: CircularProgressIndicator(strokeWidth: 2),
14981 ),
14982 ),
14983 if (turn.error != null)
14984 Container(
14985 margin: const EdgeInsets.only(bottom: 6, right: 80),
14986 padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
14987 decoration: BoxDecoration(
14988 color: Colors.red.withValues(alpha: 0.12),
14989 borderRadius: BorderRadius.circular(10),
14990 ),
14991 child: SelectableText(
14992 turn.error!,
14993 style: TextStyle(fontSize: 12, color: Colors.red[200]),
14994 ),
14995 ),
14996 if (turn.toolCalls.isNotEmpty)
14997 Container(
14998 margin: const EdgeInsets.only(bottom: 6, right: 80),
14999 decoration: BoxDecoration(
15000 color: Colors.white.withValues(alpha: 0.03),
15001 borderRadius: BorderRadius.circular(10),
15002 border: Border.all(color: Colors.white10),
15003 ),
15004 child: Theme(
15005 data: Theme.of(
15006 context,
15007 ).copyWith(dividerColor: Colors.transparent),
15008 child: ExpansionTile(
15009 dense: true,
15010 tilePadding: const EdgeInsets.symmetric(horizontal: 12),
15011 title: Text(
15012 '${turn.toolCalls.length} tool call'
15013 '${turn.toolCalls.length == 1 ? '' : 's'}',
15014 style: const TextStyle(fontSize: 12, color: Colors.white54),
15015 ),
15016 children: [
15017 Padding(
15018 padding: const EdgeInsets.fromLTRB(12, 0, 12, 12),
15019 child: SelectableText(
15020 const JsonEncoder.withIndent(
15021 ' ',
15022 ).convert(turn.toolCalls),
15023 style: const TextStyle(
15024 fontFamily: 'monospace',
15025 fontSize: 11,
15026 color: Colors.white70,
15027 ),
15028 ),
15029 ),
15030 ],
15031 ),
15032 ),
15033 ),
15034 if (turn.reply != null)
15035 Container(
15036 margin: const EdgeInsets.only(bottom: 4, right: 80),
15037 padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
15038 decoration: BoxDecoration(
15039 color: Colors.white.withValues(alpha: 0.05),
15040 borderRadius: BorderRadius.circular(10),
15041 ),
15042 child: SelectableText(
15043 turn.reply!,
15044 style: const TextStyle(fontSize: 13, height: 1.4),
15045 ),
15046 ),
15047 if (turn.usage != null)
15048 Padding(
15049 padding: const EdgeInsets.only(bottom: 6),
15050 child: Text(
15051 turn.usage!.entries
15052 .map((entry) => '${entry.key}: ${entry.value}')
15053 .join(' · '),
15054 style: const TextStyle(fontSize: 10, color: Colors.white30),
15055 ),
15056 ),
15057 ],
15058 );
15059 }
15060
15061 Widget _chatChip(String label, Color color) {
15062 return Container(
15063 padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
15064 decoration: BoxDecoration(
15065 color: color.withValues(alpha: 0.15),
15066 borderRadius: BorderRadius.circular(4),
15067 ),
15068 child: Text(
15069 label,
15070 style: TextStyle(
15071 fontSize: 10,
15072 fontWeight: FontWeight.w600,
15073 color: color,
15074 ),
15075 ),
15076 );
15077 }
15078}
15079
15080// ---------------------------------------------------------------------------
15081// GLOBAL SEARCH — GET /api/search across searchable collections. Results
15082// arrive per-collection; each group renders under its schema's
15083// views.list_mode (table | cards | feed) and views.list_fields.
15084// ---------------------------------------------------------------------------
15085
15086class GlobalSearchView extends StatefulWidget {
15087 const GlobalSearchView({super.key});
15088
15089 @override
15090 State<GlobalSearchView> createState() => _GlobalSearchViewState();
15091}
15092
15093class _GlobalSearchViewState extends State<GlobalSearchView> {
15094 final _queryController = TextEditingController();
15095 final _queryFocus = FocusNode();
15096 Map<String, dynamic>? _response;
15097 final Map<String, SchemaFormSpec> _specs = {};
15098 bool _loading = false;
15099 String? _error;
15100 String? _searchedQuery;
15101
15102 @override
15103 void dispose() {
15104 _queryController.dispose();
15105 _queryFocus.dispose();
15106 super.dispose();
15107 }
15108
15109 Future<void> _search() async {
15110 final query = _queryController.text.trim();
15111 if (query.isEmpty) return;
15112 setState(() {
15113 _loading = true;
15114 _error = null;
15115 _searchedQuery = query;
15116 });
15117 final response = await ScrollAPI().globalSearch(query, limit: 25);
15118 if (!mounted) return;
15119 if (response == null) {
15120 setState(() {
15121 _loading = false;
15122 _error = ScrollAPI().lastError ?? 'Search request failed';
15123 });
15124 return;
15125 }
15126 setState(() {
15127 _response = response;
15128 _loading = false;
15129 });
15130 // Fetch schemas for result collections we haven't seen yet, so groups
15131 // can render list_fields / list_mode. Results show immediately; rows
15132 // refine as specs arrive.
15133 final results = _results(response);
15134 for (final collection in results.keys) {
15135 if (_specs.containsKey(collection)) continue;
15136 ScrollAPI().getAdminSchema(collection).then((detail) {
15137 if (!mounted || detail == null) return;
15138 setState(() {
15139 _specs[collection] = SchemaFormSpec.fromSchema(detail);
15140 });
15141 });
15142 }
15143 }
15144
15145 Map<String, List<Map<String, dynamic>>> _results(
15146 Map<String, dynamic> response,
15147 ) {
15148 final raw = response['results'];
15149 final results = <String, List<Map<String, dynamic>>>{};
15150 if (raw is Map) {
15151 raw.forEach((collection, records) {
15152 if (records is! List) return;
15153 results[collection.toString()] = [
15154 for (final record in records)
15155 if (record is Map)
15156 Map<String, dynamic>.from(
15157 record.map((k, v) => MapEntry(k.toString(), v)),
15158 ),
15159 ];
15160 });
15161 }
15162 return results;
15163 }
15164
15165 List<String> _rowFields(String collection, Map<String, dynamic> record) {
15166 final listFields = _specs[collection]?.listFields ?? const [];
15167 if (listFields.isNotEmpty) return listFields;
15168 return [
15169 for (final key in record.keys)
15170 if (!_internalRecordKeys.contains(key)) key,
15171 ].take(4).toList();
15172 }
15173
15174 String _recordTitle(String collection, Map<String, dynamic> record) {
15175 for (final field in _rowFields(collection, record)) {
15176 final value = record[field];
15177 if (value != null && value.toString().trim().isNotEmpty) {
15178 return value.toString();
15179 }
15180 }
15181 return record['id']?.toString() ?? '(record)';
15182 }
15183
15184 void _showRecord(String collection, Map<String, dynamic> record) {
15185 final recordId = record['id']?.toString() ?? '';
15186 final hasPublicFlag = record.containsKey('is_public');
15187 final isPublic = schemaBoolIsTrue(record['is_public']);
15188 showDialog<void>(
15189 context: context,
15190 builder: (context) => AlertDialog(
15191 title: Text('$collection / $recordId'),
15192 content: SizedBox(
15193 width: 560,
15194 child: SingleChildScrollView(
15195 child: SelectableText(
15196 const JsonEncoder.withIndent(' ').convert(record),
15197 style: const TextStyle(fontFamily: 'monospace', fontSize: 12),
15198 ),
15199 ),
15200 ),
15201 actions: [
15202 if (hasPublicFlag && recordId.isNotEmpty)
15203 TextButton.icon(
15204 onPressed: () {
15205 Navigator.of(context).pop();
15206 _togglePublic(collection, recordId, makePublic: !isPublic);
15207 },
15208 icon: Icon(
15209 isPublic ? Icons.lock_outline : Icons.public,
15210 size: 16,
15211 ),
15212 label: Text(isPublic ? 'Make Private' : 'Make Public'),
15213 ),
15214 if (recordId.isNotEmpty)
15215 TextButton.icon(
15216 // Permalink convention: /{collection}/{id} via site_routes.
15217 onPressed: () {
15218 final base = ScrollAPI().objectServerUrl;
15219 if (base != null) {
15220 Process.run('open', ['$base$collection/$recordId']);
15221 }
15222 },
15223 icon: const Icon(Icons.open_in_browser, size: 16),
15224 label: const Text('Open Page'),
15225 ),
15226 TextButton(
15227 onPressed: () => Navigator.of(context).pop(),
15228 child: const Text('Close'),
15229 ),
15230 ],
15231 ),
15232 );
15233 }
15234
15235 Future<void> _togglePublic(
15236 String collection,
15237 String recordId, {
15238 required bool makePublic,
15239 }) async {
15240 final result = await ScrollAPI().updateAdminCollectionRecord(
15241 collection,
15242 recordId,
15243 {'is_public': makePublic ? 'true' : 'false'},
15244 );
15245 if (!mounted) return;
15246 final status = result['status'];
15247 final ok = status is int && status >= 200 && status < 300;
15248 ScaffoldMessenger.of(context).showSnackBar(
15249 SnackBar(
15250 content: Text(
15251 ok
15252 ? '$collection/$recordId is now '
15253 '${makePublic ? 'public' : 'private'}'
15254 : 'Update failed: HTTP ${status ?? result['error'] ?? '?'}',
15255 ),
15256 backgroundColor: ok ? Colors.green[800] : Colors.red[800],
15257 ),
15258 );
15259 if (ok) _search();
15260 }
15261
15262 Widget? _publicBadge(Map<String, dynamic> record) {
15263 if (!record.containsKey('is_public')) return null;
15264 final isPublic = schemaBoolIsTrue(record['is_public']);
15265 return _searchChip(
15266 isPublic ? 'PUBLIC' : 'PRIVATE',
15267 isPublic ? Colors.green : Colors.blueGrey,
15268 );
15269 }
15270
15271 @override
15272 Widget build(BuildContext context) {
15273 final response = _response;
15274 final results = response == null ? null : _results(response);
15275 return Padding(
15276 padding: const EdgeInsets.all(16),
15277 child: Column(
15278 crossAxisAlignment: CrossAxisAlignment.start,
15279 children: [
15280 Row(
15281 children: [
15282 Text('Search', style: Theme.of(context).textTheme.titleLarge),
15283 const SizedBox(width: 8),
15284 _searchChip('GET /api/search', Colors.blue),
15285 const SizedBox(width: 8),
15286 _searchChip('PERMISSION-AWARE', Colors.green),
15287 const Spacer(),
15288 if (_loading)
15289 const SizedBox(
15290 width: 18,
15291 height: 18,
15292 child: CircularProgressIndicator(strokeWidth: 2),
15293 ),
15294 ],
15295 ),
15296 const SizedBox(height: 12),
15297 Row(
15298 children: [
15299 Expanded(
15300 child: TextField(
15301 controller: _queryController,
15302 focusNode: _queryFocus,
15303 autofocus: true,
15304 onSubmitted: (_) => _search(),
15305 decoration: InputDecoration(
15306 hintText: 'Search all collections your session can read...',
15307 prefixIcon: const Icon(Icons.search, size: 18),
15308 isDense: true,
15309 border: OutlineInputBorder(
15310 borderRadius: BorderRadius.circular(8),
15311 ),
15312 ),
15313 style: const TextStyle(fontSize: 13),
15314 ),
15315 ),
15316 const SizedBox(width: 10),
15317 FilledButton.icon(
15318 onPressed: _loading ? null : _search,
15319 icon: const Icon(Icons.search, size: 16),
15320 label: const Text('Search'),
15321 ),
15322 ],
15323 ),
15324 const SizedBox(height: 12),
15325 if (_error != null)
15326 Padding(
15327 padding: const EdgeInsets.only(bottom: 12),
15328 child: Text(
15329 _error!,
15330 style: TextStyle(color: Colors.red[300], fontSize: 12),
15331 ),
15332 ),
15333 Expanded(child: _body(context, results)),
15334 ],
15335 ),
15336 );
15337 }
15338
15339 Widget _body(
15340 BuildContext context,
15341 Map<String, List<Map<String, dynamic>>>? results,
15342 ) {
15343 if (results == null) {
15344 return const Center(
15345 child: Text(
15346 'Terms are AND-ed across each collection\'s searchable fields.\n'
15347 'Collections opt in via their schema — denied collections are '
15348 'skipped server-side.',
15349 textAlign: TextAlign.center,
15350 style: TextStyle(color: Colors.white38, fontSize: 13),
15351 ),
15352 );
15353 }
15354 final total = _response?['total_count'];
15355 final warnings = _response?['warnings'];
15356 final nonEmpty = results.entries.where((e) => e.value.isNotEmpty).toList();
15357 if (nonEmpty.isEmpty) {
15358 return Center(
15359 child: Text(
15360 'No matches for "${_searchedQuery ?? ''}"',
15361 style: const TextStyle(color: Colors.white38, fontSize: 13),
15362 ),
15363 );
15364 }
15365 return ListView(
15366 children: [
15367 Padding(
15368 padding: const EdgeInsets.only(bottom: 8),
15369 child: Text(
15370 '${total ?? nonEmpty.fold<int>(0, (n, e) => n + e.value.length)} '
15371 'result(s) for "${_searchedQuery ?? ''}"',
15372 style: const TextStyle(color: Colors.white38, fontSize: 12),
15373 ),
15374 ),
15375 if (warnings is List && warnings.isNotEmpty)
15376 Padding(
15377 padding: const EdgeInsets.only(bottom: 8),
15378 child: Text(
15379 warnings.join(' · '),
15380 style: TextStyle(color: Colors.amber[300], fontSize: 12),
15381 ),
15382 ),
15383 for (final entry in nonEmpty) ...[
15384 Padding(
15385 padding: const EdgeInsets.only(top: 12, bottom: 6),
15386 child: Row(
15387 children: [
15388 Icon(
15389 switch (_specs[entry.key]?.listMode) {
15390 'cards' => Icons.grid_view_outlined,
15391 'feed' => Icons.view_agenda_outlined,
15392 _ => Icons.table_rows_outlined,
15393 },
15394 size: 15,
15395 color: Colors.white54,
15396 ),
15397 const SizedBox(width: 8),
15398 Text(
15399 entry.key,
15400 style: const TextStyle(
15401 fontSize: 13,
15402 fontWeight: FontWeight.w600,
15403 ),
15404 ),
15405 const SizedBox(width: 8),
15406 Text(
15407 '${entry.value.length}',
15408 style: const TextStyle(fontSize: 12, color: Colors.white38),
15409 ),
15410 ],
15411 ),
15412 ),
15413 if (_specs[entry.key]?.listMode == 'cards')
15414 Wrap(
15415 spacing: 10,
15416 runSpacing: 10,
15417 children: [
15418 for (final record in entry.value)
15419 _recordCard(entry.key, record),
15420 ],
15421 )
15422 else
15423 for (final record in entry.value) _recordRow(entry.key, record),
15424 ],
15425 ],
15426 );
15427 }
15428
15429 Widget _recordCard(String collection, Map<String, dynamic> record) {
15430 final fields = _rowFields(collection, record);
15431 return InkWell(
15432 onTap: () => _showRecord(collection, record),
15433 borderRadius: BorderRadius.circular(8),
15434 child: Container(
15435 width: 260,
15436 padding: const EdgeInsets.all(12),
15437 decoration: BoxDecoration(
15438 color: Colors.white.withValues(alpha: 0.04),
15439 borderRadius: BorderRadius.circular(8),
15440 border: Border.all(color: Colors.white10),
15441 ),
15442 child: Column(
15443 crossAxisAlignment: CrossAxisAlignment.start,
15444 children: [
15445 Text(
15446 _recordTitle(collection, record),
15447 maxLines: 3,
15448 overflow: TextOverflow.ellipsis,
15449 style: const TextStyle(fontSize: 13),
15450 ),
15451 const SizedBox(height: 6),
15452 for (final field in fields.skip(1))
15453 if (record[field] != null && field != 'is_public')
15454 Text(
15455 '$field: ${record[field]}',
15456 maxLines: 1,
15457 overflow: TextOverflow.ellipsis,
15458 style: const TextStyle(fontSize: 11, color: Colors.white54),
15459 ),
15460 if (_publicBadge(record) case final badge?)
15461 Padding(padding: const EdgeInsets.only(top: 6), child: badge),
15462 ],
15463 ),
15464 ),
15465 );
15466 }
15467
15468 Widget _recordRow(String collection, Map<String, dynamic> record) {
15469 final fields = _rowFields(collection, record);
15470 final detail = [
15471 for (final field in fields.skip(1))
15472 if (record[field] != null && field != 'is_public')
15473 '$field: ${record[field]}',
15474 ].join(' · ');
15475 return InkWell(
15476 onTap: () => _showRecord(collection, record),
15477 child: Container(
15478 padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 10),
15479 decoration: const BoxDecoration(
15480 border: Border(bottom: BorderSide(color: Colors.white10)),
15481 ),
15482 child: Row(
15483 children: [
15484 Expanded(
15485 flex: 2,
15486 child: Text(
15487 _recordTitle(collection, record),
15488 maxLines: 1,
15489 overflow: TextOverflow.ellipsis,
15490 style: const TextStyle(fontSize: 13),
15491 ),
15492 ),
15493 if (detail.isNotEmpty)
15494 Expanded(
15495 flex: 3,
15496 child: Text(
15497 detail,
15498 maxLines: 1,
15499 overflow: TextOverflow.ellipsis,
15500 style: const TextStyle(fontSize: 12, color: Colors.white54),
15501 ),
15502 ),
15503 if (_publicBadge(record) case final badge?)
15504 Padding(padding: const EdgeInsets.only(right: 8), child: badge),
15505 Text(
15506 record['id']?.toString() ?? '',
15507 style: const TextStyle(fontSize: 11, color: Colors.white30),
15508 ),
15509 ],
15510 ),
15511 ),
15512 );
15513 }
15514
15515 Widget _searchChip(String label, Color color) {
15516 return Container(
15517 padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
15518 decoration: BoxDecoration(
15519 color: color.withValues(alpha: 0.15),
15520 borderRadius: BorderRadius.circular(4),
15521 ),
15522 child: Text(
15523 label,
15524 style: TextStyle(
15525 fontSize: 10,
15526 fontWeight: FontWeight.w600,
15527 color: color,
15528 ),
15529 ),
15530 );
15531 }
15532}
15533
15534// ---------------------------------------------------------------------------
15535// OPS EVENTS — GET /admin/ops. One admin-gated stream: object execution
15536// failures + auth activity (login_failed rows are what the lockout gate
15537// reads, login_locked marks a tripped lock). Never contains key material.
15538// ---------------------------------------------------------------------------
15539
15540class OpsEventsView extends StatefulWidget {
15541 const OpsEventsView({super.key});
15542
15543 @override
15544 State<OpsEventsView> createState() => _OpsEventsViewState();
15545}
15546
15547class _OpsEventsViewState extends State<OpsEventsView> {
15548 final _identifierController = TextEditingController();
15549 String _kind = 'All';
15550 List<Map<String, dynamic>> _events = [];
15551 bool _loading = true;
15552 String? _error;
15553
15554 @override
15555 void initState() {
15556 super.initState();
15557 _load();
15558 }
15559
15560 @override
15561 void dispose() {
15562 _identifierController.dispose();
15563 super.dispose();
15564 }
15565
15566 Future<void> _load() async {
15567 setState(() {
15568 _loading = true;
15569 _error = null;
15570 });
15571 final result = await ScrollAPI().listAdminOpsEvents(
15572 kind: _kind == 'All' ? null : _kind,
15573 identifier: _identifierController.text.trim(),
15574 );
15575 if (!mounted) return;
15576 final status = result['status'];
15577 final body = result['body'];
15578 if (status is! int || status < 200 || status >= 300) {
15579 setState(() {
15580 _loading = false;
15581 _error = 'HTTP ${status ?? result['error'] ?? '?'}';
15582 });
15583 return;
15584 }
15585 final raw = body is Map
15586 ? (body['events'] ?? body['items'] ?? body['results'])
15587 : body;
15588 setState(() {
15589 _loading = false;
15590 _events = [
15591 if (raw is List)
15592 for (final event in raw)
15593 if (event is Map)
15594 Map<String, dynamic>.from(
15595 event.map((k, v) => MapEntry(k.toString(), v)),
15596 ),
15597 ];
15598 });
15599 }
15600
15601 Color _eventColor(Map<String, dynamic> event) {
15602 if (event['kind']?.toString() == 'execution_error') return Colors.red;
15603 return switch (event['event']?.toString()) {
15604 'login_failed' => Colors.orange,
15605 'login_locked' => Colors.red,
15606 'login_succeeded' => Colors.green,
15607 'session_minted' => Colors.blue,
15608 'logout' => Colors.blueGrey,
15609 _ => Colors.purple,
15610 };
15611 }
15612
15613 String _eventTitle(Map<String, dynamic> event) {
15614 if (event['kind']?.toString() == 'execution_error') {
15615 final object = event['object_id'] ?? '?';
15616 final method = event['method'] ?? '';
15617 return 'execution_error $object${method == '' ? '' : '.$method'}';
15618 }
15619 return (event['event'] ?? 'auth').toString();
15620 }
15621
15622 String _eventDetail(Map<String, dynamic> event) {
15623 final parts = <String>[];
15624 for (final key in const [
15625 'identifier',
15626 'user_id',
15627 'auth_method',
15628 'label',
15629 'error_type',
15630 'message',
15631 'correlation_id',
15632 ]) {
15633 final value = event[key];
15634 if (value != null && value.toString().trim().isNotEmpty) {
15635 parts.add('$key: $value');
15636 }
15637 }
15638 return parts.join(' · ');
15639 }
15640
15641 void _showEvent(Map<String, dynamic> event) {
15642 showDialog<void>(
15643 context: context,
15644 builder: (context) => AlertDialog(
15645 title: Text(_eventTitle(event)),
15646 content: SizedBox(
15647 width: 560,
15648 child: SingleChildScrollView(
15649 child: SelectableText(
15650 const JsonEncoder.withIndent(' ').convert(event),
15651 style: const TextStyle(fontFamily: 'monospace', fontSize: 12),
15652 ),
15653 ),
15654 ),
15655 actions: [
15656 TextButton(
15657 onPressed: () => Navigator.of(context).pop(),
15658 child: const Text('Close'),
15659 ),
15660 ],
15661 ),
15662 );
15663 }
15664
15665 @override
15666 Widget build(BuildContext context) {
15667 return Padding(
15668 padding: const EdgeInsets.all(16),
15669 child: Column(
15670 crossAxisAlignment: CrossAxisAlignment.start,
15671 children: [
15672 Row(
15673 children: [
15674 Text('Ops Events', style: Theme.of(context).textTheme.titleLarge),
15675 const SizedBox(width: 8),
15676 _opsChip('READ ONLY', Colors.green),
15677 const SizedBox(width: 8),
15678 _opsChip('GET /admin/ops', Colors.blue),
15679 const SizedBox(wid
Only the first 512 KB is shown. Download the zip for the whole file.