Initial commit: unionflow-mobile-apps

Application Flutter complète (sans build artifacts).

Signed-off-by: lions dev Team
This commit is contained in:
dahoud
2026-03-15 16:30:08 +00:00
commit d094d6db9c
1790 changed files with 507435 additions and 0 deletions

View File

@@ -0,0 +1,92 @@
/// BLoC pour les demandes d'aide (solidarité)
library solidarity_bloc;
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:injectable/injectable.dart';
import '../data/models/demande_aide_model.dart';
import '../data/repositories/demande_aide_repository.dart';
part 'solidarity_event.dart';
part 'solidarity_state.dart';
@injectable
class SolidarityBloc extends Bloc<SolidarityEvent, SolidarityState> {
final DemandeAideRepository _repository;
SolidarityBloc(this._repository) : super(const SolidarityState()) {
on<LoadDemandesAide>(_onLoadDemandesAide);
on<LoadDemandeAideById>(_onLoadDemandeAideById);
on<SearchDemandesAide>(_onSearchDemandesAide);
on<CreateDemandeAide>(_onCreateDemandeAide);
on<ApprouverDemandeAide>(_onApprouverDemandeAide);
on<RejeterDemandeAide>(_onRejeterDemandeAide);
}
Future<void> _onLoadDemandesAide(LoadDemandesAide event, Emitter<SolidarityState> emit) async {
emit(state.copyWith(status: SolidarityStatus.loading, message: 'Chargement...'));
try {
final list = await _repository.getMesDemandes(page: event.page, size: event.size);
emit(state.copyWith(status: SolidarityStatus.loaded, demandes: list));
} catch (e) {
emit(state.copyWith(status: SolidarityStatus.error, message: e.toString(), error: e));
}
}
Future<void> _onLoadDemandeAideById(LoadDemandeAideById event, Emitter<SolidarityState> emit) async {
emit(state.copyWith(status: SolidarityStatus.loading));
try {
final demande = await _repository.getById(event.id);
emit(state.copyWith(status: SolidarityStatus.loaded, demandeDetail: demande));
} catch (e) {
emit(state.copyWith(status: SolidarityStatus.error, message: e.toString(), error: e));
}
}
Future<void> _onSearchDemandesAide(SearchDemandesAide event, Emitter<SolidarityState> emit) async {
emit(state.copyWith(status: SolidarityStatus.loading));
try {
final list = await _repository.search(
statut: event.statut,
type: event.type,
page: event.page,
size: event.size,
);
emit(state.copyWith(status: SolidarityStatus.loaded, demandes: list));
} catch (e) {
emit(state.copyWith(status: SolidarityStatus.error, message: e.toString(), error: e));
}
}
Future<void> _onCreateDemandeAide(CreateDemandeAide event, Emitter<SolidarityState> emit) async {
emit(state.copyWith(status: SolidarityStatus.loading, message: 'Création...'));
try {
await _repository.create(event.demande);
add(const LoadDemandesAide());
} catch (e) {
emit(state.copyWith(status: SolidarityStatus.error, message: e.toString(), error: e));
}
}
Future<void> _onApprouverDemandeAide(ApprouverDemandeAide event, Emitter<SolidarityState> emit) async {
emit(state.copyWith(status: SolidarityStatus.loading));
try {
final updated = await _repository.approuver(event.id);
emit(state.copyWith(status: SolidarityStatus.loaded, demandeDetail: updated));
add(const LoadDemandesAide());
} catch (e) {
emit(state.copyWith(status: SolidarityStatus.error, message: e.toString(), error: e));
}
}
Future<void> _onRejeterDemandeAide(RejeterDemandeAide event, Emitter<SolidarityState> emit) async {
emit(state.copyWith(status: SolidarityStatus.loading));
try {
final updated = await _repository.rejeter(event.id, motif: event.motif);
emit(state.copyWith(status: SolidarityStatus.loaded, demandeDetail: updated));
add(const LoadDemandesAide());
} catch (e) {
emit(state.copyWith(status: SolidarityStatus.error, message: e.toString(), error: e));
}
}
}

View File

@@ -0,0 +1,54 @@
part of 'solidarity_bloc.dart';
abstract class SolidarityEvent extends Equatable {
const SolidarityEvent();
@override
List<Object?> get props => [];
}
class LoadDemandesAide extends SolidarityEvent {
final int page;
final int size;
const LoadDemandesAide({this.page = 0, this.size = 20});
@override
List<Object?> get props => [page, size];
}
class LoadDemandeAideById extends SolidarityEvent {
final String id;
const LoadDemandeAideById(this.id);
@override
List<Object?> get props => [id];
}
class SearchDemandesAide extends SolidarityEvent {
final String? statut;
final String? type;
final int page;
final int size;
const SearchDemandesAide({this.statut, this.type, this.page = 0, this.size = 20});
@override
List<Object?> get props => [statut, type, page, size];
}
class CreateDemandeAide extends SolidarityEvent {
final DemandeAideModel demande;
const CreateDemandeAide(this.demande);
@override
List<Object?> get props => [demande];
}
class ApprouverDemandeAide extends SolidarityEvent {
final String id;
const ApprouverDemandeAide(this.id);
@override
List<Object?> get props => [id];
}
class RejeterDemandeAide extends SolidarityEvent {
final String id;
final String? motif;
const RejeterDemandeAide(this.id, {this.motif});
@override
List<Object?> get props => [id, motif];
}

View File

@@ -0,0 +1,38 @@
part of 'solidarity_bloc.dart';
enum SolidarityStatus { initial, loading, loaded, error }
class SolidarityState extends Equatable {
final SolidarityStatus status;
final List<DemandeAideModel> demandes;
final DemandeAideModel? demandeDetail;
final String? message;
final Object? error;
const SolidarityState({
this.status = SolidarityStatus.initial,
this.demandes = const [],
this.demandeDetail,
this.message,
this.error,
});
SolidarityState copyWith({
SolidarityStatus? status,
List<DemandeAideModel>? demandes,
DemandeAideModel? demandeDetail,
String? message,
Object? error,
}) {
return SolidarityState(
status: status ?? this.status,
demandes: demandes ?? this.demandes,
demandeDetail: demandeDetail ?? this.demandeDetail,
message: message ?? this.message,
error: error ?? this.error,
);
}
@override
List<Object?> get props => [status, demandes, demandeDetail, message, error];
}

View File

@@ -0,0 +1,96 @@
/// Modèle pour les demandes d'aide (solidarité)
/// Correspond à l'API /api/demandes-aide (DemandeAideDTO)
library demande_aide_model;
import 'package:equatable/equatable.dart';
import 'package:json_annotation/json_annotation.dart';
part 'demande_aide_model.g.dart';
@JsonSerializable(explicitToJson: true)
class DemandeAideModel extends Equatable {
final String? id;
final String? numeroReference;
final String? type;
final String? titre;
final String? description;
final String? justification;
final double? montantDemande;
final double? montantAccorde;
final String? statut;
final String? urgence;
final String? localisation;
final String? motif;
final String? demandeurId;
final String? demandeur;
final String? telephone;
final String? email;
final DateTime? dateDemande;
final DateTime? dateLimite;
final String? responsableTraitement;
final String? organisationId;
final DateTime? dateCreation;
const DemandeAideModel({
this.id,
this.numeroReference,
this.type,
this.titre,
this.description,
this.justification,
this.montantDemande,
this.montantAccorde,
this.statut,
this.urgence,
this.localisation,
this.motif,
this.demandeurId,
this.demandeur,
this.telephone,
this.email,
this.dateDemande,
this.dateLimite,
this.responsableTraitement,
this.organisationId,
this.dateCreation,
});
factory DemandeAideModel.fromJson(Map<String, dynamic> json) =>
_$DemandeAideModelFromJson(json);
Map<String, dynamic> toJson() => _$DemandeAideModelToJson(this);
String get statutLibelle {
switch (statut) {
case 'BROUILLON':
return 'Brouillon';
case 'SOUMISE':
return 'Soumise';
case 'EN_ATTENTE':
return 'En attente';
case 'APPROUVEE':
return 'Approuvée';
case 'REJETEE':
return 'Rejetée';
case 'EN_COURS_TRAITEMENT':
return 'En cours de traitement';
case 'TERMINEE':
return 'Terminée';
default:
return statut ?? '';
}
}
String get typeLibelle => type ?? '';
@override
List<Object?> get props => [
id,
numeroReference,
titre,
statut,
type,
dateDemande,
montantDemande,
organisationId,
];
}

View File

@@ -0,0 +1,63 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'demande_aide_model.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
DemandeAideModel _$DemandeAideModelFromJson(Map<String, dynamic> json) =>
DemandeAideModel(
id: json['id'] as String?,
numeroReference: json['numeroReference'] as String?,
type: json['type'] as String?,
titre: json['titre'] as String?,
description: json['description'] as String?,
justification: json['justification'] as String?,
montantDemande: (json['montantDemande'] as num?)?.toDouble(),
montantAccorde: (json['montantAccorde'] as num?)?.toDouble(),
statut: json['statut'] as String?,
urgence: json['urgence'] as String?,
localisation: json['localisation'] as String?,
motif: json['motif'] as String?,
demandeurId: json['demandeurId'] as String?,
demandeur: json['demandeur'] as String?,
telephone: json['telephone'] as String?,
email: json['email'] as String?,
dateDemande: json['dateDemande'] == null
? null
: DateTime.parse(json['dateDemande'] as String),
dateLimite: json['dateLimite'] == null
? null
: DateTime.parse(json['dateLimite'] as String),
responsableTraitement: json['responsableTraitement'] as String?,
organisationId: json['organisationId'] as String?,
dateCreation: json['dateCreation'] == null
? null
: DateTime.parse(json['dateCreation'] as String),
);
Map<String, dynamic> _$DemandeAideModelToJson(DemandeAideModel instance) =>
<String, dynamic>{
'id': instance.id,
'numeroReference': instance.numeroReference,
'type': instance.type,
'titre': instance.titre,
'description': instance.description,
'justification': instance.justification,
'montantDemande': instance.montantDemande,
'montantAccorde': instance.montantAccorde,
'statut': instance.statut,
'urgence': instance.urgence,
'localisation': instance.localisation,
'motif': instance.motif,
'demandeurId': instance.demandeurId,
'demandeur': instance.demandeur,
'telephone': instance.telephone,
'email': instance.email,
'dateDemande': instance.dateDemande?.toIso8601String(),
'dateLimite': instance.dateLimite?.toIso8601String(),
'responsableTraitement': instance.responsableTraitement,
'organisationId': instance.organisationId,
'dateCreation': instance.dateCreation?.toIso8601String(),
};

View File

@@ -0,0 +1,134 @@
/// Repository pour les demandes d'aide (solidarité)
/// Interface avec l'API /api/demandes-aide
/// Note: le backend doit exposer DemandeAideResource pour que les appels fonctionnent.
library demande_aide_repository;
import 'package:dio/dio.dart';
import 'package:injectable/injectable.dart';
import 'package:unionflow_mobile_apps/core/network/api_client.dart';
import '../models/demande_aide_model.dart';
abstract class DemandeAideRepository {
/// Demandes du membre connecté (GET /api/demandes-aide/mes)
Future<List<DemandeAideModel>> getMesDemandes({int page = 0, int size = 50});
Future<List<DemandeAideModel>> getAll({int page = 0, int size = 20});
Future<DemandeAideModel?> getById(String id);
Future<DemandeAideModel> create(DemandeAideModel demande);
Future<DemandeAideModel> update(String id, DemandeAideModel demande);
Future<DemandeAideModel> approuver(String id);
Future<DemandeAideModel> rejeter(String id, {String? motif});
Future<List<DemandeAideModel>> search({
String? statut,
String? type,
String? urgence,
int page = 0,
int size = 20,
});
}
@LazySingleton(as: DemandeAideRepository)
class DemandeAideRepositoryImpl implements DemandeAideRepository {
final ApiClient _apiClient;
static const String _base = '/api/demandes-aide';
DemandeAideRepositoryImpl(this._apiClient);
@override
Future<List<DemandeAideModel>> getMesDemandes({int page = 0, int size = 50}) async {
final response = await _apiClient.get(
'$_base/mes',
queryParameters: {'page': page, 'size': size},
);
if (response.statusCode == 200) {
final List<dynamic> data = response.data is List ? response.data : [];
return data.map((e) => DemandeAideModel.fromJson(e as Map<String, dynamic>)).toList();
}
throw Exception('Erreur ${response.statusCode}');
}
@override
Future<List<DemandeAideModel>> getAll({int page = 0, int size = 20}) async {
final response = await _apiClient.get(
_base,
queryParameters: {'page': page, 'size': size},
);
if (response.statusCode == 200) {
final List<dynamic> data = response.data is List ? response.data : (response.data as Map)['content'] as List? ?? [];
return data
.map((e) => DemandeAideModel.fromJson(e as Map<String, dynamic>))
.toList();
}
throw Exception('Erreur ${response.statusCode}');
}
@override
Future<DemandeAideModel?> getById(String id) async {
final response = await _apiClient.get('$_base/$id');
if (response.statusCode == 200) {
return DemandeAideModel.fromJson(response.data as Map<String, dynamic>);
}
if (response.statusCode == 404) return null;
throw Exception('Erreur ${response.statusCode}');
}
@override
Future<DemandeAideModel> create(DemandeAideModel demande) async {
final response = await _apiClient.post(_base, data: demande.toJson());
if (response.statusCode == 201 || response.statusCode == 200) {
return DemandeAideModel.fromJson(response.data as Map<String, dynamic>);
}
throw Exception('Erreur création: ${response.statusCode}');
}
@override
Future<DemandeAideModel> update(String id, DemandeAideModel demande) async {
final response = await _apiClient.put('$_base/$id', data: demande.toJson());
if (response.statusCode == 200) {
return DemandeAideModel.fromJson(response.data as Map<String, dynamic>);
}
throw Exception('Erreur mise à jour: ${response.statusCode}');
}
@override
Future<DemandeAideModel> approuver(String id) async {
final response = await _apiClient.put('$_base/$id/approuver');
if (response.statusCode == 200) {
return DemandeAideModel.fromJson(response.data as Map<String, dynamic>);
}
throw Exception('Erreur approbation: ${response.statusCode}');
}
@override
Future<DemandeAideModel> rejeter(String id, {String? motif}) async {
final response = await _apiClient.put(
'$_base/$id/rejeter',
data: motif != null && motif.isNotEmpty ? {'motif': motif} : null,
);
if (response.statusCode == 200) {
return DemandeAideModel.fromJson(response.data as Map<String, dynamic>);
}
throw Exception('Erreur rejet: ${response.statusCode}');
}
@override
Future<List<DemandeAideModel>> search({
String? statut,
String? type,
String? urgence,
int page = 0,
int size = 20,
}) async {
final q = <String, dynamic>{'page': page, 'size': size};
if (statut != null) q['statut'] = statut;
if (type != null) q['type'] = type;
if (urgence != null) q['urgence'] = urgence;
final response = await _apiClient.get('$_base/search', queryParameters: q);
if (response.statusCode == 200) {
final List<dynamic> data = response.data is List ? response.data : (response.data as Map)['content'] as List? ?? [];
return data
.map((e) => DemandeAideModel.fromJson(e as Map<String, dynamic>))
.toList();
}
throw Exception('Erreur ${response.statusCode}');
}
}

View File

@@ -0,0 +1,256 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:intl/intl.dart';
import '../../../../shared/design_system/unionflow_design_system.dart';
import '../../../../shared/widgets/core_card.dart';
import '../../../../shared/widgets/info_badge.dart';
import '../../../../shared/widgets/mini_avatar.dart';
import '../../bloc/solidarity_bloc.dart';
import '../../data/models/demande_aide_model.dart';
import '../../../authentication/presentation/bloc/auth_bloc.dart';
class DemandeAideDetailPage extends StatefulWidget {
final String demandeId;
const DemandeAideDetailPage({super.key, required this.demandeId});
@override
State<DemandeAideDetailPage> createState() => _DemandeAideDetailPageState();
}
class _DemandeAideDetailPageState extends State<DemandeAideDetailPage> {
final _currencyFormat = NumberFormat.currency(locale: 'fr_FR', symbol: 'FCFA');
@override
void initState() {
super.initState();
context.read<SolidarityBloc>().add(LoadDemandeAideById(widget.demandeId));
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: AppColors.background,
appBar: const UFAppBar(
title: 'DÉTAIL DEMANDE',
backgroundColor: AppColors.surface,
foregroundColor: AppColors.textPrimaryLight,
),
body: BlocConsumer<SolidarityBloc, SolidarityState>(
listenWhen: (prev, curr) => prev.status != curr.status,
listener: (context, state) {
if (state.status == SolidarityStatus.error && state.message != null) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(state.message!), backgroundColor: Colors.red),
);
}
},
buildWhen: (prev, curr) =>
prev.demandeDetail != curr.demandeDetail || prev.status != curr.status,
builder: (context, state) {
if (state.status == SolidarityStatus.loading && state.demandeDetail == null) {
return const Center(child: CircularProgressIndicator());
}
final d = state.demandeDetail;
if (d == null) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(Icons.error_outline, size: 64, color: Colors.grey),
const SizedBox(height: 16),
Text(
'Demande introuvable',
style: Theme.of(context).textTheme.titleMedium,
),
],
),
);
}
return SingleChildScrollView(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_InfoCard(title: 'Référence', value: d.numeroReference ?? d.id ?? ''),
_InfoCard(title: 'Statut', value: d.statutLibelle),
_InfoCard(title: 'Titre', value: d.titre ?? ''),
if (d.type != null) _InfoCard(title: 'Type', value: d.typeLibelle),
if (d.description != null && d.description!.isNotEmpty)
_InfoCard(title: 'Description', value: d.description!),
if (d.montantDemande != null && d.montantDemande! > 0)
_InfoCard(
title: 'Montant demandé',
value: _currencyFormat.format(d.montantDemande!),
),
if (d.montantAccorde != null && d.montantAccorde! > 0)
_InfoCard(
title: 'Montant accordé',
value: _currencyFormat.format(d.montantAccorde!),
),
if (d.demandeur != null) _InfoCard(title: 'Demandeur', value: d.demandeur!),
if (d.dateDemande != null)
_InfoCard(
title: 'Date demande',
value: DateFormat('dd/MM/yyyy').format(d.dateDemande!),
),
if (d.motif != null && d.motif!.isNotEmpty)
_InfoCard(title: 'Motif', value: d.motif!),
_ActionsSection(demande: d, isGestionnaire: _isGestionnaire()),
],
),
);
},
),
);
}
bool _isGestionnaire() {
final state = context.read<AuthBloc>().state;
if (state is AuthAuthenticated) {
return state.effectiveRole.level >= 50;
}
return false;
}
}
class _InfoCard extends StatelessWidget {
final String title;
final String value;
final Widget? trail;
const _InfoCard({required this.title, required this.value, this.trail});
@override
Widget build(BuildContext context) {
return CoreCard(
margin: const EdgeInsets.only(bottom: 8),
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
title.toUpperCase(),
style: AppTypography.subtitleSmall.copyWith(
fontWeight: FontWeight.bold,
fontSize: 9,
color: AppColors.textSecondaryLight,
),
),
const SizedBox(height: 2),
Text(
value,
style: AppTypography.bodyTextSmall.copyWith(fontSize: 12),
),
],
),
),
if (trail != null) trail!,
],
),
);
}
}
class _ActionsSection extends StatelessWidget {
final DemandeAideModel demande;
final bool isGestionnaire;
const _ActionsSection({required this.demande, required this.isGestionnaire});
@override
Widget build(BuildContext context) {
if (!isGestionnaire) return const SizedBox.shrink();
final bloc = context.read<SolidarityBloc>();
if (demande.statut != 'EN_ATTENTE' && demande.statut != 'SOUMISE') {
return const SizedBox.shrink();
}
if (demande.id == null) return const SizedBox.shrink();
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Padding(
padding: const EdgeInsets.symmetric(vertical: 8),
child: Text(
'ACTIONS ADMINISTRATIVES',
style: AppTypography.subtitleSmall.copyWith(
fontWeight: FontWeight.bold,
letterSpacing: 1.1,
),
),
),
const SizedBox(height: 8),
Row(
children: [
Expanded(
child: ElevatedButton(
onPressed: () => bloc.add(ApprouverDemandeAide(demande.id!)),
style: ElevatedButton.styleFrom(
backgroundColor: AppColors.success,
foregroundColor: Colors.white,
elevation: 0,
padding: const EdgeInsets.symmetric(vertical: 12),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(4)),
),
child: Text('APPROUVER', style: AppTypography.actionText.copyWith(fontSize: 11, color: Colors.white)),
),
),
const SizedBox(width: 12),
Expanded(
child: OutlinedButton(
onPressed: () => _showRejetDialog(context, demande.id!, bloc),
style: OutlinedButton.styleFrom(
foregroundColor: AppColors.error,
side: const BorderSide(color: AppColors.error),
padding: const EdgeInsets.symmetric(vertical: 12),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(4)),
),
child: Text('REJETER', style: AppTypography.actionText.copyWith(fontSize: 11)),
),
),
],
),
],
);
}
void _showRejetDialog(BuildContext context, String demandeId, SolidarityBloc bloc) {
final motifController = TextEditingController();
showDialog<void>(
context: context,
builder: (ctx) => AlertDialog(
title: const Text('Rejeter la demande'),
content: TextField(
controller: motifController,
decoration: const InputDecoration(
labelText: 'Motif du rejet (recommandé pour traçabilité)',
hintText: 'Saisir le motif...',
border: OutlineInputBorder(),
),
maxLines: 3,
autofocus: true,
),
actions: [
TextButton(
onPressed: () => Navigator.pop(ctx),
child: const Text('Annuler'),
),
FilledButton(
onPressed: () {
final motif = motifController.text.trim();
Navigator.pop(ctx);
bloc.add(RejeterDemandeAide(demandeId, motif: motif.isNotEmpty ? motif : null));
},
style: FilledButton.styleFrom(backgroundColor: AppColors.error),
child: const Text('Rejeter'),
),
],
),
);
}
}

View File

@@ -0,0 +1,257 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:intl/intl.dart';
import '../../../../shared/design_system/unionflow_design_system.dart';
import '../../../../shared/widgets/core_card.dart';
import '../../../../shared/widgets/info_badge.dart';
import '../../../../shared/widgets/mini_avatar.dart';
import '../../bloc/solidarity_bloc.dart';
import '../../data/models/demande_aide_model.dart';
import 'demande_aide_detail_page.dart';
import '../widgets/create_demande_aide_dialog.dart';
import '../../../authentication/presentation/bloc/auth_bloc.dart';
/// Page liste des demandes d'aide (solidarité) - Version Épurée
class DemandesAidePage extends StatefulWidget {
const DemandesAidePage({super.key});
@override
State<DemandesAidePage> createState() => _DemandesAidePageState();
}
class _DemandesAidePageState extends State<DemandesAidePage>
with SingleTickerProviderStateMixin {
late TabController _tabController;
final _currencyFormat = NumberFormat.currency(locale: 'fr_FR', symbol: 'FCFA', decimalDigits: 0);
@override
void initState() {
super.initState();
_tabController = TabController(length: 3, vsync: this);
_loadTab(0);
}
@override
void dispose() {
_tabController.dispose();
super.dispose();
}
void _loadTab(int index) {
bool isGestionnaire = false;
final authState = context.read<AuthBloc>().state;
if (authState is AuthAuthenticated) {
isGestionnaire = authState.effectiveRole.level >= 50;
}
if (isGestionnaire) {
switch (index) {
case 0:
context.read<SolidarityBloc>().add(const SearchDemandesAide()); // Search sans statut = getAll
break;
case 1:
context.read<SolidarityBloc>().add(const SearchDemandesAide(statut: 'EN_ATTENTE'));
break;
case 2:
context.read<SolidarityBloc>().add(const SearchDemandesAide(statut: 'APPROUVEE'));
break;
}
} else {
// Normal member always fetches their own requests
context.read<SolidarityBloc>().add(const LoadDemandesAide());
}
}
@override
Widget build(BuildContext context) {
return BlocListener<SolidarityBloc, SolidarityState>(
listener: (context, state) {
if (state.status == SolidarityStatus.error && state.message != null) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(state.message!,
style: AppTypography.bodyTextSmall.copyWith(color: Colors.white)),
backgroundColor: AppColors.error,
),
);
}
},
child: Scaffold(
backgroundColor: AppColors.background,
appBar: UFAppBar(
title: 'SOLIDARITÉ',
backgroundColor: AppColors.surface,
foregroundColor: AppColors.textPrimaryLight,
bottom: TabBar(
controller: _tabController,
onTap: _loadTab,
labelColor: AppColors.primaryGreen,
unselectedLabelColor: AppColors.textSecondaryLight,
indicatorColor: AppColors.primaryGreen,
indicatorSize: TabBarIndicatorSize.label,
labelStyle: AppTypography.actionText.copyWith(fontSize: 10, fontWeight: FontWeight.bold),
tabs: const [
Tab(child: Text('TOUTES')),
Tab(child: Text('ATTENTE')),
Tab(child: Text('APPROUVÉES')),
],
),
),
body: TabBarView(
controller: _tabController,
children: [
_buildList(null),
_buildList('EN_ATTENTE'),
_buildList('APPROUVEE'),
],
),
),
);
}
Widget _buildList(String? statutFilter) {
return BlocBuilder<SolidarityBloc, SolidarityState>(
buildWhen: (prev, curr) =>
prev.status != curr.status || prev.demandes != curr.demandes,
builder: (context, state) {
if (state.status == SolidarityStatus.loading && state.demandes.isEmpty) {
return const Center(child: CircularProgressIndicator(strokeWidth: 2));
}
var list = state.demandes;
if (statutFilter != null) {
list = list.where((d) => d.statut == statutFilter).toList();
}
if (list.isEmpty) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(Icons.volunteer_activism_outlined, size: 32, color: AppColors.lightBorder),
const SizedBox(height: 12),
Text('Aucune demande', style: AppTypography.subtitleSmall),
],
),
);
}
return RefreshIndicator(
onRefresh: () async => _loadTab(_tabController.index),
child: ListView.builder(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
itemCount: list.length,
itemBuilder: (context, index) {
return _DemandeCard(
demande: list[index],
currencyFormat: _currencyFormat,
onTap: () => _openDetail(list[index]),
);
},
),
);
},
);
}
void _openDetail(DemandeAideModel d) {
if (d.id == null) return;
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => BlocProvider.value(
value: context.read<SolidarityBloc>(),
child: DemandeAideDetailPage(demandeId: d.id!),
),
),
).then((_) => _loadTab(_tabController.index));
}
}
class _DemandeCard extends StatelessWidget {
final DemandeAideModel demande;
final NumberFormat currencyFormat;
final VoidCallback onTap;
const _DemandeCard({
required this.demande,
required this.currencyFormat,
required this.onTap,
});
@override
Widget build(BuildContext context) {
return CoreCard(
margin: const EdgeInsets.only(bottom: 10),
onTap: onTap,
padding: const EdgeInsets.all(12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
const MiniAvatar(size: 24, fallbackText: '?'),
const SizedBox(width: 10),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
demande.titre ?? 'Demande sans titre',
style: AppTypography.actionText.copyWith(fontSize: 12),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
Text(
demande.numeroReference ?? demande.id?.substring(0, 8) ?? '',
style: AppTypography.subtitleSmall.copyWith(fontSize: 9),
),
],
),
),
_buildStatutBadge(demande.statut),
],
),
const SizedBox(height: 12),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('MONTANT DEMANDÉ', style: AppTypography.subtitleSmall.copyWith(fontSize: 8, fontWeight: FontWeight.bold)),
Text(
currencyFormat.format(demande.montantDemande ?? 0),
style: AppTypography.headerSmall.copyWith(fontSize: 13, color: AppColors.primaryGreen),
),
],
),
Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Text('TYPE', style: AppTypography.subtitleSmall.copyWith(fontSize: 8, fontWeight: FontWeight.bold)),
Text(demande.typeLibelle, style: AppTypography.bodyTextSmall.copyWith(fontSize: 10)),
],
),
],
),
],
),
);
}
Widget _buildStatutBadge(String? statut) {
Color color;
switch (statut) {
case 'APPROUVEE':
color = AppColors.success;
break;
case 'REJETEE':
color = AppColors.error;
break;
case 'EN_ATTENTE':
case 'SOUMISE':
color = AppColors.brandGreenLight;
break;
default:
color = AppColors.textSecondaryLight;
}
return InfoBadge(text: statut ?? 'INCONNU', backgroundColor: color);
}
}

View File

@@ -0,0 +1,26 @@
/// Wrapper BLoC pour la page des demandes d'aide
library demandes_aide_page_wrapper;
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:get_it/get_it.dart';
import '../../bloc/solidarity_bloc.dart';
import 'demandes_aide_page.dart';
final _getIt = GetIt.instance;
class DemandesAidePageWrapper extends StatelessWidget {
const DemandesAidePageWrapper({super.key});
@override
Widget build(BuildContext context) {
return BlocProvider<SolidarityBloc>(
create: (context) {
final bloc = _getIt<SolidarityBloc>();
bloc.add(const LoadDemandesAide());
return bloc;
},
child: const DemandesAidePage(),
);
}
}

View File

@@ -0,0 +1,244 @@
/// Dialog de création d'une demande d'aide
library create_demande_aide_dialog;
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:get_it/get_it.dart';
import '../../../../core/utils/logger.dart';
import '../../bloc/solidarity_bloc.dart';
import '../../data/models/demande_aide_model.dart';
import '../../../organizations/domain/repositories/organization_repository.dart';
import '../../../organizations/data/models/organization_model.dart';
import '../../../members/data/models/membre_complete_model.dart';
import '../../../profile/domain/repositories/profile_repository.dart';
class CreateDemandeAideDialog extends StatefulWidget {
final VoidCallback onCreated;
const CreateDemandeAideDialog({super.key, required this.onCreated});
@override
State<CreateDemandeAideDialog> createState() => _CreateDemandeAideDialogState();
}
class _CreateDemandeAideDialogState extends State<CreateDemandeAideDialog> {
final _formKey = GlobalKey<FormState>();
final _titreController = TextEditingController();
final _descriptionController = TextEditingController();
final _justificationController = TextEditingController();
final _montantController = TextEditingController();
String? _organisationId;
String? _type;
List<OrganizationModel> _organisations = [];
bool _loading = false;
bool _isInitLoading = true;
MembreCompletModel? _me;
static const List<Map<String, String>> _types = [
{'value': 'FINANCIERE', 'label': 'Financière'},
{'value': 'MATERIELLE', 'label': 'Matérielle'},
{'value': 'ALIMENTAIRE', 'label': 'Alimentaire'},
{'value': 'MEDICALE', 'label': 'Médicale'},
{'value': 'SCOLAIRE', 'label': 'Scolaire'},
{'value': 'LOGEMENT', 'label': 'Logement'},
{'value': 'AUTRE', 'label': 'Autre'},
];
@override
void initState() {
super.initState();
_loadInitialData();
}
Future<void> _loadInitialData() async {
try {
final user = await GetIt.instance<IProfileRepository>().getMe();
final orgRepo = GetIt.instance<IOrganizationRepository>();
final list = await orgRepo.getOrganizations(page: 0, size: 100);
if (mounted) {
setState(() {
_me = user;
_organisations = list;
_isInitLoading = false;
});
}
} catch (e, st) {
AppLogger.error('CreateDemandeAideDialog: chargement données initiales échoué', error: e, stackTrace: st);
if (mounted) {
setState(() {
_isInitLoading = false;
});
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Impossible de charger le profil ou les organisations. Réessayez.')),
);
}
}
}
@override
void dispose() {
_titreController.dispose();
_descriptionController.dispose();
_justificationController.dispose();
_montantController.dispose();
super.dispose();
}
void _submit() {
if (_me == null) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Profil non chargé, veuillez réessayer')),
);
return;
}
if (!_formKey.currentState!.validate()) return;
final titre = _titreController.text.trim();
final description = _descriptionController.text.trim();
if (titre.isEmpty || description.isEmpty) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Titre et description obligatoires')),
);
return;
}
final montant = double.tryParse(_montantController.text.replaceAll(',', '.'));
setState(() => _loading = true);
final demande = DemandeAideModel(
titre: titre,
description: description,
justification: _justificationController.text.trim().isEmpty
? null
: _justificationController.text.trim(),
type: _type,
montantDemande: montant,
organisationId: _organisationId,
demandeurId: _me!.id,
dateDemande: DateTime.now(),
statut: 'BROUILLON',
);
context.read<SolidarityBloc>().add(CreateDemandeAide(demande));
widget.onCreated();
if (mounted) {
setState(() => _loading = false);
Navigator.of(context).pop();
}
}
@override
Widget build(BuildContext context) {
return AlertDialog(
title: const Text('Nouvelle demande d\'aide'),
content: SingleChildScrollView(
child: Form(
key: _formKey,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
if (_isInitLoading)
const CircularProgressIndicator()
else if (_me != null)
TextFormField(
initialValue: '${_me!.prenom} ${_me!.nom}',
decoration: const InputDecoration(
labelText: 'Demandeur',
border: OutlineInputBorder(),
prefixIcon: Icon(Icons.person),
),
enabled: false,
)
else
const Text('Impossible de récupérer votre profil', style: TextStyle(color: Colors.red)),
const SizedBox(height: 12),
TextFormField(
controller: _titreController,
decoration: const InputDecoration(
labelText: 'Titre *',
border: OutlineInputBorder(),
),
validator: (v) => (v == null || v.trim().isEmpty) ? 'Obligatoire' : null,
enabled: !_loading,
),
const SizedBox(height: 12),
TextFormField(
controller: _descriptionController,
decoration: const InputDecoration(
labelText: 'Description *',
border: OutlineInputBorder(),
),
maxLines: 3,
validator: (v) => (v == null || v.trim().isEmpty) ? 'Obligatoire' : null,
enabled: !_loading,
),
const SizedBox(height: 12),
DropdownButtonFormField<String>(
value: _type,
decoration: const InputDecoration(
labelText: 'Type d\'aide',
border: OutlineInputBorder(),
),
items: _types
.map((e) => DropdownMenuItem(
value: e['value'],
child: Text(e['label']!),
))
.toList(),
onChanged: _loading ? null : (v) => setState(() => _type = v),
),
const SizedBox(height: 12),
TextFormField(
controller: _montantController,
decoration: const InputDecoration(
labelText: 'Montant demandé (FCFA, optionnel)',
border: OutlineInputBorder(),
),
keyboardType: const TextInputType.numberWithOptions(decimal: true),
enabled: !_loading,
),
const SizedBox(height: 12),
TextFormField(
controller: _justificationController,
decoration: const InputDecoration(
labelText: 'Justification',
border: OutlineInputBorder(),
),
maxLines: 2,
enabled: !_loading,
),
const SizedBox(height: 12),
DropdownButtonFormField<String>(
value: _organisationId,
isExpanded: true,
decoration: const InputDecoration(
labelText: 'Organisation',
border: OutlineInputBorder(),
),
items: _organisations
.map((o) => DropdownMenuItem(
value: o.id,
child: Text(o.nom, overflow: TextOverflow.ellipsis, maxLines: 1),
))
.toList(),
onChanged: _loading ? null : (v) => setState(() => _organisationId = v),
),
],
),
),
),
actions: [
TextButton(
onPressed: _loading ? null : () => Navigator.of(context).pop(),
child: const Text('Annuler'),
),
FilledButton(
onPressed: _loading ? null : _submit,
child: _loading
? const SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(strokeWidth: 2),
)
: const Text('Créer'),
),
],
);
}
}