forked from eatvio/eatvio_app
feat: implement offline-first architecture with local database synchronization and diary caching
This commit is contained in:
@@ -3,6 +3,8 @@ import 'dart:io';
|
||||
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:eatvio_app/core/image_compressing/image_compress_utility.dart';
|
||||
import 'package:eatvio_app/core/internet_connection_cubit/internet_connection_cubit.dart';
|
||||
import 'package:eatvio_app/core/local_db/diary_local_data_source.dart';
|
||||
import 'package:eatvio_app/core/utils/date_time_utils.dart';
|
||||
import 'package:eatvio_app/features/chat/repositories/chat_repository.dart';
|
||||
import 'package:eatvio_app/features/consultations/models/consultation_model.dart';
|
||||
@@ -30,7 +32,13 @@ class DiaryCubit extends Cubit<DiaryState> {
|
||||
final DietRepository dietRepository;
|
||||
final ChatRepository chatRepository;
|
||||
final SettingsRepository settingsRepository;
|
||||
final DiaryLocalDataSource localDataSource;
|
||||
final InternetConnectionCubit connectionCubit;
|
||||
int? diaryId;
|
||||
|
||||
// Трек офлайн-режима
|
||||
bool _lastFetchWasOffline = false;
|
||||
|
||||
DiaryCubit({
|
||||
required this.chatRepository,
|
||||
required this.diaryRepository,
|
||||
@@ -38,6 +46,8 @@ class DiaryCubit extends Cubit<DiaryState> {
|
||||
required this.profileRepository,
|
||||
required this.dietRepository,
|
||||
required this.settingsRepository,
|
||||
required this.localDataSource,
|
||||
required this.connectionCubit,
|
||||
}) : super(const DiaryState.loading()) {
|
||||
today = DateTime.now();
|
||||
selectedDay = today;
|
||||
@@ -86,7 +96,11 @@ class DiaryCubit extends Cubit<DiaryState> {
|
||||
|
||||
final diaryDay = await getDiary();
|
||||
if (diaryDay == null) {
|
||||
emit(const DiaryState.error(errorMessage: 'Diary not found'));
|
||||
// Офлайн и нет кэша — показываем понятное сообщение
|
||||
final msg = connectionCubit.state.isInternetAvailable
|
||||
? 'Дневник не найден'
|
||||
: 'Нет интернета. Откройте дневник онлайн хотя бы один раз, чтобы он был доступен офлайн.';
|
||||
emit(DiaryState.error(errorMessage: msg));
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -110,7 +124,9 @@ class DiaryCubit extends Cubit<DiaryState> {
|
||||
|
||||
Future<void> updateCurrentDiary() async {
|
||||
try {
|
||||
final diaryDay = await diaryRepository.getDiaryDayV2(day: selectedDay.toISO8601WithTimeZoneOffset());
|
||||
final diaryDay = await diaryRepository.getDiaryDayV2(
|
||||
day: selectedDay.toISO8601WithTimeZoneOffset(),
|
||||
);
|
||||
final diaryEntity = diaryDay.toEntity();
|
||||
if (diaryEntity != null) {
|
||||
setDiary(diaryDay: diaryEntity, diaryId: diaryId);
|
||||
@@ -121,19 +137,39 @@ class DiaryCubit extends Cubit<DiaryState> {
|
||||
}
|
||||
|
||||
Future<DiaryDayModel?> getDiary() async {
|
||||
_lastFetchWasOffline = false;
|
||||
|
||||
// Офлайн: СРАЗУ в кэш, не трогаем сеть
|
||||
if (!connectionCubit.state.isInternetAvailable) {
|
||||
_lastFetchWasOffline = true;
|
||||
try {
|
||||
return await diaryRepository.getDiaryDayV2(
|
||||
day: selectedDay.toISO8601WithTimeZoneOffset(),
|
||||
);
|
||||
} catch (_) {
|
||||
return null; // Нет кэша — вернём null, UI покажет offline-заглушку
|
||||
}
|
||||
}
|
||||
|
||||
// Онлайн: создаём день + грузим с сервера
|
||||
try {
|
||||
await diaryRepository.createDiaryDay(day: selectedDay.toISO8601WithTimeZoneOffset());
|
||||
final diaryDay = await diaryRepository.getDiaryDayV2(day: selectedDay.toISO8601WithTimeZoneOffset());
|
||||
return diaryDay;
|
||||
return await diaryRepository.getDiaryDayV2(day: selectedDay.toISO8601WithTimeZoneOffset());
|
||||
} catch (e, st) {
|
||||
log(e.toString(), stackTrace: st);
|
||||
if (e is DioException) {
|
||||
if (e.response?.statusCode == 422) {
|
||||
final diaryDay = await diaryRepository.getDiaryDayV2(day: selectedDay.toISO8601WithTimeZoneOffset());
|
||||
return diaryDay;
|
||||
}
|
||||
if (e is DioException && e.response?.statusCode == 422) {
|
||||
// День уже существует — просто загружаем
|
||||
try {
|
||||
return await diaryRepository.getDiaryDayV2(day: selectedDay.toISO8601WithTimeZoneOffset());
|
||||
} catch (_) {}
|
||||
}
|
||||
// Другая сетевая ошибка → пробуем кэш
|
||||
_lastFetchWasOffline = true;
|
||||
try {
|
||||
return await diaryRepository.getDiaryDayV2(day: selectedDay.toISO8601WithTimeZoneOffset());
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -232,35 +268,54 @@ class DiaryCubit extends Cubit<DiaryState> {
|
||||
try {
|
||||
bool isMoodEnabled = false;
|
||||
bool isWakeUpAndRetireTimeEnabled = false;
|
||||
if (diaryId != null) {
|
||||
} else {
|
||||
final profileSettings = await settingsRepository.getProfileSettings();
|
||||
isMoodEnabled = profileSettings.isMoodFillable;
|
||||
isWakeUpAndRetireTimeEnabled = profileSettings.isBedtimeFillable;
|
||||
if (diaryId == null) {
|
||||
try {
|
||||
final profileSettings = await settingsRepository.getProfileSettings();
|
||||
isMoodEnabled = profileSettings.isMoodFillable;
|
||||
isWakeUpAndRetireTimeEnabled = profileSettings.isBedtimeFillable;
|
||||
} catch (_) {
|
||||
// Офлайн — используем значения по умолчанию
|
||||
}
|
||||
}
|
||||
|
||||
ConsultantReviewModel? consultantReview;
|
||||
int? planDuration;
|
||||
int? currentPlanDay;
|
||||
String? planName;
|
||||
if (diaryDay.chosenPlanId != null) {
|
||||
final chosenPlanModel = await chatRepository.getChosenPlan(id: diaryDay.chosenPlanId!);
|
||||
if (!isConsultantView &&
|
||||
(diaryDay.typeOfDiary.diaryState == DiaryStateEnum.lastDayCommented || diaryDay.typeOfDiary.diaryState == DiaryStateEnum.commented)) {
|
||||
await diaryRepository.viewCommentOfDiaryDayByConsultant(diaryId: diaryDay.id);
|
||||
try {
|
||||
final chosenPlanModel = await chatRepository.getChosenPlan(id: diaryDay.chosenPlanId!);
|
||||
if (!isConsultantView &&
|
||||
(diaryDay.typeOfDiary.diaryState == DiaryStateEnum.lastDayCommented ||
|
||||
diaryDay.typeOfDiary.diaryState == DiaryStateEnum.commented)) {
|
||||
await diaryRepository.viewCommentOfDiaryDayByConsultant(diaryId: diaryDay.id);
|
||||
}
|
||||
consultantReview = await diaryRepository.getDiaryComments(
|
||||
planId: diaryDay.chosenPlanId!,
|
||||
diaryId: diaryDay.id,
|
||||
);
|
||||
planDuration = chosenPlanModel.plan.duration;
|
||||
planName = chosenPlanModel.plan.name;
|
||||
currentPlanDay = consultantReview.currentPlanDay;
|
||||
} catch (_) {
|
||||
// Офлайн — данные плана недоступны
|
||||
}
|
||||
consultantReview = await diaryRepository.getDiaryComments(planId: diaryDay.chosenPlanId!, diaryId: diaryDay.id);
|
||||
planDuration = chosenPlanModel.plan.duration;
|
||||
planName = chosenPlanModel.plan.name;
|
||||
currentPlanDay = consultantReview.currentPlanDay;
|
||||
}
|
||||
|
||||
final nutrition = await getNutrition(diaryDay.id);
|
||||
|
||||
final isDiaryFinished = diaryDay.typeOfDiary.diaryState == DiaryStateEnum.finished || diaryDay.typeOfDiary.diaryState == DiaryStateEnum.lastDayFinished;
|
||||
final isDiaryFinished =
|
||||
diaryDay.typeOfDiary.diaryState == DiaryStateEnum.finished ||
|
||||
diaryDay.typeOfDiary.diaryState == DiaryStateEnum.lastDayFinished;
|
||||
|
||||
final isDiaryCommented =
|
||||
diaryDay.typeOfDiary.diaryState == DiaryStateEnum.commented ||
|
||||
diaryDay.typeOfDiary.diaryState == DiaryStateEnum.lastDayCommented ||
|
||||
diaryDay.typeOfDiary.diaryState == DiaryStateEnum.reviewedByUser;
|
||||
|
||||
// Offline-first: получаем кол-во операций в очереди
|
||||
final pendingCount = await localDataSource.getPendingCount();
|
||||
|
||||
emit(
|
||||
DiaryState.loaded(
|
||||
diary: diaryDay,
|
||||
@@ -276,6 +331,8 @@ class DiaryCubit extends Cubit<DiaryState> {
|
||||
chosenPlanName: planName,
|
||||
isMoodEnabled: isMoodEnabled,
|
||||
isWakeUpAndRetireEnabled: isWakeUpAndRetireTimeEnabled,
|
||||
pendingOpsCount: pendingCount,
|
||||
isOfflineMode: _lastFetchWasOffline,
|
||||
),
|
||||
);
|
||||
} catch (e, st) {
|
||||
@@ -295,8 +352,13 @@ class DiaryCubit extends Cubit<DiaryState> {
|
||||
}
|
||||
}
|
||||
|
||||
Future<NutritionDataModel> getNutrition(int index) async {
|
||||
return (await diaryRepository.getNutritionData(index));
|
||||
Future<NutritionDataModel?> getNutrition(int index) async {
|
||||
try {
|
||||
return await diaryRepository.getNutritionData(index);
|
||||
} catch (e) {
|
||||
log('getNutrition offline fallback: $e');
|
||||
return null; // Офлайн — нет данных по калориям, не критично
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> addProductToMeal({
|
||||
|
||||
@@ -16,7 +16,7 @@ abstract class DiaryState with _$DiaryState {
|
||||
|
||||
const factory DiaryState.loaded({
|
||||
required DiaryDayEntity diary,
|
||||
required NutritionDataModel nutrition,
|
||||
NutritionDataModel? nutrition,
|
||||
required DateTime selectedDay,
|
||||
required int selectedMeal,
|
||||
int? chosenPlanCurrentDay,
|
||||
@@ -29,6 +29,10 @@ abstract class DiaryState with _$DiaryState {
|
||||
@Default(false) bool isWakeUpAndRetireEnabled,
|
||||
@Default(false) bool isMoodEnabled,
|
||||
@Default(false) bool isLoadingAddingProductInMeal,
|
||||
// Offline-first: кол-во операций в очереди на синхронизацию
|
||||
@Default(0) int pendingOpsCount,
|
||||
// Offline-first: true если данные получены из локального кэша
|
||||
@Default(false) bool isOfflineMode,
|
||||
}) = DiaryStateLoaded;
|
||||
|
||||
const factory DiaryState.loadedTomorrowWithDiet({required DiaryFutureDietDayEntity diary, required DateTime selectedDay, required int selectedMeal}) =
|
||||
|
||||
Reference in New Issue
Block a user