Integration fonctionnalités V1 ( resas + gestion machines

This commit is contained in:
bastien
2026-07-03 19:02:48 +02:00
parent 20f383dd62
commit bf191d6396
46 changed files with 4691 additions and 654 deletions
@@ -0,0 +1,219 @@
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:mobile_scanner/mobile_scanner.dart';
import '../../../core/api/api_response.dart';
import '../../../core/router/app_router.dart';
import '../../../core/theme/app_colors.dart';
import '../../machines/data/machine_repository.dart';
import '../../wash/data/wash_repository.dart';
/// Écran de scan QR → page dédiée machine.
class QrScannerScreen extends ConsumerStatefulWidget {
const QrScannerScreen({super.key});
@override
ConsumerState<QrScannerScreen> createState() => _QrScannerScreenState();
}
class _QrScannerScreenState extends ConsumerState<QrScannerScreen> {
final MobileScannerController _controller = MobileScannerController(
detectionSpeed: DetectionSpeed.noDuplicates,
facing: CameraFacing.back,
);
bool _isProcessing = false;
String? _lastScannedValue;
static const _frameSize = 260.0;
@override
void dispose() {
_controller.dispose();
super.dispose();
}
Future<void> _onDetect(BarcodeCapture capture) async {
if (_isProcessing) return;
final value = capture.barcodes.firstOrNull?.rawValue?.trim();
if (value == null || value.isEmpty) return;
if (value == _lastScannedValue) return;
setState(() {
_isProcessing = true;
_lastScannedValue = value;
});
await _controller.stop();
try {
final reference = QrMachineReference.parse(value);
if (!reference.isValid) {
throw const FormatException('QR code invalide');
}
final detail = await ref.read(machineRepositoryProvider).lookup(
qrCode: reference.qrCode,
machineUuid: reference.machineUuid,
);
if (!mounted) return;
context.pop();
context.push(AppRoutes.machineAction(detail.machine.uuid));
} on DioException catch (error) {
if (!mounted) return;
_showErrorAndResume(ApiResponse.errorMessage(error, fallback: 'Machine introuvable'));
} on FormatException catch (error) {
if (!mounted) return;
_showErrorAndResume(error.message);
} catch (_) {
if (!mounted) return;
_showErrorAndResume('Impossible de lire ce QR code');
}
}
Future<void> _showErrorAndResume(String message) async {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(message), backgroundColor: AppColors.error),
);
setState(() {
_isProcessing = false;
_lastScannedValue = null;
});
await _controller.start();
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.black,
appBar: AppBar(
title: const Text('Scanner une machine'),
backgroundColor: Colors.black,
foregroundColor: Colors.white,
actions: [
IconButton(
tooltip: 'Lampe',
onPressed: () => _controller.toggleTorch(),
icon: const Icon(Icons.flash_on_rounded),
),
],
),
body: Stack(
fit: StackFit.expand,
children: [
MobileScanner(
controller: _controller,
onDetect: _onDetect,
),
CustomPaint(
painter: _ScannerOverlayPainter(frameSize: _frameSize),
child: const SizedBox.expand(),
),
Align(
alignment: Alignment.bottomCenter,
child: Container(
width: double.infinity,
padding: const EdgeInsets.fromLTRB(24, 24, 24, 32),
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [Colors.transparent, Colors.black.withValues(alpha: 0.9)],
),
),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const Text(
'Placez le QR code dans le cadre',
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.w600,
fontSize: 16,
),
),
const SizedBox(height: 6),
Text(
'Ex. démo : LAVERIE-DEMO-001',
textAlign: TextAlign.center,
style: TextStyle(color: Colors.white.withValues(alpha: 0.7), fontSize: 13),
),
if (_isProcessing) ...[
const SizedBox(height: 16),
const SizedBox(
width: 28,
height: 28,
child: CircularProgressIndicator(strokeWidth: 2.5, color: Colors.white),
),
const SizedBox(height: 8),
const Text(
'Identification de la machine…',
style: TextStyle(color: Colors.white70, fontSize: 13),
),
],
],
),
),
),
],
),
);
}
}
class _ScannerOverlayPainter extends CustomPainter {
_ScannerOverlayPainter({required this.frameSize});
final double frameSize;
@override
void paint(Canvas canvas, Size size) {
final center = Offset(size.width / 2, size.height / 2);
final rect = Rect.fromCenter(center: center, width: frameSize, height: frameSize);
final rrect = RRect.fromRectAndRadius(rect, const Radius.circular(20));
canvas.drawPath(
Path.combine(
PathOperation.difference,
Path()..addRect(Rect.fromLTWH(0, 0, size.width, size.height)),
Path()..addRRect(rrect),
),
Paint()..color = Colors.black.withValues(alpha: 0.55),
);
canvas.drawRRect(
rrect,
Paint()
..color = Colors.white
..style = PaintingStyle.stroke
..strokeWidth = 2.5,
);
const cornerLen = 28.0;
final corner = Paint()
..color = AppColors.primary
..style = PaintingStyle.stroke
..strokeWidth = 4
..strokeCap = StrokeCap.round;
canvas.drawLine(rect.topLeft, rect.topLeft + const Offset(cornerLen, 0), corner);
canvas.drawLine(rect.topLeft, rect.topLeft + const Offset(0, cornerLen), corner);
canvas.drawLine(rect.topRight, rect.topRight + const Offset(-cornerLen, 0), corner);
canvas.drawLine(rect.topRight, rect.topRight + const Offset(0, cornerLen), corner);
canvas.drawLine(rect.bottomLeft, rect.bottomLeft + const Offset(cornerLen, 0), corner);
canvas.drawLine(rect.bottomLeft, rect.bottomLeft + const Offset(0, -cornerLen), corner);
canvas.drawLine(rect.bottomRight, rect.bottomRight + const Offset(-cornerLen, 0), corner);
canvas.drawLine(rect.bottomRight, rect.bottomRight + const Offset(0, -cornerLen), corner);
}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}
+133 -84
View File
@@ -1,103 +1,152 @@
import 'dart:async';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:intl/intl.dart';
import '../../../core/api/api_client.dart';
import '../../../core/api/api_endpoints.dart';
import '../../../core/api/api_response.dart';
import '../../../core/router/app_router.dart';
import '../../../core/theme/app_colors.dart';
import '../../../core/widgets/empty_state.dart';
import '../../../core/widgets/screen_header.dart';
import '../data/wash_repository.dart';
import '../domain/wash.dart';
import '../domain/wash_progress.dart';
import 'widgets/active_wash_progress_card.dart';
/// Fournisseur de l'historique des lavages.
final washesProvider = FutureProvider<List<Wash>>((ref) async {
final response = await ref.watch(apiClientProvider).get(ApiEndpoints.washes);
final data = response.data;
bool _isActiveWash(String status) =>
status == 'running' || status == 'pending_start' || status == 'active';
List<dynamic> list;
if (data is List<dynamic>) {
list = data;
} else if (data is Map<String, dynamic> && data['data'] is List<dynamic>) {
list = data['data'] as List<dynamic>;
} else {
list = [];
}
return list.map((json) => Wash.fromJson(json as Map<String, dynamic>)).toList();
});
/// Écran historique et démarrage de lavage.
class WashScreen extends ConsumerWidget {
/// Écran historique et lavages en cours avec progression.
class WashScreen extends ConsumerStatefulWidget {
const WashScreen({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
ConsumerState<WashScreen> createState() => _WashScreenState();
}
class _WashScreenState extends ConsumerState<WashScreen> {
Timer? _ticker;
@override
void initState() {
super.initState();
_ticker = Timer.periodic(const Duration(seconds: 1), (_) {
if (mounted) setState(() {});
});
}
@override
void dispose() {
_ticker?.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
final washesAsync = ref.watch(washesProvider);
return Scaffold(
appBar: AppBar(title: const Text('Mes lavages')),
body: washesAsync.when(
loading: () => const Center(child: CircularProgressIndicator()),
error: (error, _) => Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
return washesAsync.when(
loading: () => const Center(child: CircularProgressIndicator()),
error: (error, _) => EmptyState(
icon: Icons.error_outline,
title: 'Erreur de chargement',
subtitle: error is DioException
? ApiResponse.errorMessage(error, fallback: 'Impossible de charger les lavages.')
: 'Impossible de charger les lavages.',
actionLabel: 'Réessayer',
onAction: () => ref.invalidate(washesProvider),
),
data: (washes) {
if (washes.isEmpty) {
return EmptyState(
icon: Icons.qr_code_scanner_outlined,
title: 'Aucun lavage',
subtitle: 'Scannez une machine pour voir\nses infos et démarrer un cycle.',
actionLabel: 'Scanner',
onAction: () => context.push(AppRoutes.washScan),
);
}
final active = washes.where((w) => _isActiveWash(w.status)).toList();
final history = washes.where((w) => !_isActiveWash(w.status)).toList();
final currencyFormat = NumberFormat.currency(locale: 'fr_FR', symbol: '');
return RefreshIndicator(
onRefresh: () async => ref.invalidate(washesProvider),
child: ListView(
padding: const EdgeInsets.fromLTRB(16, 8, 16, 88),
children: [
Text('Erreur : $error'),
const SizedBox(height: 12),
ElevatedButton(
onPressed: () => ref.invalidate(washesProvider),
child: const Text('Réessayer'),
),
if (active.isNotEmpty) ...[
const ScreenHeader(
title: 'En cours',
subtitle: 'Progression en temps réel',
),
...active.map((wash) {
final progress = _liveProgress(wash);
return ActiveWashProgressCard(
wash: wash,
format: currencyFormat,
progress: progress,
);
}),
const SizedBox(height: 16),
],
if (history.isNotEmpty) ...[
Text('Historique', style: Theme.of(context).textTheme.titleMedium),
const SizedBox(height: 10),
...history.map(
(wash) => Padding(
padding: const EdgeInsets.only(bottom: 8),
child: _HistoryWashTile(wash: wash, format: currencyFormat),
),
),
],
],
),
);
},
);
}
WashProgress _liveProgress(Wash wash) {
if (wash.progress != null && wash.progress!.percent > 0) {
return WashProgress.compute(
startedAt: wash.startedAt,
estimatedEndAt: wash.progress!.estimatedEndAt ?? wash.cycleEndsAt,
durationMinutes: wash.durationMinutes,
machineType: wash.machineType,
status: wash.status,
);
}
return wash.liveProgress;
}
}
class _HistoryWashTile extends StatelessWidget {
const _HistoryWashTile({required this.wash, required this.format});
final Wash wash;
final NumberFormat format;
@override
Widget build(BuildContext context) {
return Card(
child: ListTile(
leading: const CircleAvatar(
backgroundColor: Color(0xFFE2E8F0),
child: Icon(Icons.check_circle_outline, color: AppColors.success, size: 20),
),
title: Text(wash.machineName),
subtitle: wash.startedAt != null
? Text(DateFormat('dd/MM/yyyy · HH:mm').format(wash.startedAt!))
: null,
trailing: Text(
format.format(wash.cost),
style: const TextStyle(fontWeight: FontWeight.w600),
),
data: (washes) {
if (washes.isEmpty) {
return const Center(
child: Text(
'Aucun lavage enregistré.\nScannez un QR code pour démarrer un cycle.',
textAlign: TextAlign.center,
),
);
}
final currencyFormat = NumberFormat.currency(locale: 'fr_FR', symbol: '');
return RefreshIndicator(
onRefresh: () async => ref.invalidate(washesProvider),
child: ListView.separated(
padding: const EdgeInsets.all(16),
itemCount: washes.length,
separatorBuilder: (_, __) => const SizedBox(height: 8),
itemBuilder: (context, index) {
final wash = washes[index];
return Card(
child: ListTile(
leading: const Icon(Icons.local_laundry_service),
title: Text(wash.machineName),
subtitle: wash.startedAt != null
? Text(DateFormat('dd/MM/yyyy HH:mm').format(wash.startedAt!))
: null,
trailing: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Text(currencyFormat.format(wash.cost)),
Text(wash.status, style: Theme.of(context).textTheme.bodySmall),
],
),
),
);
},
),
);
},
),
floatingActionButton: FloatingActionButton.extended(
onPressed: () {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Scan QR — à connecter à l\'API /washes/start')),
);
},
icon: const Icon(Icons.qr_code_scanner),
label: const Text('Scanner'),
),
);
}
@@ -0,0 +1,163 @@
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import '../../../../core/theme/app_colors.dart';
import '../../domain/wash.dart';
import '../../domain/wash_progress.dart';
/// Carte lavage en cours avec pourcentage et étape du cycle.
class ActiveWashProgressCard extends StatelessWidget {
const ActiveWashProgressCard({
super.key,
required this.wash,
required this.format,
this.progress,
});
final Wash wash;
final NumberFormat format;
final WashProgress? progress;
@override
Widget build(BuildContext context) {
final p = progress ?? wash.liveProgress;
final steps = _stepsForType(wash.machineType);
final currentIndex = steps.indexWhere((s) => s.key == p.phase);
final activeStep = currentIndex >= 0 ? currentIndex : 0;
return Card(
margin: const EdgeInsets.only(bottom: 10),
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Container(
width: 44,
height: 44,
decoration: BoxDecoration(
color: AppColors.machineRunning.withValues(alpha: 0.12),
borderRadius: BorderRadius.circular(12),
),
child: const Icon(Icons.local_laundry_service, color: AppColors.machineRunning),
),
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(wash.machineName, style: Theme.of(context).textTheme.titleMedium),
Text(
p.phaseLabel,
style: TextStyle(
color: AppColors.machineRunning,
fontWeight: FontWeight.w600,
fontSize: 13,
),
),
],
),
),
Text(
'${p.percent}%',
style: const TextStyle(
fontSize: 22,
fontWeight: FontWeight.w700,
color: AppColors.machineRunning,
),
),
],
),
const SizedBox(height: 14),
ClipRRect(
borderRadius: BorderRadius.circular(6),
child: LinearProgressIndicator(
value: p.percent / 100,
minHeight: 8,
backgroundColor: AppColors.machineRunning.withValues(alpha: 0.12),
color: AppColors.machineRunning,
),
),
const SizedBox(height: 14),
Row(
children: List.generate(steps.length, (index) {
final step = steps[index];
final isDone = index < activeStep;
final isActive = index == activeStep;
final color = isDone || isActive
? AppColors.machineRunning
: AppColors.textSecondary.withValues(alpha: 0.35);
return Expanded(
child: Column(
children: [
Icon(
isDone ? Icons.check_circle : step.icon,
size: 20,
color: color,
),
const SizedBox(height: 4),
Text(
step.label,
maxLines: 1,
overflow: TextOverflow.ellipsis,
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 9,
fontWeight: isActive ? FontWeight.w700 : FontWeight.normal,
color: isActive ? AppColors.machineRunning : AppColors.textSecondary,
),
),
],
),
);
}),
),
const SizedBox(height: 12),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
p.remainingLabel.isNotEmpty ? p.remainingLabel : 'Cycle en cours…',
style: Theme.of(context).textTheme.bodyMedium,
),
Text(
format.format(wash.cost),
style: const TextStyle(fontWeight: FontWeight.w600),
),
],
),
],
),
),
);
}
static List<_WashStep> _stepsForType(String? type) {
if (type?.startsWith('dryer') ?? false) {
return const [
_WashStep('lock', 'Verrou', Icons.lock_outline),
_WashStep('heat', 'Chauffe', Icons.whatshot_outlined),
_WashStep('dry', 'Sèche', Icons.air),
_WashStep('finish', 'Fin', Icons.check),
];
}
return const [
_WashStep('lock', 'Verrou', Icons.lock_outline),
_WashStep('fill', 'Eau', Icons.water_drop_outlined),
_WashStep('wash', 'Lave', Icons.local_laundry_service_outlined),
_WashStep('rinse', 'Rince', Icons.waves_outlined),
_WashStep('spin', 'Essore', Icons.rotate_right),
_WashStep('finish', 'Fin', Icons.check),
];
}
}
class _WashStep {
const _WashStep(this.key, this.label, this.icon);
final String key;
final String label;
final IconData icon;
}