forked from eatvio/eatvio_app
fix: diary loading
This commit is contained in:
@@ -88,6 +88,7 @@ class DiaryCubit extends Cubit<DiaryState> {
|
||||
emit(const DiaryState.loading());
|
||||
}
|
||||
if (diaryId != null) {
|
||||
log('[fetchDiaryV2] Loading by diaryId=$diaryId');
|
||||
final diaryDayById = await diaryRepository.getDiaryDay(diaryId);
|
||||
final diaryEntity = diaryDayById.toEntity();
|
||||
if (diaryEntity != null) {
|
||||
@@ -102,24 +103,29 @@ class DiaryCubit extends Cubit<DiaryState> {
|
||||
final msg = connectionCubit.state.isInternetAvailable
|
||||
? 'Дневник не найден'
|
||||
: 'Нет интернета. Откройте дневник онлайн хотя бы один раз, чтобы он был доступен офлайн.';
|
||||
log('[fetchDiaryV2] diaryDay is null, msg=$msg');
|
||||
emit(DiaryState.error(errorMessage: msg));
|
||||
return true;
|
||||
}
|
||||
|
||||
log('[fetchDiaryV2] diaryDay loaded, id=${diaryDay.id}, converting to entity...');
|
||||
final diaryEntity = diaryDay.toEntity();
|
||||
if (diaryEntity != null) {
|
||||
setDiary(diaryDay: diaryEntity, diaryId: diaryId);
|
||||
log('[fetchDiaryV2] entity OK, calling setDiary...');
|
||||
await setDiary(diaryDay: diaryEntity, diaryId: diaryId);
|
||||
log('[fetchDiaryV2] setDiary completed');
|
||||
return true;
|
||||
}
|
||||
if (diaryDay.typeOfDiary.hasChosenDiet == true && diaryDay.typeOfDiary.diaryState == null) {
|
||||
setDiaryForDietOnly(diaryDay.toDiaryFutureDayEntity());
|
||||
return true;
|
||||
}
|
||||
log('[fetchDiaryV2] no entity, emitting previous state');
|
||||
emit(currentState);
|
||||
return false;
|
||||
} catch (e, st) {
|
||||
log('[fetchDiaryV2] CRASH: $e', stackTrace: st);
|
||||
await reportFrom(e, st, this);
|
||||
log(e.toString(), stackTrace: st);
|
||||
emit(DiaryState.error(errorMessage: e.toString()));
|
||||
return false;
|
||||
}
|
||||
@@ -142,37 +148,49 @@ class DiaryCubit extends Cubit<DiaryState> {
|
||||
|
||||
Future<DiaryDayModel?> getDiary() async {
|
||||
_lastFetchWasOffline = false;
|
||||
final dayStr = selectedDay.toISO8601WithTimeZoneOffset();
|
||||
log('[getDiary] START: day=$dayStr, isOnline=${connectionCubit.state.isInternetAvailable}');
|
||||
|
||||
// Офлайн: СРАЗУ в кэш, не трогаем сеть
|
||||
if (!connectionCubit.state.isInternetAvailable) {
|
||||
_lastFetchWasOffline = true;
|
||||
try {
|
||||
return await diaryRepository.getDiaryDayV2(
|
||||
day: selectedDay.toISO8601WithTimeZoneOffset(),
|
||||
);
|
||||
} catch (_) {
|
||||
final result = await diaryRepository.getDiaryDayV2(day: dayStr);
|
||||
log('[getDiary] OFFLINE: loaded from cache OK');
|
||||
return result;
|
||||
} catch (e) {
|
||||
log('[getDiary] OFFLINE: no cache: $e');
|
||||
return null; // Нет кэша — вернём null, UI покажет offline-заглушку
|
||||
}
|
||||
}
|
||||
|
||||
// Онлайн: создаём день + грузим с сервера
|
||||
try {
|
||||
await diaryRepository.createDiaryDay(day: selectedDay.toISO8601WithTimeZoneOffset());
|
||||
return await diaryRepository.getDiaryDayV2(day: selectedDay.toISO8601WithTimeZoneOffset());
|
||||
log('[getDiary] ONLINE: creating diary day...');
|
||||
await diaryRepository.createDiaryDay(day: dayStr);
|
||||
log('[getDiary] ONLINE: day created, loading...');
|
||||
final result = await diaryRepository.getDiaryDayV2(day: dayStr);
|
||||
log('[getDiary] ONLINE: loaded OK, id=${result.id}');
|
||||
return result;
|
||||
} catch (e, st) {
|
||||
log('[getDiary] ONLINE ERROR: $e');
|
||||
await reportFrom(e, st, this);
|
||||
log(e.toString(), stackTrace: st);
|
||||
if (e is DioException && e.response?.statusCode == 422) {
|
||||
// День уже существует — просто загружаем
|
||||
try {
|
||||
return await diaryRepository.getDiaryDayV2(day: selectedDay.toISO8601WithTimeZoneOffset());
|
||||
} catch (_) {}
|
||||
log('[getDiary] 422 fallback: loading existing day...');
|
||||
return await diaryRepository.getDiaryDayV2(day: dayStr);
|
||||
} catch (e2) {
|
||||
log('[getDiary] 422 fallback failed: $e2');
|
||||
}
|
||||
}
|
||||
// Другая сетевая ошибка → пробуем кэш
|
||||
_lastFetchWasOffline = true;
|
||||
try {
|
||||
return await diaryRepository.getDiaryDayV2(day: selectedDay.toISO8601WithTimeZoneOffset());
|
||||
} catch (_) {
|
||||
log('[getDiary] Error fallback: trying cache...');
|
||||
return await diaryRepository.getDiaryDayV2(day: dayStr);
|
||||
} catch (e3) {
|
||||
log('[getDiary] Cache fallback failed: $e3');
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -325,7 +343,12 @@ class DiaryCubit extends Cubit<DiaryState> {
|
||||
diaryDay.typeOfDiary.diaryState == DiaryStateEnum.reviewedByUser;
|
||||
|
||||
// Offline-first: получаем кол-во операций в очереди
|
||||
final pendingCount = await localDataSource.getPendingCount();
|
||||
int pendingCount = 0;
|
||||
try {
|
||||
pendingCount = await localDataSource.getPendingCount();
|
||||
} catch (_) {
|
||||
// Ошибка чтения pending_operations — не критично
|
||||
}
|
||||
|
||||
emit(
|
||||
DiaryState.loaded(
|
||||
|
||||
122
lib/features/diary/presentation/bloc/glossary_sync_cubit.dart
Normal file
122
lib/features/diary/presentation/bloc/glossary_sync_cubit.dart
Normal file
@@ -0,0 +1,122 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:eatvio_app/core/internet_connection_cubit/internet_connection_cubit.dart';
|
||||
import 'package:eatvio_app/core/local_db/services/glossary_sync_runner.dart';
|
||||
import 'package:eatvio_app/features/diary/presentation/bloc/glossary_sync_state.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
|
||||
/// Кубит для отслеживания синхронизации глоссария продуктов.
|
||||
///
|
||||
/// Подписывается на [InternetConnectionCubit] — при появлении сети
|
||||
/// автоматически запускает синхронизацию. Эмитит детальные стадии:
|
||||
/// checking → downloading → processing → completed/error.
|
||||
///
|
||||
/// Используется в [GlossarySyncBannerWidget] для показа прогресса в UI.
|
||||
class GlossarySyncCubit extends Cubit<GlossarySyncState> {
|
||||
final GlossarySyncService _syncService;
|
||||
final InternetConnectionCubit _connectionCubit;
|
||||
|
||||
StreamSubscription? _connectionSub;
|
||||
bool _isSyncing = false;
|
||||
|
||||
/// Таймер автоскрытия баннера после успешной синхронизации
|
||||
Timer? _hideTimer;
|
||||
|
||||
GlossarySyncCubit({
|
||||
required GlossarySyncService syncService,
|
||||
required InternetConnectionCubit connectionCubit,
|
||||
}) : _syncService = syncService,
|
||||
_connectionCubit = connectionCubit,
|
||||
super(const GlossarySyncState.idle());
|
||||
|
||||
/// Начать прослушивание сети и автозапуск синхронизации.
|
||||
void start() {
|
||||
_connectionSub = _connectionCubit.stream.listen((state) {
|
||||
if (state.isInternetAvailable && !_isSyncing) {
|
||||
syncNow();
|
||||
}
|
||||
});
|
||||
|
||||
// Запустить немедленно если уже online
|
||||
if (_connectionCubit.state.isInternetAvailable) {
|
||||
syncNow();
|
||||
}
|
||||
}
|
||||
|
||||
/// Принудительно запустить синхронизацию (можно вызвать из UI).
|
||||
Future<void> syncNow() async {
|
||||
if (_isSyncing) return;
|
||||
_isSyncing = true;
|
||||
_hideTimer?.cancel();
|
||||
|
||||
try {
|
||||
final count = await _syncService.sync(
|
||||
onStageChanged: _onStageChanged,
|
||||
onDownloadProgress: _onDownloadProgress,
|
||||
onProcessingProgress: _onProcessingProgress,
|
||||
);
|
||||
|
||||
if (count == 0) {
|
||||
emit(const GlossarySyncState.upToDate());
|
||||
} else {
|
||||
emit(GlossarySyncState.completed(syncedCount: count));
|
||||
}
|
||||
|
||||
// Автоскрытие через 4 секунды
|
||||
_hideTimer = Timer(const Duration(seconds: 4), () {
|
||||
if (!isClosed) emit(const GlossarySyncState.idle());
|
||||
});
|
||||
} catch (e) {
|
||||
emit(GlossarySyncState.error(message: _humanReadableError(e)));
|
||||
// Скрыть ошибку через 6 секунд
|
||||
_hideTimer = Timer(const Duration(seconds: 6), () {
|
||||
if (!isClosed) emit(const GlossarySyncState.idle());
|
||||
});
|
||||
} finally {
|
||||
_isSyncing = false;
|
||||
}
|
||||
}
|
||||
|
||||
void _onStageChanged(GlossarySyncStage stage) {
|
||||
if (isClosed) return;
|
||||
switch (stage) {
|
||||
case GlossarySyncStage.checking:
|
||||
emit(const GlossarySyncState.checking());
|
||||
case GlossarySyncStage.downloading:
|
||||
emit(const GlossarySyncState.downloading());
|
||||
case GlossarySyncStage.processing:
|
||||
emit(const GlossarySyncState.processing(processed: 0, total: 0));
|
||||
case GlossarySyncStage.saving:
|
||||
// Остаёмся на processing — saving идёт мгновенно
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void _onDownloadProgress(double progress) {
|
||||
if (isClosed) return;
|
||||
emit(GlossarySyncState.downloading(progress: progress));
|
||||
}
|
||||
|
||||
void _onProcessingProgress(int processed, int total) {
|
||||
if (isClosed) return;
|
||||
emit(GlossarySyncState.processing(processed: processed, total: total));
|
||||
}
|
||||
|
||||
String _humanReadableError(Object e) {
|
||||
final msg = e.toString();
|
||||
if (msg.contains('SocketException') || msg.contains('connection')) {
|
||||
return 'Нет соединения с сервером';
|
||||
}
|
||||
if (msg.contains('TimeoutException') || msg.contains('timeout')) {
|
||||
return 'Сервер не отвечает';
|
||||
}
|
||||
return 'Ошибка синхронизации глоссария';
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> close() {
|
||||
_connectionSub?.cancel();
|
||||
_hideTimer?.cancel();
|
||||
return super.close();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import 'package:freezed_annotation/freezed_annotation.dart';
|
||||
|
||||
part 'glossary_sync_state.freezed.dart';
|
||||
|
||||
/// Состояние синхронизации глоссария продуктов.
|
||||
///
|
||||
/// idle → ничего не происходит
|
||||
/// checking → проверяем checksum через /meta
|
||||
/// downloading → скачиваем дамп в файл
|
||||
/// processing → парсим JSON + bulk-insert в БД (progress: 0.0–1.0)
|
||||
/// completed → синхронизация завершена (syncedCount записей)
|
||||
/// error → ошибка синхронизации
|
||||
@freezed
|
||||
abstract class GlossarySyncState with _$GlossarySyncState {
|
||||
const factory GlossarySyncState.idle() = GlossarySyncIdle;
|
||||
|
||||
const factory GlossarySyncState.checking() = GlossarySyncChecking;
|
||||
|
||||
const factory GlossarySyncState.downloading({
|
||||
/// Прогресс загрузки файла: 0.0 – 1.0 (null если Content-Length неизвестен)
|
||||
double? progress,
|
||||
}) = GlossarySyncDownloading;
|
||||
|
||||
const factory GlossarySyncState.processing({
|
||||
/// Кол-во обработанных записей
|
||||
required int processed,
|
||||
/// Общее кол-во записей в дампе
|
||||
required int total,
|
||||
}) = GlossarySyncProcessing;
|
||||
|
||||
const factory GlossarySyncState.completed({
|
||||
/// Кол-во синхронизированных записей
|
||||
required int syncedCount,
|
||||
}) = GlossarySyncCompleted;
|
||||
|
||||
const factory GlossarySyncState.error({
|
||||
required String message,
|
||||
}) = GlossarySyncError;
|
||||
|
||||
const factory GlossarySyncState.upToDate() = GlossarySyncUpToDate;
|
||||
}
|
||||
Reference in New Issue
Block a user