initial commit

This commit is contained in:
2026-07-27 14:42:23 +02:00
commit 833c68a189
257 changed files with 17947 additions and 0 deletions
+196
View File
@@ -0,0 +1,196 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../../core/models/models.dart';
import '../../core/models/severity_mapping.dart';
import '../../core/network/api_exception.dart';
import '../../core/routing/route_paths.dart';
import '../../core/theme/theme_x.dart';
import '../../core/widgets/error_banner.dart';
import '../../core/widgets/slide_over_panel.dart';
import '../../core/widgets/status_pill.dart';
import '../../data/repositories/services_repository.dart';
import 'widgets/service_detail_body.dart';
import 'widgets/service_form_dialog.dart';
import 'widgets/services_table.dart';
class ServicesScreen extends ConsumerStatefulWidget {
const ServicesScreen({super.key, this.serviceId});
/// Present when routed via `/services?id=...` — renders the slide-over
/// detail panel for this service alongside the still-visible table.
final String? serviceId;
@override
ConsumerState<ServicesScreen> createState() => _ServicesScreenState();
}
class _ServicesScreenState extends ConsumerState<ServicesScreen> {
final _busyIds = <String>{};
Future<void> _run(String id, Future<void> Function() action, {String? successMessage}) async {
setState(() => _busyIds.add(id));
try {
await action();
ref.invalidate(servicesListProvider);
if (mounted && successMessage != null) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(successMessage)));
}
} catch (e) {
if (mounted) {
final message = e is ApiException ? e.userMessage : e.toString();
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(message)));
}
} finally {
if (mounted) setState(() => _busyIds.remove(id));
}
}
void _toggleRunning(Service service) {
final repo = ref.read(servicesRepositoryProvider);
if (repo == null) return;
_run(service.id, () => service.status == 'up' ? repo.stop(service.id) : repo.start(service.id));
}
void _backupNow(Service service) {
final repo = ref.read(servicesRepositoryProvider);
if (repo == null) return;
_run(service.id, () => repo.backupNow(service.id), successMessage: 'Backup started');
}
Future<void> _delete(Service service) async {
final confirmed = await showDialog<bool>(
context: context,
builder: (context) => AlertDialog(
title: const Text('Delete service?'),
content: Text('This removes "${service.name}" from NodeMaster. It does not stop or delete the container.'),
actions: [
TextButton(onPressed: () => Navigator.of(context).pop(false), child: const Text('Cancel')),
FilledButton(
style: FilledButton.styleFrom(backgroundColor: context.status.critical),
onPressed: () => Navigator.of(context).pop(true),
child: const Text('Delete'),
),
],
),
);
if (confirmed != true) return;
final repo = ref.read(servicesRepositoryProvider);
if (repo == null) return;
await _run(service.id, () => repo.delete(service.id));
if (mounted) context.go(RoutePaths.services);
}
@override
Widget build(BuildContext context) {
final servicesAsync = ref.watch(servicesListProvider);
return Stack(
children: [
Padding(
padding: const EdgeInsets.all(24),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
servicesAsync.maybeWhen(
data: (services) => '${services.length} SERVICES',
orElse: () => 'SERVICES',
),
style: context.text.titleSmall,
),
FilledButton.icon(
onPressed: () => showServiceFormDialog(context),
icon: const Icon(Icons.add, size: 17),
label: const Text('Add service'),
),
],
),
const SizedBox(height: 12),
Expanded(
child: servicesAsync.when(
loading: () => const Center(child: CircularProgressIndicator()),
error: (error, stackTrace) => Align(
alignment: Alignment.topCenter,
child: ErrorBanner(
message: error is ApiException ? error.userMessage : error.toString(),
onRetry: () => ref.invalidate(servicesListProvider),
),
),
data: (services) => SingleChildScrollView(
child: ServicesTable(
services: services,
busyServiceIds: _busyIds,
onRowTap: (service) => context.go(RoutePaths.serviceDetail(service.id)),
onToggleRunning: _toggleRunning,
),
),
),
),
],
),
),
_buildDetailPanel(servicesAsync),
],
);
}
Widget _buildDetailPanel(AsyncValue<List<Service>> servicesAsync) {
final id = widget.serviceId;
final service = servicesAsync.maybeWhen(
data: (services) {
for (final s in services) {
if (s.id == id) return s;
}
return null;
},
orElse: () => null,
);
return SlideOverPanel(
open: id != null,
onClose: () => context.go(RoutePaths.services),
title: service?.name ?? '',
subtitle: service == null
? null
: StatusPill(label: service.status, severity: severityForServiceStatus(service.status)),
body: service == null
? const SizedBox.shrink()
: ServiceDetailBody(service: service),
headerActions: service == null
? const []
: [
IconButton(
tooltip: 'Edit',
icon: const Icon(Icons.edit_outlined, size: 18),
onPressed: () => showServiceFormDialog(context, existing: service),
),
],
actions: service == null
? const []
: [
OutlinedButton.icon(
onPressed: () => _toggleRunning(service),
icon: Icon(service.status == 'up' ? Icons.stop_rounded : Icons.play_arrow_rounded, size: 17),
label: Text(service.status == 'up' ? 'Stop' : 'Start'),
),
OutlinedButton.icon(
onPressed: service.backup == null ? null : () => _backupNow(service),
icon: const Icon(Icons.cloud_outlined, size: 17),
label: const Text('Backup'),
),
OutlinedButton.icon(
style: OutlinedButton.styleFrom(foregroundColor: context.status.critical),
onPressed: () => _delete(service),
icon: const Icon(Icons.delete_outline, size: 17),
label: const Text('Delete'),
),
],
);
}
}
@@ -0,0 +1,172 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:intl/intl.dart';
import '../../../core/models/models.dart';
import '../../../core/models/severity_mapping.dart';
import '../../../core/network/api_exception.dart';
import '../../../core/theme/theme_x.dart';
import '../../../core/widgets/backup_target_form_dialog.dart';
import '../../../core/widgets/backup_targets_list.dart';
import '../../../core/widgets/mono_text.dart';
import '../../../core/widgets/status_pill.dart';
import '../../../data/repositories/services_repository.dart';
/// The scrollable body of the Services slide-over panel — everything below
/// the title/close row that [SlideOverPanel] already renders.
class ServiceDetailBody extends ConsumerWidget {
const ServiceDetailBody({super.key, required this.service});
final Service service;
Future<void> _addTarget(BuildContext context, WidgetRef ref) {
return showBackupTargetFormDialog(
context,
onSave: (draft) async {
final repo = ref.read(servicesRepositoryProvider);
if (repo == null) throw const ApiException.unknown('No active connection.');
await repo.addBackupTarget(service.id, draft);
ref.invalidate(servicesListProvider);
},
);
}
Future<void> _editTarget(BuildContext context, WidgetRef ref, BackupTarget target) {
return showBackupTargetFormDialog(
context,
existing: target,
onSave: (draft) async {
final repo = ref.read(servicesRepositoryProvider);
if (repo == null) throw const ApiException.unknown('No active connection.');
await repo.updateBackupTarget(service.id, target.id, draft);
ref.invalidate(servicesListProvider);
},
);
}
Future<void> _deleteTarget(BuildContext context, WidgetRef ref, BackupTarget target) async {
final confirmed = await showDialog<bool>(
context: context,
builder: (context) => AlertDialog(
title: const Text('Remove backup target?'),
content: Text('This removes "${target.name}" from this service\'s backup targets.'),
actions: [
TextButton(onPressed: () => Navigator.of(context).pop(false), child: const Text('Cancel')),
FilledButton(
style: FilledButton.styleFrom(backgroundColor: context.status.critical),
onPressed: () => Navigator.of(context).pop(true),
child: const Text('Remove'),
),
],
),
);
if (confirmed != true) return;
final repo = ref.read(servicesRepositoryProvider);
if (repo == null) return;
try {
await repo.deleteBackupTarget(service.id, target.id);
ref.invalidate(servicesListProvider);
} catch (e) {
final message = e is ApiException ? e.userMessage : e.toString();
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(message)));
}
}
}
Future<void> _runTarget(WidgetRef ref, BackupTarget target) async {
final repo = ref.read(servicesRepositoryProvider);
if (repo == null) throw const ApiException.unknown('No active connection.');
await repo.runBackupTarget(service.id, target.id);
}
Future<RunState> _fetchProgress(WidgetRef ref, BackupTarget target) async {
final repo = ref.read(servicesRepositoryProvider);
if (repo == null) return const RunState();
return repo.getBackupTargetProgress(service.id, target.id);
}
@override
Widget build(BuildContext context, WidgetRef ref) {
final backup = service.backup;
final targets = backup?.targets ?? const [];
final history = (backup?.history ?? const []).reversed.take(5).toList();
final timeFormat = DateFormat('MM-dd HH:mm');
return ListView(
padding: const EdgeInsets.fromLTRB(20, 12, 20, 20),
children: [
_KvRow(label: 'Compose file', value: MonoText(service.composeFile)),
_KvRow(
label: 'Compose type',
value: Text(service.composeType?.isNotEmpty == true ? service.composeType! : 'docker compose'),
),
_KvRow(
label: 'Backup folder',
value: service.backupFolder?.isNotEmpty == true
? MonoText(service.backupFolder!)
: Text('Not set', style: context.text.bodySmall),
),
_KvRow(label: 'Stop on backup', value: Text(service.stopOnBackup ? 'Yes' : 'No')),
const SizedBox(height: 18),
Text('BACKUP TARGETS', style: context.text.titleSmall),
const SizedBox(height: 4),
BackupTargetsList(
targets: targets,
onAdd: () => _addTarget(context, ref),
onEdit: (target) => _editTarget(context, ref, target),
onDelete: (target) => _deleteTarget(context, ref, target),
onRun: (target) => _runTarget(ref, target),
fetchProgress: (target) => _fetchProgress(ref, target),
onSettled: (target, state) => ref.invalidate(servicesListProvider),
),
const SizedBox(height: 18),
Text('RECENT BACKUPS', style: context.text.titleSmall),
const SizedBox(height: 4),
if (history.isEmpty)
Padding(
padding: const EdgeInsets.only(top: 6),
child: Text('No backup history yet.', style: context.text.bodySmall),
)
else
for (final execution in history)
Padding(
padding: const EdgeInsets.symmetric(vertical: 7),
child: Row(
children: [
MonoText(timeFormat.format(execution.timestamp.toLocal()), small: true),
const Spacer(),
StatusPill(
label: execution.success ? '${execution.durationSeconds}s' : 'failed',
severity: severityForSuccess(execution.success),
),
],
),
),
],
);
}
}
class _KvRow extends StatelessWidget {
const _KvRow({required this.label, required this.value});
final String label;
final Widget value;
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.symmetric(vertical: 12),
decoration: BoxDecoration(border: Border(bottom: BorderSide(color: context.colors.outlineVariant))),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(width: 128, child: Text(label, style: context.text.bodySmall)),
Expanded(child: value),
],
),
);
}
}
@@ -0,0 +1,161 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../core/models/models.dart';
import '../../../core/network/api_exception.dart';
import '../../../data/repositories/services_repository.dart';
const _composeTypes = ['docker compose', 'docker-compose', 'podman-compose'];
/// Add/edit dialog for a [Service]'s core identity fields. Backup target
/// configuration is deliberately out of scope here — that's a node/service
/// backup-config concern owned by the Backups screen, not service CRUD.
Future<void> showServiceFormDialog(BuildContext context, {Service? existing}) {
return showDialog<void>(
context: context,
builder: (context) => _ServiceFormDialog(existing: existing),
);
}
class _ServiceFormDialog extends ConsumerStatefulWidget {
const _ServiceFormDialog({this.existing});
final Service? existing;
@override
ConsumerState<_ServiceFormDialog> createState() => _ServiceFormDialogState();
}
class _ServiceFormDialogState extends ConsumerState<_ServiceFormDialog> {
final _formKey = GlobalKey<FormState>();
late final _nameController = TextEditingController(text: widget.existing?.name);
late final _composeFileController = TextEditingController(text: widget.existing?.composeFile);
late final _backupFolderController = TextEditingController(text: widget.existing?.backupFolder);
late String _composeType = widget.existing?.composeType?.isNotEmpty == true
? widget.existing!.composeType!
: _composeTypes.first;
late bool _stopOnBackup = widget.existing?.stopOnBackup ?? false;
bool _saving = false;
String? _error;
@override
void dispose() {
_nameController.dispose();
_composeFileController.dispose();
_backupFolderController.dispose();
super.dispose();
}
Future<void> _save() async {
if (!(_formKey.currentState?.validate() ?? false)) return;
setState(() {
_saving = true;
_error = null;
});
final existing = widget.existing;
final draft = (existing ?? const Service(name: '', composeFile: '')).copyWith(
name: _nameController.text.trim(),
composeFile: _composeFileController.text.trim(),
composeType: _composeType,
backupFolder: _backupFolderController.text.trim(),
stopOnBackup: _stopOnBackup,
);
final repo = ref.read(servicesRepositoryProvider);
if (repo == null) {
setState(() {
_saving = false;
_error = 'No active connection.';
});
return;
}
try {
if (existing == null) {
await repo.add(draft);
} else {
await repo.update(existing.id, draft);
}
ref.invalidate(servicesListProvider);
if (mounted) Navigator.of(context).pop();
} catch (e) {
setState(() {
_saving = false;
_error = e is ApiException ? e.userMessage : e.toString();
});
}
}
@override
Widget build(BuildContext context) {
return AlertDialog(
title: Text(widget.existing == null ? 'Add service' : 'Edit service'),
content: Form(
key: _formKey,
child: SizedBox(
width: 420,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
TextFormField(
controller: _nameController,
decoration: const InputDecoration(labelText: 'Name'),
validator: (v) => (v == null || v.trim().isEmpty) ? 'Required.' : null,
),
const SizedBox(height: 14),
TextFormField(
controller: _composeFileController,
decoration: const InputDecoration(
labelText: 'Compose file',
hintText: '/opt/compose/gitea/docker-compose.yml',
),
validator: (v) => (v == null || v.trim().isEmpty) ? 'Required.' : null,
),
const SizedBox(height: 14),
DropdownButtonFormField<String>(
initialValue: _composeType,
decoration: const InputDecoration(labelText: 'Compose type'),
items: [
for (final type in _composeTypes) DropdownMenuItem(value: type, child: Text(type)),
],
onChanged: (value) => setState(() => _composeType = value ?? _composeTypes.first),
),
const SizedBox(height: 14),
TextFormField(
controller: _backupFolderController,
decoration: const InputDecoration(
labelText: 'Backup folder (optional)',
hintText: '/opt/data/containers/gitea',
),
),
const SizedBox(height: 8),
SwitchListTile(
contentPadding: EdgeInsets.zero,
title: const Text('Stop container while backing up'),
value: _stopOnBackup,
onChanged: (value) => setState(() => _stopOnBackup = value),
),
if (_error != null) ...[
const SizedBox(height: 8),
Text(_error!, style: TextStyle(color: Theme.of(context).colorScheme.error)),
],
],
),
),
),
actions: [
TextButton(
onPressed: _saving ? null : () => Navigator.of(context).pop(),
child: const Text('Cancel'),
),
FilledButton(
onPressed: _saving ? null : _save,
child: _saving
? const SizedBox(width: 16, height: 16, child: CircularProgressIndicator(strokeWidth: 2))
: const Text('Save'),
),
],
);
}
}
@@ -0,0 +1,88 @@
import 'package:flutter/material.dart';
import '../../../core/models/models.dart';
import '../../../core/models/severity_mapping.dart';
import '../../../core/theme/theme_x.dart';
import '../../../core/widgets/data_table_scaffold.dart';
import '../../../core/widgets/empty_state.dart';
import '../../../core/widgets/mono_text.dart';
import '../../../core/widgets/status_pill.dart';
class ServicesTable extends StatelessWidget {
const ServicesTable({
super.key,
required this.services,
required this.onRowTap,
required this.onToggleRunning,
required this.busyServiceIds,
});
final List<Service> services;
final void Function(Service service) onRowTap;
final void Function(Service service) onToggleRunning;
final Set<String> busyServiceIds;
String _backupSummary(Service service) {
final targets = service.backup?.targets ?? const [];
if (targets.isEmpty) return 'none';
if (targets.length == 1) return targets.first.method.name;
return '${targets.length} targets';
}
@override
Widget build(BuildContext context) {
return DataTableScaffold(
empty: const EmptyState(
icon: Icons.layers_outlined,
title: 'No services yet',
message: 'Scan a compose folder from the Dashboard, or add one manually.',
),
columns: const [
DataColumn(label: Text('Service')),
DataColumn(label: Text('Status')),
DataColumn(label: Text('Compose file')),
DataColumn(label: Text('Backup')),
DataColumn(label: Text('')),
],
rows: [
for (final service in services)
DataRow(
onSelectChanged: (_) => onRowTap(service),
cells: [
DataCell(
Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text(service.name, style: context.text.labelLarge),
Text(
service.composeType?.isNotEmpty == true ? service.composeType! : 'docker compose',
style: context.text.bodySmall,
),
],
),
),
DataCell(
StatusPill(label: service.status, severity: severityForServiceStatus(service.status)),
),
DataCell(MonoText(service.composeFile)),
DataCell(
_backupSummary(service) == 'none'
? Text('none', style: context.text.bodySmall)
: Text(_backupSummary(service), style: context.text.bodyMedium),
),
DataCell(
busyServiceIds.contains(service.id)
? const SizedBox(width: 18, height: 18, child: CircularProgressIndicator(strokeWidth: 2))
: IconButton(
tooltip: service.status == 'up' ? 'Stop' : 'Start',
icon: Icon(service.status == 'up' ? Icons.stop_rounded : Icons.play_arrow_rounded, size: 20),
onPressed: () => onToggleRunning(service),
),
),
],
),
],
);
}
}