release: squash merge develop → master
Quotidien / Epic C : feed bulles parent (#173), module Cartes (#194/#195), evenements_agenda (#205), couples garde AM (#169–#171), API absences (#172). Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -0,0 +1,94 @@
|
||||
import 'dart:convert';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:p_tits_pas/models/absence_garde.dart';
|
||||
import 'package:p_tits_pas/services/api/api_config.dart';
|
||||
import 'package:p_tits_pas/services/api/tokenService.dart';
|
||||
|
||||
class AbsencesGardeService {
|
||||
static Future<List<AbsenceGarde>> getAbsences({String? placementId}) async {
|
||||
final token = await TokenService.getToken();
|
||||
final headers = token != null ? ApiConfig.authHeaders(token) : ApiConfig.headers;
|
||||
|
||||
final uri = Uri.parse(ApiConfig.baseUrl +
|
||||
'/evenements-agenda' +
|
||||
(placementId != null ? '?placementId=$placementId' : ''));
|
||||
|
||||
final res = await http.get(uri, headers: headers);
|
||||
if (res.statusCode == 200) {
|
||||
final json = jsonDecode(res.body);
|
||||
final List items = json['items'] ?? [];
|
||||
return items.map((e) => AbsenceGarde.fromJson(e)).toList();
|
||||
} else {
|
||||
throw Exception('Erreur de chargement des absences : ${res.statusCode}');
|
||||
}
|
||||
}
|
||||
|
||||
static Future<AbsenceGarde> creerAbsence({
|
||||
required String idPlacement,
|
||||
required String type,
|
||||
required String dateDebut,
|
||||
required String dateFin,
|
||||
String? motif,
|
||||
}) async {
|
||||
final token = await TokenService.getToken();
|
||||
final headers = token != null ? ApiConfig.authHeaders(token) : ApiConfig.headers;
|
||||
|
||||
final uri = Uri.parse('${ApiConfig.baseUrl}/evenements-agenda');
|
||||
final res = await http.post(
|
||||
uri,
|
||||
headers: headers,
|
||||
body: jsonEncode({
|
||||
'id_placement': idPlacement,
|
||||
'type': type,
|
||||
'date_debut': dateDebut,
|
||||
'date_fin': dateFin,
|
||||
if (motif != null) 'motif': motif,
|
||||
}),
|
||||
);
|
||||
if (res.statusCode == 201) {
|
||||
return AbsenceGarde.fromJson(jsonDecode(res.body));
|
||||
} else {
|
||||
throw Exception("Erreur de création d'absence : ${res.statusCode}");
|
||||
}
|
||||
}
|
||||
|
||||
static Future<AbsenceGarde> modifierAbsence(
|
||||
String id, {
|
||||
String? dateDebut,
|
||||
String? dateFin,
|
||||
String? statut,
|
||||
String? motif,
|
||||
}) async {
|
||||
final token = await TokenService.getToken();
|
||||
final headers = token != null ? ApiConfig.authHeaders(token) : ApiConfig.headers;
|
||||
|
||||
final uri = Uri.parse('${ApiConfig.baseUrl}/evenements-agenda/$id');
|
||||
final Map<String, dynamic> body = {};
|
||||
if (dateDebut != null) body['date_debut'] = dateDebut;
|
||||
if (dateFin != null) body['date_fin'] = dateFin;
|
||||
if (statut != null) body['statut'] = statut;
|
||||
if (motif != null) body['motif'] = motif;
|
||||
|
||||
final res = await http.patch(
|
||||
uri,
|
||||
headers: headers,
|
||||
body: jsonEncode(body),
|
||||
);
|
||||
if (res.statusCode == 200) {
|
||||
return AbsenceGarde.fromJson(jsonDecode(res.body));
|
||||
} else {
|
||||
throw Exception("Erreur de modification d'absence : ${res.statusCode}");
|
||||
}
|
||||
}
|
||||
|
||||
static Future<void> supprimerAbsence(String id) async {
|
||||
final token = await TokenService.getToken();
|
||||
final headers = token != null ? ApiConfig.authHeaders(token) : ApiConfig.headers;
|
||||
|
||||
final uri = Uri.parse('${ApiConfig.baseUrl}/evenements-agenda/$id');
|
||||
final res = await http.delete(uri, headers: headers);
|
||||
if (res.statusCode != 204) {
|
||||
throw Exception("Erreur de suppression d'absence : ${res.statusCode}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -67,7 +67,11 @@ class ApiConfig {
|
||||
static const String parentsCoupleGardeCourant =
|
||||
'/parents/me/couples-garde/courant';
|
||||
static const String assistantesMaternelles = '/assistantes-maternelles';
|
||||
/// Création dossier AM actif par le staff (#156) — body type register AM.
|
||||
/// Couples de garde de l'AM connectée (#170 / #171).
|
||||
static const String assistantesMaternellesCouplesGarde =
|
||||
'/assistantes-maternelles/me/couples-garde';
|
||||
static const String assistantesMaternellesCoupleGardeCourant =
|
||||
'/assistantes-maternelles/me/couples-garde/courant';
|
||||
static const String assistantesMaternellesDossier =
|
||||
'/assistantes-maternelles/dossier';
|
||||
static const String enfants = '/enfants';
|
||||
@@ -89,6 +93,10 @@ class ApiConfig {
|
||||
static const String conversations = '/conversations';
|
||||
static const String notifications = '/notifications';
|
||||
|
||||
/// File d'attention / bulles (#173 / #194).
|
||||
static const String cards = '/cards';
|
||||
static const String cardsStream = '/cards/stream';
|
||||
|
||||
// Headers
|
||||
static Map<String, String> get headers => {
|
||||
'Content-Type': 'application/json',
|
||||
@@ -96,7 +104,8 @@ class ApiConfig {
|
||||
};
|
||||
|
||||
static Map<String, String> authHeaders(String token) => {
|
||||
...headers,
|
||||
'Content-Type': 'application/json',
|
||||
'Accept': 'application/json',
|
||||
'Authorization': 'Bearer $token',
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:p_tits_pas/models/carte_bulle.dart';
|
||||
import 'package:p_tits_pas/services/api/api_config.dart';
|
||||
import 'package:p_tits_pas/services/api/tokenService.dart';
|
||||
|
||||
/// Accès API Cartes (file d'attention) — tickets #173 / #194.
|
||||
/// - GET /cards?placementId=
|
||||
/// - POST /cards/:id/respond
|
||||
class CardsService {
|
||||
static Future<Map<String, String>> _headers() async {
|
||||
final token = await TokenService.getToken();
|
||||
return token != null
|
||||
? ApiConfig.authHeaders(token)
|
||||
: Map<String, String>.from(ApiConfig.headers);
|
||||
}
|
||||
|
||||
static String _extractError(String body, String fallback) {
|
||||
try {
|
||||
final decoded = jsonDecode(body);
|
||||
if (decoded is Map<String, dynamic>) {
|
||||
final message = decoded['message'];
|
||||
if (message is String && message.trim().isNotEmpty) {
|
||||
return message;
|
||||
}
|
||||
if (message is Map && message['message'] is String) {
|
||||
return message['message'] as String;
|
||||
}
|
||||
}
|
||||
} catch (_) {}
|
||||
return fallback;
|
||||
}
|
||||
|
||||
/// Feed de bulles pour l'utilisateur (filtré par couple / placement).
|
||||
static Future<List<CarteBulle>> lister({String? placementId}) async {
|
||||
final query = <String, String>{};
|
||||
if (placementId != null && placementId.isNotEmpty) {
|
||||
query['placementId'] = placementId;
|
||||
}
|
||||
final uri = Uri.parse(
|
||||
'${ApiConfig.baseUrl}${ApiConfig.cards}',
|
||||
).replace(queryParameters: query.isEmpty ? null : query);
|
||||
|
||||
final response = await http.get(uri, headers: await _headers());
|
||||
if (response.statusCode != 200) {
|
||||
throw Exception(
|
||||
_extractError(response.body, 'Erreur chargement des cartes'),
|
||||
);
|
||||
}
|
||||
|
||||
final decoded = jsonDecode(response.body);
|
||||
final list = (decoded is Map ? decoded['items'] as List? : null) ?? const [];
|
||||
return list
|
||||
.whereType<Map>()
|
||||
.map((e) => CarteBulle.fromJson(Map<String, dynamic>.from(e)))
|
||||
.toList();
|
||||
}
|
||||
|
||||
/// Répondre : accept | refuse | ack.
|
||||
static Future<CarteBulle> repondre({
|
||||
required String cardId,
|
||||
required String action,
|
||||
String? comment,
|
||||
}) async {
|
||||
final response = await http.post(
|
||||
Uri.parse(
|
||||
'${ApiConfig.baseUrl}${ApiConfig.cards}/$cardId/respond',
|
||||
),
|
||||
headers: await _headers(),
|
||||
body: jsonEncode({
|
||||
'action': action,
|
||||
if (comment != null && comment.trim().isNotEmpty)
|
||||
'comment': comment.trim(),
|
||||
}),
|
||||
);
|
||||
|
||||
if (response.statusCode != 200) {
|
||||
throw Exception(
|
||||
_extractError(response.body, 'Erreur lors de la réponse'),
|
||||
);
|
||||
}
|
||||
|
||||
final decoded = jsonDecode(response.body);
|
||||
return CarteBulle.fromJson(Map<String, dynamic>.from(decoded as Map));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:p_tits_pas/models/carte_bulle.dart';
|
||||
import 'package:p_tits_pas/services/api/api_config.dart';
|
||||
import 'package:p_tits_pas/services/api/tokenService.dart';
|
||||
|
||||
import 'cards_stream_connector_stub.dart'
|
||||
if (dart.library.html) 'cards_stream_connector_web.dart'
|
||||
if (dart.library.io) 'cards_stream_connector_io.dart';
|
||||
|
||||
/// Événement temps réel file d'attention — ticket #195.
|
||||
class CardsStreamEvent {
|
||||
final String type;
|
||||
final String? cardId;
|
||||
final CarteBulle? card;
|
||||
|
||||
const CardsStreamEvent({
|
||||
required this.type,
|
||||
this.cardId,
|
||||
this.card,
|
||||
});
|
||||
}
|
||||
|
||||
/// Client SSE `GET /cards/stream` avec reconnexion.
|
||||
class CardsStreamClient {
|
||||
final void Function(CardsStreamEvent event) onEvent;
|
||||
final VoidCallback? onReconnectSync;
|
||||
|
||||
CardsStreamClient({
|
||||
required this.onEvent,
|
||||
this.onReconnectSync,
|
||||
});
|
||||
|
||||
final CardsStreamConnector _connector = CardsStreamConnector();
|
||||
bool _started = false;
|
||||
bool _stopRequested = false;
|
||||
int _attempt = 0;
|
||||
Timer? _retryTimer;
|
||||
bool _hadConnection = false;
|
||||
|
||||
void start() {
|
||||
if (_started) return;
|
||||
_started = true;
|
||||
_stopRequested = false;
|
||||
_attempt = 0;
|
||||
unawaited(_connect());
|
||||
}
|
||||
|
||||
void stop() {
|
||||
_stopRequested = true;
|
||||
_started = false;
|
||||
_retryTimer?.cancel();
|
||||
_retryTimer = null;
|
||||
_connector.close();
|
||||
}
|
||||
|
||||
Future<void> _connect() async {
|
||||
if (_stopRequested) return;
|
||||
|
||||
final token = await TokenService.getToken();
|
||||
if (token == null || token.isEmpty) {
|
||||
_scheduleRetry();
|
||||
return;
|
||||
}
|
||||
|
||||
final base =
|
||||
'${ApiConfig.baseUrl}${ApiConfig.cardsStream}'.replaceAll(
|
||||
RegExp(r'/+$'),
|
||||
'',
|
||||
);
|
||||
|
||||
// Web (EventSource) : token en query. IO : Bearer dans le connecteur.
|
||||
final url = kIsWeb
|
||||
? Uri.parse(base).replace(
|
||||
queryParameters: {'access_token': token},
|
||||
).toString()
|
||||
: base;
|
||||
|
||||
await _connector.connect(
|
||||
url: url,
|
||||
bearerToken: kIsWeb ? null : token,
|
||||
onEvent: _handleRaw,
|
||||
onError: (_) {
|
||||
if (_stopRequested) return;
|
||||
_connector.close();
|
||||
_scheduleRetry();
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
void _handleRaw(String eventType, String data) {
|
||||
if (_stopRequested) return;
|
||||
|
||||
// Premier événement (souvent heartbeat) = connexion OK.
|
||||
if (!_hadConnection) {
|
||||
_hadConnection = true;
|
||||
_attempt = 0;
|
||||
} else if (eventType == 'heartbeat') {
|
||||
_attempt = 0;
|
||||
return;
|
||||
}
|
||||
|
||||
if (eventType == 'heartbeat') return;
|
||||
|
||||
try {
|
||||
final decoded = jsonDecode(data);
|
||||
if (decoded is! Map) return;
|
||||
final map = Map<String, dynamic>.from(decoded);
|
||||
final type = (map['event']?.toString().isNotEmpty == true)
|
||||
? map['event'].toString()
|
||||
: eventType;
|
||||
final cardId = map['card_id']?.toString();
|
||||
final payload = map['data'];
|
||||
|
||||
CarteBulle? card;
|
||||
if (type == 'response.added' && payload is Map) {
|
||||
final nested = payload['card'];
|
||||
if (nested is Map) {
|
||||
card = CarteBulle.fromJson(Map<String, dynamic>.from(nested));
|
||||
}
|
||||
} else if ((type == 'card.created' || type == 'card.updated') &&
|
||||
payload is Map) {
|
||||
card = CarteBulle.fromJson(Map<String, dynamic>.from(payload));
|
||||
}
|
||||
|
||||
onEvent(
|
||||
CardsStreamEvent(
|
||||
type: type,
|
||||
cardId: cardId ?? card?.id,
|
||||
card: card,
|
||||
),
|
||||
);
|
||||
} catch (_) {
|
||||
// Événement mal formé : ignorer.
|
||||
}
|
||||
}
|
||||
|
||||
void _scheduleRetry() {
|
||||
if (_stopRequested) return;
|
||||
_retryTimer?.cancel();
|
||||
final delaySec = (1 << _attempt.clamp(0, 4)).clamp(1, 30);
|
||||
_attempt++;
|
||||
_retryTimer = Timer(Duration(seconds: delaySec), () {
|
||||
if (_stopRequested) return;
|
||||
if (_hadConnection) {
|
||||
// Resync REST après coupure pour ne pas manquer d'événements.
|
||||
onReconnectSync?.call();
|
||||
}
|
||||
unawaited(_connect());
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:http/http.dart' as http;
|
||||
|
||||
/// Connecteur SSE via HTTP stream (IO / mobile) — ticket #195.
|
||||
class CardsStreamConnector {
|
||||
http.Client? _client;
|
||||
StreamSubscription<List<int>>? _sub;
|
||||
bool _closed = false;
|
||||
|
||||
Future<void> connect({
|
||||
required String url,
|
||||
String? bearerToken,
|
||||
required void Function(String eventType, String data) onEvent,
|
||||
required void Function(Object error) onError,
|
||||
}) async {
|
||||
close();
|
||||
_closed = false;
|
||||
final client = http.Client();
|
||||
_client = client;
|
||||
|
||||
try {
|
||||
final request = http.Request('GET', Uri.parse(url));
|
||||
request.headers['Accept'] = 'text/event-stream';
|
||||
request.headers['Cache-Control'] = 'no-cache';
|
||||
if (bearerToken != null && bearerToken.isNotEmpty) {
|
||||
request.headers['Authorization'] = 'Bearer $bearerToken';
|
||||
}
|
||||
|
||||
final response = await client.send(request);
|
||||
if (response.statusCode != 200) {
|
||||
onError(
|
||||
StateError('SSE cards HTTP ${response.statusCode}'),
|
||||
);
|
||||
close();
|
||||
return;
|
||||
}
|
||||
|
||||
String? eventType;
|
||||
final dataBuf = StringBuffer();
|
||||
final lineBuf = StringBuffer();
|
||||
|
||||
void flushEvent() {
|
||||
if (dataBuf.isEmpty) {
|
||||
eventType = null;
|
||||
return;
|
||||
}
|
||||
onEvent(eventType ?? 'message', dataBuf.toString());
|
||||
dataBuf.clear();
|
||||
eventType = null;
|
||||
}
|
||||
|
||||
void handleLine(String line) {
|
||||
if (line.isEmpty) {
|
||||
flushEvent();
|
||||
return;
|
||||
}
|
||||
if (line.startsWith(':')) return;
|
||||
if (line.startsWith('event:')) {
|
||||
eventType = line.substring(6).trim();
|
||||
return;
|
||||
}
|
||||
if (line.startsWith('data:')) {
|
||||
final payload = line.length > 5 ? line.substring(5) : '';
|
||||
final trimmed = payload.startsWith(' ')
|
||||
? payload.substring(1)
|
||||
: payload;
|
||||
if (dataBuf.isNotEmpty) dataBuf.write('\n');
|
||||
dataBuf.write(trimmed);
|
||||
}
|
||||
}
|
||||
|
||||
_sub = response.stream.listen(
|
||||
(chunk) {
|
||||
if (_closed) return;
|
||||
lineBuf.write(utf8.decode(chunk, allowMalformed: true));
|
||||
var content = lineBuf.toString();
|
||||
var idx = content.indexOf('\n');
|
||||
while (idx >= 0) {
|
||||
var line = content.substring(0, idx);
|
||||
if (line.endsWith('\r')) {
|
||||
line = line.substring(0, line.length - 1);
|
||||
}
|
||||
handleLine(line);
|
||||
content = content.substring(idx + 1);
|
||||
idx = content.indexOf('\n');
|
||||
}
|
||||
lineBuf
|
||||
..clear()
|
||||
..write(content);
|
||||
},
|
||||
onError: (Object e) {
|
||||
if (!_closed) onError(e);
|
||||
},
|
||||
onDone: () {
|
||||
if (!_closed) onError(StateError('SSE cards fermé'));
|
||||
},
|
||||
cancelOnError: true,
|
||||
);
|
||||
} catch (e) {
|
||||
if (!_closed) onError(e);
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
void close() {
|
||||
_closed = true;
|
||||
_sub?.cancel();
|
||||
_sub = null;
|
||||
_client?.close();
|
||||
_client = null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import 'dart:async';
|
||||
|
||||
/// Connecteur SSE — stub (tests / plateformes sans impl).
|
||||
class CardsStreamConnector {
|
||||
Future<void> connect({
|
||||
required String url,
|
||||
String? bearerToken,
|
||||
required void Function(String eventType, String data) onEvent,
|
||||
required void Function(Object error) onError,
|
||||
}) async {}
|
||||
|
||||
void close() {}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
// Connecteur web uniquement (import conditionnel).
|
||||
// ignore_for_file: avoid_web_libraries_in_flutter, deprecated_member_use
|
||||
|
||||
import 'dart:html' as html;
|
||||
|
||||
/// Connecteur SSE navigateur (EventSource) — ticket #195.
|
||||
/// Auth via `?access_token=` (EventSource ne permet pas Authorization).
|
||||
class CardsStreamConnector {
|
||||
html.EventSource? _source;
|
||||
final Map<String, html.EventListener> _listeners = {};
|
||||
|
||||
Future<void> connect({
|
||||
required String url,
|
||||
String? bearerToken,
|
||||
required void Function(String eventType, String data) onEvent,
|
||||
required void Function(Object error) onError,
|
||||
}) async {
|
||||
close();
|
||||
final source = html.EventSource(url);
|
||||
_source = source;
|
||||
|
||||
const names = [
|
||||
'card.created',
|
||||
'card.updated',
|
||||
'card.deleted',
|
||||
'response.added',
|
||||
'heartbeat',
|
||||
];
|
||||
for (final name in names) {
|
||||
void listener(html.Event raw) {
|
||||
final msg = raw as html.MessageEvent;
|
||||
final data = msg.data?.toString() ?? '';
|
||||
if (data.isEmpty) return;
|
||||
onEvent(name, data);
|
||||
}
|
||||
|
||||
_listeners[name] = listener;
|
||||
source.addEventListener(name, listener);
|
||||
}
|
||||
|
||||
void onErr(html.Event _) {
|
||||
onError(StateError('SSE cards déconnecté'));
|
||||
}
|
||||
|
||||
_listeners['error'] = onErr;
|
||||
source.addEventListener('error', onErr);
|
||||
}
|
||||
|
||||
void close() {
|
||||
final source = _source;
|
||||
if (source != null) {
|
||||
_listeners.forEach((name, listener) {
|
||||
source.removeEventListener(name, listener);
|
||||
});
|
||||
source.close();
|
||||
}
|
||||
_listeners.clear();
|
||||
_source = null;
|
||||
}
|
||||
}
|
||||
@@ -383,6 +383,13 @@ class AuthService {
|
||||
}
|
||||
|
||||
/// Récupère l'utilisateur connecté depuis le cache
|
||||
static const String tokenKey = 'auth_token';
|
||||
|
||||
static Future<String?> getToken() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
return prefs.getString(tokenKey);
|
||||
}
|
||||
|
||||
static Future<AppUser?> getCurrentUser() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final userJson = prefs.getString(_currentUserKey);
|
||||
|
||||
@@ -73,4 +73,45 @@ class CoupleGardeService {
|
||||
Map<String, dynamic>.from(decoded as Map),
|
||||
);
|
||||
}
|
||||
|
||||
/// Liste les couples de garde et le couple courant de l'AM connectée.
|
||||
static Future<CouplesGardeResponse> getAmCouplesGarde() async {
|
||||
final response = await http.get(
|
||||
Uri.parse('${ApiConfig.baseUrl}${ApiConfig.assistantesMaternellesCouplesGarde}'),
|
||||
headers: await _headers(),
|
||||
);
|
||||
|
||||
if (response.statusCode != 200) {
|
||||
throw Exception(
|
||||
_extractError(response.body, 'Erreur chargement des couples de garde (AM)'),
|
||||
);
|
||||
}
|
||||
|
||||
final decoded = jsonDecode(response.body);
|
||||
return CouplesGardeResponse.fromJson(
|
||||
Map<String, dynamic>.from(decoded as Map),
|
||||
);
|
||||
}
|
||||
|
||||
/// Persiste le couple courant (AM) et renvoie la liste à jour.
|
||||
static Future<CouplesGardeResponse> definirAmCoupleCourant(
|
||||
String coupleId,
|
||||
) async {
|
||||
final response = await http.put(
|
||||
Uri.parse('${ApiConfig.baseUrl}${ApiConfig.assistantesMaternellesCoupleGardeCourant}'),
|
||||
headers: await _headers(),
|
||||
body: jsonEncode({'couple_id': coupleId}),
|
||||
);
|
||||
|
||||
if (response.statusCode != 200) {
|
||||
throw Exception(
|
||||
_extractError(response.body, 'Erreur sélection du couple de garde (AM)'),
|
||||
);
|
||||
}
|
||||
|
||||
final decoded = jsonDecode(response.body);
|
||||
return CouplesGardeResponse.fromJson(
|
||||
Map<String, dynamic>.from(decoded as Map),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user