Compare commits

...

2 Commits

Author SHA1 Message Date
d8bcde1312 Add support for file uploads using new async upload jobs, add admin section for uploading distance files
All checks were successful
Release / meta (push) Successful in 3s
Release / linux-build (push) Successful in 59s
Release / web-build (push) Successful in 1m24s
Release / android-build (push) Successful in 6m13s
Release / release-master (push) Successful in 8s
Release / release-dev (push) Successful in 13s
2026-01-27 21:43:34 +00:00
45bd872b23 add support for network calculation from the calculator
All checks were successful
Release / meta (push) Successful in 1m39s
Release / linux-build (push) Successful in 1m55s
Release / web-build (push) Successful in 3m12s
Release / android-build (push) Successful in 6m48s
Release / release-master (push) Successful in 22s
Release / release-dev (push) Successful in 28s
2026-01-27 00:41:27 +00:00
14 changed files with 801 additions and 73 deletions

View File

@@ -40,6 +40,7 @@ class RouteDetailsView extends StatelessWidget {
final List<double> costs;
final VoidCallback onBack;
final Set<String> routingPoints;
final VoidCallback? onNetworksPressed;
const RouteDetailsView({
super.key,
@@ -47,6 +48,7 @@ class RouteDetailsView extends StatelessWidget {
required this.costs,
required this.onBack,
this.routingPoints = const {},
this.onNetworksPressed,
});
@override
@@ -56,13 +58,21 @@ class RouteDetailsView extends StatelessWidget {
final mutedColor = Theme.of(context).colorScheme.outlineVariant;
return Column(
children: [
Align(
alignment: Alignment.centerLeft,
child: TextButton.icon(
onPressed: onBack,
icon: const Icon(Icons.arrow_back),
label: const Text('Back'),
),
Row(
children: [
TextButton.icon(
onPressed: onBack,
icon: const Icon(Icons.arrow_back),
label: const Text('Back'),
),
const Spacer(),
if (onNetworksPressed != null)
TextButton.icon(
onPressed: onNetworksPressed,
icon: const Icon(Icons.account_tree),
label: const Text('Networks'),
),
],
),
Expanded(
child: ListView.builder(

View File

@@ -32,6 +32,8 @@ class _LegCardState extends State<LegCard> {
final sharedTo = leg.sharedTo;
final distanceUnits = context.watch<DistanceUnitService>();
final routeSegments = _parseRouteSegments(leg.route);
final networkMileage = _sortedNetworkMileage(leg);
final countryMileage = _sortedCountryMileage(leg);
final textTheme = Theme.of(context).textTheme;
return Card(
clipBehavior: Clip.antiAlias,
@@ -160,10 +162,11 @@ class _LegCardState extends State<LegCard> {
),
);
}
if (leg.network.isNotEmpty) {
final networkSummary = _networkSummary(leg);
if (networkSummary != null) {
children.add(
Text(
leg.network,
networkSummary,
style: textTheme.labelSmall,
),
);
@@ -285,6 +288,28 @@ class _LegCardState extends State<LegCard> {
),
const SizedBox(height: 12),
],
if (networkMileage.isNotEmpty || countryMileage.isNotEmpty) ...[
Text('Network mileage', style: textTheme.titleSmall),
const SizedBox(height: 6),
...networkMileage.map(
(entry) => Text(
'${entry.network}: ${distanceUnits.format(entry.miles, decimals: 1)}',
style: textTheme.bodyMedium,
),
),
if (countryMileage.isNotEmpty) ...[
const SizedBox(height: 8),
Text('Country mileage', style: textTheme.titleSmall),
const SizedBox(height: 6),
...countryMileage.map(
(entry) => Text(
'${entry.country}: ${distanceUnits.format(entry.miles, decimals: 1)}',
style: textTheme.bodyMedium,
),
),
],
const SizedBox(height: 12),
],
if (routeSegments.isNotEmpty) ...[
Text('Route', style: textTheme.titleSmall),
const SizedBox(height: 6),
@@ -483,6 +508,33 @@ class _LegCardState extends State<LegCard> {
List<String> _parseRouteSegments(List<String> route) {
return route.map((e) => e.toString()).where((e) => e.trim().isNotEmpty).toList();
}
List<NetworkMileage> _sortedNetworkMileage(Leg leg) {
final items = leg.networkMileage
.where((entry) => entry.network.trim().isNotEmpty)
.toList();
items.sort((a, b) => b.miles.compareTo(a.miles));
return items;
}
List<CountryMileage> _sortedCountryMileage(Leg leg) {
final items = leg.countryMileage
.where((entry) => entry.country.trim().isNotEmpty)
.toList();
items.sort((a, b) => b.miles.compareTo(a.miles));
return items;
}
String? _networkSummary(Leg leg) {
final networks = _sortedNetworkMileage(leg);
if (networks.isNotEmpty) {
return networks.map((entry) => entry.network).join(', ');
}
if (leg.network.trim().isNotEmpty) {
return leg.network;
}
return null;
}
}
class _SharedIcons extends StatelessWidget {

View File

@@ -192,7 +192,7 @@ class _LoginLogoState extends State<_LoginLogo> {
}
String _colorToHex(Color color) {
final hex = color.value.toRadixString(16).padLeft(8, '0');
final hex = color.toARGB32().toRadixString(16).padLeft(8, '0');
return '#${hex.substring(2)}';
}
}

View File

@@ -2,6 +2,8 @@ import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:mileograph_flutter/components/calculator/route_summary_widget.dart';
import 'package:mileograph_flutter/objects/objects.dart';
import 'package:mileograph_flutter/services/distance_unit_service.dart';
import 'package:provider/provider.dart';
class CalculatorDetailsPage extends StatelessWidget {
const CalculatorDetailsPage({
@@ -34,13 +36,85 @@ class CalculatorDetailsPage extends StatelessWidget {
);
}
return Padding(
padding: const EdgeInsets.all(16.0),
child: RouteDetailsView(
route: parsed.calculatedRoute,
costs: parsed.costs,
routingPoints: parsed.inputRoute.toSet(),
onBack: () => context.pop(),
final networks = List<NetworkMileage>.from(parsed.networkMileage)
..sort((a, b) => b.miles.compareTo(a.miles));
final countries = List<CountryMileage>.from(parsed.countryMileage)
..sort((a, b) => b.miles.compareTo(a.miles));
return Scaffold(
endDrawer: _NetworksDrawer(
networks: networks,
countries: countries,
),
body: Builder(
builder: (scaffoldContext) => Padding(
padding: const EdgeInsets.all(16.0),
child: RouteDetailsView(
route: parsed.calculatedRoute,
costs: parsed.costs,
routingPoints: parsed.inputRoute.toSet(),
onBack: () => context.pop(),
onNetworksPressed: () =>
Scaffold.of(scaffoldContext).openEndDrawer(),
),
),
),
);
}
}
class _NetworksDrawer extends StatelessWidget {
const _NetworksDrawer({
required this.networks,
required this.countries,
});
final List<NetworkMileage> networks;
final List<CountryMileage> countries;
@override
Widget build(BuildContext context) {
final distanceUnits = context.watch<DistanceUnitService>();
return Drawer(
child: SafeArea(
child: ListView(
padding: const EdgeInsets.all(16),
children: [
Text(
'Networks',
style: Theme.of(context).textTheme.titleMedium,
),
const SizedBox(height: 8),
if (networks.isEmpty)
const Text('No network mileage data.')
else
...networks.map(
(entry) => ListTile(
contentPadding: EdgeInsets.zero,
title: Text(entry.network),
trailing:
Text(distanceUnits.format(entry.miles, decimals: 2)),
),
),
const SizedBox(height: 16),
Text(
'Countries',
style: Theme.of(context).textTheme.titleMedium,
),
const SizedBox(height: 8),
if (countries.isEmpty)
const Text('No country mileage data.')
else
...countries.map(
(entry) => ListTile(
contentPadding: EdgeInsets.zero,
title: Text(entry.country),
trailing:
Text(distanceUnits.format(entry.miles, decimals: 2)),
),
),
],
),
),
);
}

View File

@@ -813,17 +813,17 @@ List<DateTime> _buildBoundaries(
for (final seg in segments) {
boundaryDates.add(seg.start);
boundaryDates.add(seg.end);
minStart = minStart == null || seg.start.isBefore(minStart!)
minStart = minStart == null || seg.start.isBefore(minStart)
? seg.start
: minStart;
maxEnd = maxEnd == null || seg.end.isAfter(maxEnd!) ? seg.end : maxEnd;
maxEnd = maxEnd == null || seg.end.isAfter(maxEnd) ? seg.end : maxEnd;
}
minStart ??= now.subtract(const Duration(days: 1));
final effectiveMinStart = minStart ?? now.subtract(const Duration(days: 1));
final effectiveMaxEnd = maxEnd ?? now;
boundaryDates.add(effectiveMaxEnd);
var boundaries = boundaryDates.toList()..sort();
if (boundaries.length < 2) {
boundaries = [minStart!, effectiveMaxEnd];
boundaries = [effectiveMinStart, effectiveMaxEnd];
}
return boundaries;
}

View File

@@ -1,4 +1,5 @@
import 'package:flutter/material.dart';
import 'package:file_selector/file_selector.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';
import 'package:mileograph_flutter/objects/objects.dart';
@@ -28,6 +29,16 @@ class _AdminPageState extends State<AdminPage> {
bool _sending = false;
List<XFile> _routeFiles = [];
bool _routeUploading = false;
String? _routeStatus;
String? _routeStatusMessage;
String? _routeErrorMessage;
int? _routeProcessed;
int? _routeTotal;
double? _routeProgress;
Map<String, dynamic>? _routeResult;
@override
void initState() {
super.initState();
@@ -340,6 +351,191 @@ class _AdminPageState extends State<AdminPage> {
}
}
int? _parseCount(dynamic value) {
if (value is num) return value.toInt();
return int.tryParse(value?.toString() ?? '');
}
double? _parsePercent(
dynamic value, {
required int? processed,
required int? total,
}) {
if (value is num) {
final raw = value.toDouble();
final normalized = raw > 1 ? raw / 100 : raw;
return normalized.clamp(0, 1);
}
if (processed != null && total != null && total > 0) {
return (processed / total).clamp(0, 1);
}
return null;
}
Duration _pollDelay(int attempt) {
const delays = [
Duration(seconds: 1),
Duration(seconds: 2),
Duration(seconds: 2),
Duration(seconds: 5),
Duration(seconds: 5),
Duration(seconds: 8),
Duration(seconds: 10),
];
if (attempt < delays.length) return delays[attempt];
return const Duration(seconds: 10);
}
String _routeStatusLabel() {
final status = _routeStatus ?? '';
final lower = status.toLowerCase();
final base = switch (lower) {
'queued' => 'Queued',
'running' => 'Processing',
'succeeded' => 'Completed',
'failed' => 'Failed',
_ => status,
};
final parts = <String>[base];
if (_routeProcessed != null && _routeTotal != null) {
parts.add('Files $_routeProcessed of $_routeTotal');
}
if (_routeProgress != null) {
parts.add('${(_routeProgress! * 100).toStringAsFixed(0)}%');
}
return parts.join(' · ');
}
Future<void> _pickRouteFiles() async {
final files = await openFiles(
acceptedTypeGroups: const [
XTypeGroup(
label: 'XLSX spreadsheets',
extensions: ['xlsx'],
),
],
);
if (files.isEmpty) return;
setState(() {
_routeFiles = files;
_routeStatus = null;
_routeStatusMessage = null;
_routeErrorMessage = null;
_routeProcessed = null;
_routeTotal = null;
_routeProgress = null;
_routeResult = null;
});
}
Future<void> _uploadRouteFiles() async {
if (_routeFiles.isEmpty || _routeUploading) return;
setState(() {
_routeUploading = true;
_routeStatus = null;
_routeStatusMessage = null;
_routeErrorMessage = null;
_routeProcessed = null;
_routeTotal = null;
_routeProgress = null;
_routeResult = null;
});
try {
final api = context.read<ApiService>();
final payloads = <MultipartFilePayload>[];
for (final file in _routeFiles) {
final bytes = await file.readAsBytes();
payloads.add(
MultipartFilePayload(
bytes: bytes,
filename: file.name,
),
);
}
final response = await api.postMultipartFiles(
'/route/update',
files: payloads,
headers: const {'accept': 'application/json'},
);
if (!mounted) return;
final parsed = response is Map
? Map<String, dynamic>.from(response)
: null;
final jobId = parsed?['job_id']?.toString();
if (jobId == null || jobId.isEmpty) {
setState(() {
_routeErrorMessage = 'Upload failed to start.';
});
return;
}
setState(() {
_routeStatus = parsed?['status']?.toString() ?? 'queued';
});
var attempt = 0;
while (mounted) {
final statusResponse = await api.get('/uploads/$jobId');
if (!mounted) return;
final statusMap = statusResponse is Map
? Map<String, dynamic>.from(statusResponse)
: null;
if (statusMap == null) {
setState(() {
_routeErrorMessage = 'Upload status unavailable.';
});
return;
}
final status = statusMap['status']?.toString() ?? 'queued';
final processed = _parseCount(statusMap['processed']);
final total = _parseCount(statusMap['total']);
final percent = _parsePercent(
statusMap['percent'],
processed: processed,
total: total,
);
setState(() {
_routeStatus = status;
_routeProcessed = processed;
_routeTotal = total;
_routeProgress = percent;
});
if (status == 'succeeded') {
final result = statusMap['result'];
setState(() {
if (result is Map) {
_routeResult = Map<String, dynamic>.from(result);
}
final message = _routeResult?['message']?.toString();
_routeStatusMessage = message != null && message.isNotEmpty
? message
: 'Route update complete.';
});
return;
}
if (status == 'failed') {
setState(() {
_routeErrorMessage =
statusMap['error']?.toString() ?? 'Route update failed.';
});
return;
}
await Future.delayed(_pollDelay(attempt));
attempt += 1;
}
} on ApiException catch (e) {
if (!mounted) return;
setState(() {
_routeErrorMessage = e.message;
});
} catch (e) {
if (!mounted) return;
setState(() {
_routeErrorMessage = e.toString();
});
} finally {
if (mounted) setState(() => _routeUploading = false);
}
}
void _showSnack(String message) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(message)));
}
@@ -443,6 +639,87 @@ class _AdminPageState extends State<AdminPage> {
label: Text(_sending ? 'Sending...' : 'Send notification'),
),
),
const SizedBox(height: 32),
const Divider(height: 32),
Text(
'Route update uploads',
style: Theme.of(context).textTheme.titleLarge?.copyWith(
fontWeight: FontWeight.w700,
),
),
const SizedBox(height: 8),
Text(
'Upload one or more XLSX sheets to update route distances.',
style: Theme.of(context).textTheme.bodyMedium,
),
const SizedBox(height: 12),
Row(
children: [
Expanded(
child: Text(
_routeFiles.isEmpty
? 'No files selected'
: '${_routeFiles.length} file(s) selected',
overflow: TextOverflow.ellipsis,
),
),
const SizedBox(width: 8),
OutlinedButton.icon(
onPressed: _routeUploading ? null : _pickRouteFiles,
icon: const Icon(Icons.upload_file),
label: const Text('Choose files'),
),
],
),
const SizedBox(height: 12),
FilledButton.icon(
onPressed:
_routeFiles.isEmpty || _routeUploading ? null : _uploadRouteFiles,
icon: _routeUploading
? const SizedBox(
width: 18,
height: 18,
child: CircularProgressIndicator(strokeWidth: 2),
)
: const Icon(Icons.file_upload),
label: Text(_routeUploading ? 'Uploading...' : 'Upload files'),
),
if (_routeStatus != null) ...[
const SizedBox(height: 12),
Text(
_routeStatusLabel(),
style: Theme.of(context).textTheme.bodyMedium,
),
if (_routeProgress != null) ...[
const SizedBox(height: 6),
LinearProgressIndicator(value: _routeProgress),
],
],
if (_routeStatusMessage != null) ...[
const SizedBox(height: 12),
Text(
_routeStatusMessage!,
style: Theme.of(context).textTheme.bodyMedium,
),
],
if (_routeErrorMessage != null) ...[
const SizedBox(height: 12),
Text(
_routeErrorMessage!,
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
color: Theme.of(context).colorScheme.error,
),
),
],
if ((_routeStatus == 'failed' || _routeErrorMessage != null) &&
_routeFiles.isNotEmpty) ...[
const SizedBox(height: 8),
OutlinedButton.icon(
onPressed: _routeUploading ? null : _uploadRouteFiles,
icon: const Icon(Icons.refresh),
label: const Text('Retry upload'),
),
],
],
),
);

View File

@@ -1399,16 +1399,18 @@ class _NewEntryPageState extends State<NewEntryPage> {
singleColumn: true,
),
),
const Divider(height: 24),
TextFormField(
controller: _networkController,
textCapitalization: TextCapitalization.characters,
inputFormatters: const [_UpperCaseTextFormatter()],
decoration: const InputDecoration(
labelText: 'Network',
border: OutlineInputBorder(),
if (_useManualMileage) ...[
const Divider(height: 24),
TextFormField(
controller: _networkController,
textCapitalization: TextCapitalization.characters,
inputFormatters: const [_UpperCaseTextFormatter()],
decoration: const InputDecoration(
labelText: 'Network',
border: OutlineInputBorder(),
),
),
),
],
TextFormField(
controller: _notesController,
maxLines: 3,
@@ -1520,6 +1522,9 @@ class _NewEntryPageState extends State<NewEntryPage> {
onSelected: (val) {
setState(() {
_useManualMileage = val;
if (!val) {
_networkController.clear();
}
if (val && _routeResult != null) {
_mileageController.text = _formatDistance(
distanceUnitService,

View File

@@ -18,7 +18,7 @@ extension _NewEntrySubmitLogic on _NewEntryPageState {
}
}
if (_networkController.text.trim().isEmpty) {
if (_useManualMileage && _networkController.text.trim().isEmpty) {
missing.add('Network');
}
@@ -93,7 +93,7 @@ extension _NewEntrySubmitLogic on _NewEntryPageState {
final isEditingExisting = _isEditing && widget.editLegId != null;
try {
final commonPayload = {
final commonPayload = {
if (isEditingExisting) "leg_id": widget.editLegId,
"leg_trip": _selectedTripId,
"leg_begin_time": _legDateTime.toIso8601String(),
@@ -104,7 +104,8 @@ extension _NewEntrySubmitLogic on _NewEntryPageState {
"leg_destination_time": destinationTime.toIso8601String(),
"leg_notes": _notesController.text.trim(),
"leg_headcode": _headcodeController.text.trim(),
"leg_network": _networkController.text.trim(),
if (_useManualMileage)
"leg_network": _networkController.text.trim(),
"leg_origin": _originController.text.trim(),
"leg_destination": _destinationController.text.trim(),
"leg_begin_delay": beginDelay,

View File

@@ -170,6 +170,21 @@ class _StatsPageState extends State<StatsPage> {
),
),
),
if (year.topCountries.isNotEmpty)
_buildSection<StatsCountryMileage>(
context,
title: 'Top countries',
items: year.topCountries,
emptyLabel: 'No country data',
itemBuilder: (item, index) => ListTile(
dense: true,
contentPadding: const EdgeInsets.symmetric(horizontal: 8),
title: Text(item.country),
trailing: Text(
distanceUnits.format(item.mileage, decimals: 1),
),
),
),
_buildSection<StatsStationVisits>(
context,
title: 'Top stations',

View File

@@ -699,11 +699,8 @@ class _TractionPageState extends State<TractionPage> {
);
final hasAdminActions = isElevated;
final hasMoreMenu = true;
final moreButton = !hasMoreMenu
? null
: PopupMenuButton<_TractionMoreAction>(
final moreButton = PopupMenuButton<_TractionMoreAction>(
tooltip: 'More options',
onSelected: (action) async {
switch (action) {
@@ -859,11 +856,11 @@ class _TractionPageState extends State<TractionPage> {
final desktopActions = [
refreshButton,
newTractionButton,
if (moreButton != null) moreButton,
moreButton,
];
final mobileActions = [
if (moreButton != null) moreButton,
moreButton,
newTractionButton,
refreshButton,
];
@@ -972,6 +969,10 @@ class _TractionPageState extends State<TractionPage> {
Map<String, dynamic>? importResult;
String? statusMessage;
String? errorMessage;
String? jobStatus;
int? processed;
int? total;
double? progressValue;
await showModalBottomSheet<void>(
context: context,
@@ -980,6 +981,65 @@ class _TractionPageState extends State<TractionPage> {
final theme = Theme.of(sheetContext);
return StatefulBuilder(
builder: (context, setModalState) {
int? parseCount(dynamic value) {
if (value is num) return value.toInt();
return int.tryParse(value?.toString() ?? '');
}
double? parsePercent(
dynamic value, {
required int? processed,
required int? total,
}) {
if (value is num) {
final raw = value.toDouble();
final normalized = raw > 1 ? raw / 100 : raw;
return normalized.clamp(0, 1);
}
if (processed != null && total != null && total > 0) {
return (processed / total).clamp(0, 1);
}
return null;
}
Duration pollDelay(int attempt) {
const delays = [
Duration(seconds: 1),
Duration(seconds: 2),
Duration(seconds: 2),
Duration(seconds: 5),
Duration(seconds: 5),
Duration(seconds: 8),
Duration(seconds: 10),
];
if (attempt < delays.length) return delays[attempt];
return const Duration(seconds: 10);
}
String statusLabel(
String status, {
required int? processed,
required int? total,
required double? percent,
}) {
final lower = status.toLowerCase();
final base = switch (lower) {
'queued' => 'Queued',
'running' => 'Processing',
'succeeded' => 'Completed',
'failed' => 'Failed',
_ => status,
};
final parts = <String>[base];
if (processed != null && total != null) {
parts.add('Rows $processed of $total');
}
if (percent != null) {
parts.add('${(percent * 100).toStringAsFixed(0)}%');
}
return parts.join(' · ');
}
Future<void> pickFile() async {
final file = await openFile(
acceptedTypeGroups: const [
@@ -995,6 +1055,10 @@ class _TractionPageState extends State<TractionPage> {
importResult = null;
statusMessage = null;
errorMessage = null;
jobStatus = null;
processed = null;
total = null;
progressValue = null;
});
}
@@ -1006,6 +1070,10 @@ class _TractionPageState extends State<TractionPage> {
importResult = null;
statusMessage = null;
errorMessage = null;
jobStatus = null;
processed = null;
total = null;
progressValue = null;
});
try {
final data = context.read<DataService>();
@@ -1016,33 +1084,98 @@ class _TractionPageState extends State<TractionPage> {
filename: file.name,
headers: const {'accept': 'application/json'},
);
if (!mounted) return;
if (!context.mounted) return;
final parsed = response is Map
? Map<String, dynamic>.from(response)
: null;
if (parsed != null) {
final imported = _importCount(parsed['imported']);
final updated = _importCount(parsed['updated']);
final errors = _importErrors(parsed);
final errorNote =
errors.isNotEmpty ? ' (${errors.length} error(s))' : '';
statusMessage =
'Import complete. Imported $imported, updated $updated$errorNote.';
importResult = parsed;
} else {
statusMessage = 'Import complete.';
final jobId = parsed?['job_id']?.toString();
if (jobId == null || jobId.isEmpty) {
setModalState(() {
errorMessage = 'Upload failed to start.';
});
return;
}
setModalState(() {
jobStatus = parsed?['status']?.toString() ?? 'queued';
});
var attempt = 0;
while (context.mounted) {
final statusResponse =
await data.api.get('/uploads/$jobId');
if (!context.mounted) return;
final statusMap = statusResponse is Map
? Map<String, dynamic>.from(statusResponse)
: null;
if (statusMap == null) {
setModalState(() {
errorMessage = 'Upload status unavailable.';
});
return;
}
final status = statusMap['status']?.toString() ?? 'queued';
final processedCount = parseCount(statusMap['processed']);
final totalCount = parseCount(statusMap['total']);
final percent = parsePercent(
statusMap['percent'],
processed: processedCount,
total: totalCount,
);
setModalState(() {
jobStatus = status;
processed = processedCount;
total = totalCount;
progressValue = percent;
});
if (status == 'succeeded') {
final result = statusMap['result'];
Map<String, dynamic>? parsedResult;
if (result is Map) {
parsedResult = Map<String, dynamic>.from(result);
}
setModalState(() {
importResult = parsedResult;
if (importResult != null) {
final imported =
_importCount(importResult!['imported']);
final updated = _importCount(importResult!['updated']);
final errors = _importErrors(importResult!);
final errorNote = errors.isNotEmpty
? ' (${errors.length} error(s))'
: '';
statusMessage =
'Import complete. Imported $imported, updated $updated$errorNote.';
} else {
statusMessage = 'Import complete.';
}
});
await data.fetchClassList();
await _refreshTraction(preservePosition: true);
return;
}
if (status == 'failed') {
setModalState(() {
errorMessage =
statusMap['error']?.toString() ?? 'Import failed.';
});
return;
}
await Future.delayed(pollDelay(attempt));
attempt += 1;
}
await data.fetchClassList();
await _refreshTraction(preservePosition: true);
} on ApiException catch (e) {
if (!mounted) return;
errorMessage = e.message;
if (!context.mounted) return;
setModalState(() {
errorMessage = e.message;
});
} catch (e) {
if (!mounted) return;
errorMessage = e.toString();
if (!context.mounted) return;
setModalState(() {
errorMessage = e.toString();
});
} finally {
if (!mounted) return;
setModalState(() => uploading = false);
if (context.mounted) {
setModalState(() => uploading = false);
}
}
}
@@ -1100,6 +1233,22 @@ class _TractionPageState extends State<TractionPage> {
uploading ? 'Importing...' : 'Upload and import',
),
),
if (jobStatus != null) ...[
const SizedBox(height: 12),
Text(
statusLabel(
jobStatus!,
processed: processed,
total: total,
percent: progressValue,
),
style: theme.textTheme.bodyMedium,
),
if (progressValue != null) ...[
const SizedBox(height: 6),
LinearProgressIndicator(value: progressValue),
],
],
if (statusMessage != null) ...[
const SizedBox(height: 12),
Text(
@@ -1116,6 +1265,15 @@ class _TractionPageState extends State<TractionPage> {
),
),
],
if ((jobStatus == 'failed' || errorMessage != null) &&
selectedFile != null) ...[
const SizedBox(height: 8),
OutlinedButton.icon(
onPressed: uploading ? null : uploadFile,
icon: const Icon(Icons.refresh),
label: const Text('Retry upload'),
),
],
if (importResult != null)
_buildImportSummary(context, importResult!),
],

View File

@@ -517,6 +517,7 @@ class StatsAbout {
final mileageByYear = <int, double>{};
final classByYear = <int, List<StatsClassMileage>>{};
final networkByYear = <int, List<StatsNetworkMileage>>{};
final countryByYear = <int, List<StatsCountryMileage>>{};
final stationByYear = <int, List<StatsStationVisits>>{};
final winnersByYear = <int, int>{};
final winnerTypeCountsByYear = <int, Map<String, int>>{};
@@ -577,6 +578,17 @@ class StatsAbout {
return const [];
}
List<StatsCountryMileage> parseCountryList(dynamic value) {
if (value is List) {
return value
.whereType<Map>()
.map((e) => StatsCountryMileage.fromJson(
e.map((key, value) => MapEntry(key.toString(), value))))
.toList();
}
return const [];
}
void parseYearMap<T>(
dynamic source,
Map<int, T> target,
@@ -611,6 +623,11 @@ class StatsAbout {
networkByYear,
parseNetworkList,
);
parseYearMap<List<StatsCountryMileage>>(
json['top_countries'],
countryByYear,
parseCountryList,
);
parseYearMap<List<StatsStationVisits>>(
json['top_stations'],
stationByYear,
@@ -643,6 +660,7 @@ class StatsAbout {
...mileageByYear.keys,
...classByYear.keys,
...networkByYear.keys,
...countryByYear.keys,
...stationByYear.keys,
...winnersByYear.keys,
...winnerTypeCountsByYear.keys,
@@ -656,6 +674,7 @@ class StatsAbout {
mileage: mileageByYear[year] ?? 0,
topClasses: classByYear[year] ?? const [],
topNetworks: networkByYear[year] ?? const [],
topCountries: countryByYear[year] ?? const [],
topStations: stationByYear[year] ?? const [],
winnerCount: winnersByYear[year] ?? 0,
winnerTypeCounts: winnerTypeCountsByYear[year] ?? const {},
@@ -678,6 +697,7 @@ class StatsYear {
final double mileage;
final List<StatsClassMileage> topClasses;
final List<StatsNetworkMileage> topNetworks;
final List<StatsCountryMileage> topCountries;
final List<StatsStationVisits> topStations;
final int winnerCount;
final Map<String, int> winnerTypeCounts;
@@ -688,6 +708,7 @@ class StatsYear {
required this.mileage,
required this.topClasses,
required this.topNetworks,
required this.topCountries,
required this.topStations,
required this.winnerCount,
required this.winnerTypeCounts,
@@ -727,6 +748,22 @@ class StatsNetworkMileage {
);
}
class StatsCountryMileage {
final String country;
final double mileage;
StatsCountryMileage({
required this.country,
required this.mileage,
});
factory StatsCountryMileage.fromJson(Map<String, dynamic> json) =>
StatsCountryMileage(
country: _asString(json['country'], 'Unknown'),
mileage: _asDouble(json['mileage']),
);
}
class StatsStationVisits {
final String station;
final int visits;
@@ -1205,6 +1242,8 @@ class Leg {
final String start, end, network, notes, headcode, user;
final String origin, destination;
final List<String> route;
final List<NetworkMileage> networkMileage;
final List<CountryMileage> countryMileage;
final String? legShareId;
final LegShareMeta? sharedFrom;
final List<LegShareMeta> sharedTo;
@@ -1231,6 +1270,8 @@ class Leg {
required this.driving,
required this.user,
required this.locos,
this.networkMileage = const [],
this.countryMileage = const [],
this.endTime,
this.originTime,
this.destinationTime,
@@ -1300,6 +1341,14 @@ class Leg {
: _asInt(json['leg_end_delay']),
origin: _asString(json['leg_origin']),
destination: _asString(json['leg_destination']),
networkMileage: (json['network_mileage'] as List? ?? const [])
.whereType<Map>()
.map((e) => NetworkMileage.fromJson(Map<String, dynamic>.from(e)))
.toList(),
countryMileage: (json['country_mileage'] as List? ?? const [])
.whereType<Map>()
.map((e) => CountryMileage.fromJson(Map<String, dynamic>.from(e)))
.toList(),
legShareId: _asString(json['leg_share_id']),
sharedFrom: sharedFrom,
sharedTo: sharedTo,
@@ -1470,12 +1519,16 @@ class RouteResult {
final List<String> calculatedRoute;
final List<double> costs;
final double distance;
final List<NetworkMileage> networkMileage;
final List<CountryMileage> countryMileage;
RouteResult({
required this.inputRoute,
required this.calculatedRoute,
required this.costs,
required this.distance,
this.networkMileage = const [],
this.countryMileage = const [],
});
factory RouteResult.fromJson(Map<String, dynamic> json) {
@@ -1484,10 +1537,50 @@ class RouteResult {
calculatedRoute: List<String>.from(json['calculated_route']),
costs: (json['costs'] as List).map((e) => (e as num).toDouble()).toList(),
distance: (json['distance'] as num).toDouble(),
networkMileage: (json['network_mileage'] as List? ?? const [])
.whereType<Map>()
.map((e) => NetworkMileage.fromJson(Map<String, dynamic>.from(e)))
.toList(),
countryMileage: (json['country_mileage'] as List? ?? const [])
.whereType<Map>()
.map((e) => CountryMileage.fromJson(Map<String, dynamic>.from(e)))
.toList(),
);
}
}
class NetworkMileage {
final String network;
final double miles;
NetworkMileage({
required this.network,
required this.miles,
});
factory NetworkMileage.fromJson(Map<String, dynamic> json) =>
NetworkMileage(
network: _asString(json['network']),
miles: _asDouble(json['miles']),
);
}
class CountryMileage {
final String country;
final double miles;
CountryMileage({
required this.country,
required this.miles,
});
factory CountryMileage.fromJson(Map<String, dynamic> json) =>
CountryMileage(
country: _asString(json['country']),
miles: _asDouble(json['miles']),
);
}
class Station {
final int id;
final String name;

View File

@@ -4,6 +4,18 @@ import 'package:http/http.dart' as http;
typedef TokenProvider = String? Function();
typedef UnauthorizedHandler = Future<bool> Function();
class MultipartFilePayload {
MultipartFilePayload({
required this.bytes,
required this.filename,
this.fieldName,
});
final List<int> bytes;
final String filename;
final String? fieldName;
}
class ApiService {
String _baseUrl;
final http.Client _client;
@@ -192,6 +204,41 @@ class ApiService {
return _processResponse(response);
}
Future<dynamic> postMultipartFiles(
String endpoint, {
required List<MultipartFilePayload> files,
String fieldName = 'files',
Map<String, String>? fields,
Map<String, String>? headers,
bool includeAuth = true,
bool allowRetry = true,
}) async {
Future<http.Response> send() async {
final request = http.MultipartRequest(
'POST',
Uri.parse('$baseUrl$endpoint'),
);
request.headers.addAll(_buildHeaders(headers, includeAuth: includeAuth));
if (fields != null && fields.isNotEmpty) {
request.fields.addAll(fields);
}
for (final file in files) {
request.files.add(
http.MultipartFile.fromBytes(
file.fieldName ?? fieldName,
file.bytes,
filename: file.filename,
),
);
}
final streamed = await _client.send(request);
return http.Response.fromStream(streamed);
}
final response = await _sendWithRetry(send, allowRetry: allowRetry);
return _processResponse(response);
}
Future<dynamic> postForm(
String endpoint,
Map<String, String> data, {

View File

@@ -16,7 +16,7 @@ publish_to: "none" # Remove this line if you wish to publish to pub.dev
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
# In Windows, build-name is used as the major, minor, and patch parts
# of the product and file versions while build-number is used as the build suffix.
version: 0.7.8+16
version: 0.8.1+18
environment:
sdk: ^3.8.1

View File

@@ -1,4 +1,3 @@
import 'package:flutter/foundation.dart';
import 'package:mileograph_flutter/objects/objects.dart';
import 'package:mileograph_flutter/services/api_service.dart';
import 'package:mileograph_flutter/services/authservice.dart';
@@ -8,14 +7,18 @@ import 'package:mileograph_flutter/services/distance_unit_service.dart';
import 'test_data.dart';
class FakeApiService extends ApiService {
FakeApiService({String baseUrl = 'https://example.com'})
: super(baseUrl: baseUrl);
FakeApiService({super.baseUrl = 'https://example.com'});
final Map<String, dynamic> getResponses = {};
final Map<String, dynamic> postResponses = {};
@override
Future<dynamic> get(String endpoint, {Map<String, String>? headers}) async {
Future<dynamic> get(
String endpoint, {
Map<String, String>? headers,
bool includeAuth = true,
bool allowRetry = true,
}) async {
return getResponses[endpoint];
}
@@ -24,6 +27,8 @@ class FakeApiService extends ApiService {
String endpoint,
dynamic data, {
Map<String, String>? headers,
bool includeAuth = true,
bool allowRetry = true,
}) async {
return postResponses[endpoint] ?? {};
}
@@ -170,20 +175,16 @@ class FakeDataService extends DataService {
@override
Future<void> fetchOnThisDay({DateTime? date}) async {}
@override
Future<void> fetchTripDetails() async {}
@override
Future<void> fetchHadTraction({int offset = 0, int limit = 100}) async {}
@override
Future<void> fetchLatestLocoChanges({
int limit = 100,
int offset = 0,
bool append = false,
}) async {}
@override
Future<void> fetchClassClearanceProgress({
int offset = 0,
int limit = 20,
@@ -204,12 +205,10 @@ class FakeDataService extends DataService {
List<String> networkFilter = const [],
}) async {}
@override
Future<List<TripLocoStat>> fetchTripLocoStats(int tripId) async {
return const [];
}
@override
Future<void> fetchTraction({
bool hadOnly = false,
int offset = 0,
@@ -221,7 +220,6 @@ class FakeDataService extends DataService {
Map<String, dynamic>? filters,
}) async {}
@override
Future<List<String>> fetchClassList({bool force = false}) async {
return locoClassesValue;
}
@@ -235,12 +233,10 @@ class FakeDataService extends DataService {
@override
Future<void> fetchStationNetworks() async {}
@override
Future<Map<String, dynamic>?> fetchClassStats(String locoClass) async {
return TestData.classStats;
}
@override
Future<List<LeaderboardEntry>> fetchClassLeaderboard(
String locoClass, {
bool friends = false,