forked from eatvio/eatvio_app
feat(diary): fixes
This commit is contained in:
@@ -174,12 +174,22 @@ class DiaryCubit extends Cubit<DiaryState> {
|
||||
_lastFetchWasOffline = true;
|
||||
return result;
|
||||
} catch (_) {
|
||||
// Кэша нет — попробуем сеть на случай ложного "offline"
|
||||
log('[getDiary] OFFLINE: no cache, trying network as fallback...');
|
||||
// Кэша нет — создаём день локально, чтобы он был видим
|
||||
log('[getDiary] OFFLINE: no cache, creating day locally...');
|
||||
try {
|
||||
await diaryRepository.createDiaryDay(day: dayStr);
|
||||
final result = await diaryRepository.getDiaryDayV2(day: dayStr);
|
||||
log('[getDiary] OFFLINE: local day created and loaded OK');
|
||||
_lastFetchWasOffline = true;
|
||||
return result;
|
||||
} catch (e2) {
|
||||
log('[getDiary] OFFLINE: local day creation failed: $e2');
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Онлайн (или fallback после неудачного offline): создаём день + грузим с сервера
|
||||
// Онлайн: создаём день + грузим с сервера
|
||||
try {
|
||||
log('[getDiary] ONLINE: creating diary day...');
|
||||
await diaryRepository.createDiaryDay(day: dayStr);
|
||||
|
||||
@@ -29,6 +29,10 @@ class GlossarySyncCubit extends Cubit<GlossarySyncState> {
|
||||
_connectionCubit = connectionCubit,
|
||||
super(const GlossarySyncState.idle());
|
||||
|
||||
/// Готов ли глоссарий к использованию (есть ли хотя бы 1 запись в локальном кэше).
|
||||
bool get isGlossaryReady => _glossaryReady;
|
||||
bool _glossaryReady = false;
|
||||
|
||||
/// Начать прослушивание сети и автозапуск синхронизации.
|
||||
void start() {
|
||||
_connectionSub = _connectionCubit.stream.listen((state) {
|
||||
@@ -56,6 +60,8 @@ class GlossarySyncCubit extends Cubit<GlossarySyncState> {
|
||||
onProcessingProgress: _onProcessingProgress,
|
||||
);
|
||||
|
||||
_glossaryReady = true;
|
||||
|
||||
if (count == 0) {
|
||||
emit(const GlossarySyncState.upToDate());
|
||||
} else {
|
||||
@@ -68,10 +74,13 @@ class GlossarySyncCubit extends Cubit<GlossarySyncState> {
|
||||
});
|
||||
} catch (e) {
|
||||
emit(GlossarySyncState.error(message: _humanReadableError(e)));
|
||||
// Скрыть ошибку через 6 секунд
|
||||
_hideTimer = Timer(const Duration(seconds: 6), () {
|
||||
if (!isClosed) emit(const GlossarySyncState.idle());
|
||||
});
|
||||
// Если глоссарий ещё не синхронизирован — НЕ скрываем ошибку,
|
||||
// чтобы пользователь мог нажать «Повторить».
|
||||
if (_glossaryReady) {
|
||||
_hideTimer = Timer(const Duration(seconds: 6), () {
|
||||
if (!isClosed) emit(const GlossarySyncState.idle());
|
||||
});
|
||||
}
|
||||
} finally {
|
||||
_isSyncing = false;
|
||||
}
|
||||
|
||||
@@ -56,6 +56,24 @@ class GlossarySyncBannerWidget extends StatelessWidget {
|
||||
color: const Color(0xFFDC2626),
|
||||
icon: Icons.error_outline_rounded,
|
||||
text: message,
|
||||
action: TextButton(
|
||||
onPressed: () => context.read<GlossarySyncCubit>().syncNow(),
|
||||
style: TextButton.styleFrom(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
|
||||
minimumSize: Size.zero,
|
||||
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
|
||||
),
|
||||
child: const Text(
|
||||
'Повторить',
|
||||
style: TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 12,
|
||||
fontWeight: FontWeight.w700,
|
||||
decoration: TextDecoration.underline,
|
||||
decorationColor: Colors.white,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
@@ -68,6 +86,7 @@ class GlossarySyncBannerWidget extends StatelessWidget {
|
||||
required String text,
|
||||
bool showSpinner = false,
|
||||
double? progress,
|
||||
Widget? action,
|
||||
}) {
|
||||
return _AnimatedBanner(
|
||||
color: color,
|
||||
@@ -75,6 +94,7 @@ class GlossarySyncBannerWidget extends StatelessWidget {
|
||||
text: text,
|
||||
showSpinner: showSpinner,
|
||||
progress: progress,
|
||||
action: action,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -95,6 +115,7 @@ class _AnimatedBanner extends StatefulWidget {
|
||||
final String text;
|
||||
final bool showSpinner;
|
||||
final double? progress;
|
||||
final Widget? action;
|
||||
|
||||
const _AnimatedBanner({
|
||||
required this.color,
|
||||
@@ -102,6 +123,7 @@ class _AnimatedBanner extends StatefulWidget {
|
||||
required this.text,
|
||||
this.showSpinner = false,
|
||||
this.progress,
|
||||
this.action,
|
||||
});
|
||||
|
||||
@override
|
||||
@@ -182,6 +204,7 @@ class _AnimatedBannerState extends State<_AnimatedBanner>
|
||||
),
|
||||
),
|
||||
),
|
||||
if (widget.action != null) widget.action!,
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
@@ -163,6 +163,8 @@ class DiaryRepository {
|
||||
}
|
||||
|
||||
|
||||
/// Write-Behind: обновить порцию в приёме пищи.
|
||||
/// Офлайн/сетевая ошибка → кладём в pending_operations.
|
||||
Future<void> updateProductInMeal({
|
||||
required int diaryId,
|
||||
required int mealId,
|
||||
@@ -173,24 +175,106 @@ class DiaryRepository {
|
||||
int? productNutritionalValueId,
|
||||
required PortionState portionState,
|
||||
}) async {
|
||||
final data = ProductInMeal(productName: productName, portion: portion, quantity: quantity).toJson();
|
||||
if (productNutritionalValueId != null) data['product_nutritional_value_id'] = productNutritionalValueId;
|
||||
data['state'] = portionState.name;
|
||||
return diaryService.updateProductInMeal(diary: diaryId, typeNo: mealId, portionModel: portionId, productInMeal: data);
|
||||
final payload = {
|
||||
'diary_id': diaryId,
|
||||
'meal_id': mealId,
|
||||
'portion_id': portionId,
|
||||
'product_name': productName,
|
||||
'portion': portion,
|
||||
'quantity': quantity,
|
||||
if (productNutritionalValueId != null) 'product_nutritional_value_id': productNutritionalValueId,
|
||||
'state': portionState.name,
|
||||
};
|
||||
|
||||
if (!_isOnline) {
|
||||
await localDataSource.enqueueOperation(type: 'update_portion', payload: payload);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
final data = ProductInMeal(productName: productName, portion: portion, quantity: quantity).toJson();
|
||||
if (productNutritionalValueId != null) data['product_nutritional_value_id'] = productNutritionalValueId;
|
||||
data['state'] = portionState.name;
|
||||
await diaryService.updateProductInMeal(diary: diaryId, typeNo: mealId, portionModel: portionId, productInMeal: data);
|
||||
} on DioException catch (e, s) {
|
||||
final statusCode = e.response?.statusCode;
|
||||
if (statusCode != null && statusCode >= 400 && statusCode < 500) {
|
||||
await Sentry.captureException(e, stackTrace: s);
|
||||
rethrow;
|
||||
}
|
||||
await Sentry.captureException(e, stackTrace: s);
|
||||
await localDataSource.enqueueOperation(type: 'update_portion', payload: payload);
|
||||
}
|
||||
}
|
||||
|
||||
/// Write-Behind: отметить порцию как съеденную.
|
||||
Future<void> markEaten({required int diaryId, required int mealId, required int portionId}) async {
|
||||
return diaryService.markEaten(diary: diaryId, typeNo: mealId, portionModel: portionId);
|
||||
final payload = {'diary_id': diaryId, 'meal_id': mealId, 'portion_id': portionId};
|
||||
|
||||
if (!_isOnline) {
|
||||
await localDataSource.enqueueOperation(type: 'mark_eaten', payload: payload);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await diaryService.markEaten(diary: diaryId, typeNo: mealId, portionModel: portionId);
|
||||
} on DioException catch (e, s) {
|
||||
final statusCode = e.response?.statusCode;
|
||||
if (statusCode != null && statusCode >= 400 && statusCode < 500) {
|
||||
await Sentry.captureException(e, stackTrace: s);
|
||||
rethrow;
|
||||
}
|
||||
await Sentry.captureException(e, stackTrace: s);
|
||||
await localDataSource.enqueueOperation(type: 'mark_eaten', payload: payload);
|
||||
}
|
||||
}
|
||||
|
||||
/// Write-Behind: снять отметку "съедено".
|
||||
Future<void> unmarkEaten({required int diaryId, required int mealId, required int portionId}) async {
|
||||
return diaryService.unmarkEaten(diary: diaryId, typeNo: mealId, portionModel: portionId);
|
||||
final payload = {'diary_id': diaryId, 'meal_id': mealId, 'portion_id': portionId};
|
||||
|
||||
if (!_isOnline) {
|
||||
await localDataSource.enqueueOperation(type: 'unmark_eaten', payload: payload);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await diaryService.unmarkEaten(diary: diaryId, typeNo: mealId, portionModel: portionId);
|
||||
} on DioException catch (e, s) {
|
||||
final statusCode = e.response?.statusCode;
|
||||
if (statusCode != null && statusCode >= 400 && statusCode < 500) {
|
||||
await Sentry.captureException(e, stackTrace: s);
|
||||
rethrow;
|
||||
}
|
||||
await Sentry.captureException(e, stackTrace: s);
|
||||
await localDataSource.enqueueOperation(type: 'unmark_eaten', payload: payload);
|
||||
}
|
||||
}
|
||||
|
||||
/// Write-Behind: восстановить удалённую порцию.
|
||||
Future<void> restore({required int diaryId, required int mealId, required int portionId}) async {
|
||||
return diaryService.restore(diary: diaryId, typeNo: mealId, portionModel: portionId);
|
||||
final payload = {'diary_id': diaryId, 'meal_id': mealId, 'portion_id': portionId};
|
||||
|
||||
if (!_isOnline) {
|
||||
await localDataSource.enqueueOperation(type: 'restore', payload: payload);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await diaryService.restore(diary: diaryId, typeNo: mealId, portionModel: portionId);
|
||||
} on DioException catch (e, s) {
|
||||
final statusCode = e.response?.statusCode;
|
||||
if (statusCode != null && statusCode >= 400 && statusCode < 500) {
|
||||
await Sentry.captureException(e, stackTrace: s);
|
||||
rethrow;
|
||||
}
|
||||
await Sentry.captureException(e, stackTrace: s);
|
||||
await localDataSource.enqueueOperation(type: 'restore', payload: payload);
|
||||
}
|
||||
}
|
||||
|
||||
/// Write-Behind: удалить порцию из приёма пищи.
|
||||
/// Использует idempotent API вариант для предотвращения дубликатов.
|
||||
Future<void> deleteProductFromMeal({required int diaryId, required int mealId, required int portionId}) async {
|
||||
final payload = {
|
||||
'diary_id': diaryId,
|
||||
@@ -203,8 +287,14 @@ class DiaryRepository {
|
||||
return;
|
||||
}
|
||||
|
||||
final idempotencyKey = _uuid.v4();
|
||||
try {
|
||||
await diaryService.deleteProductFromMeal(diary: diaryId, typeNo: mealId, portionModel: portionId);
|
||||
await diaryService.deleteProductFromMealIdempotent(
|
||||
idempotencyKey: idempotencyKey,
|
||||
diary: diaryId,
|
||||
typeNo: mealId,
|
||||
portionModel: portionId,
|
||||
);
|
||||
} on DioException catch (e, s) {
|
||||
final statusCode = e.response?.statusCode;
|
||||
if (statusCode != null && statusCode >= 400 && statusCode < 500) {
|
||||
@@ -216,14 +306,66 @@ class DiaryRepository {
|
||||
}
|
||||
}
|
||||
|
||||
/// Write-Behind: загрузить фото приёма пищи.
|
||||
/// Офлайн → сохраняем файл локально и ставим в очередь.
|
||||
Future<void> uploadPhotos({required int diaryId, required int mealId, required List<File> files}) async {
|
||||
for (var i = 0; i < files.length; i++) {
|
||||
await diaryService.uploadPhotoOfMeal(diary: diaryId, typeNo: mealId, photo: files[i]);
|
||||
final file = files[i];
|
||||
final payload = {'diary_id': diaryId, 'type_no': mealId};
|
||||
|
||||
if (!_isOnline) {
|
||||
await localDataSource.enqueueOperation(
|
||||
type: 'upload_photo',
|
||||
payload: payload,
|
||||
localFilePath: file.path,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
final idempotencyKey = _uuid.v4();
|
||||
try {
|
||||
await diaryService.uploadPhotoIdempotent(
|
||||
idempotencyKey: idempotencyKey,
|
||||
diary: diaryId,
|
||||
typeNo: mealId,
|
||||
photo: file,
|
||||
);
|
||||
} on DioException catch (e, s) {
|
||||
final statusCode = e.response?.statusCode;
|
||||
if (statusCode != null && statusCode >= 400 && statusCode < 500) {
|
||||
await Sentry.captureException(e, stackTrace: s);
|
||||
rethrow;
|
||||
}
|
||||
await Sentry.captureException(e, stackTrace: s);
|
||||
await localDataSource.enqueueOperation(
|
||||
type: 'upload_photo',
|
||||
payload: payload,
|
||||
localFilePath: file.path,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Write-Behind: удалить фото приёма пищи.
|
||||
Future<void> deletePhoto({required int diaryId, required int mealId, required DiaryPhotoModel photo}) async {
|
||||
await diaryService.deletePhotoOfMeal(diaryId: diaryId, typeNo: mealId, userAttachment: photo.id);
|
||||
final payload = {'diary_id': diaryId, 'type_no': mealId, 'media_id': photo.id};
|
||||
|
||||
if (!_isOnline) {
|
||||
await localDataSource.enqueueOperation(type: 'delete_photo', payload: payload);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await diaryService.deletePhotoOfMeal(diaryId: diaryId, typeNo: mealId, userAttachment: photo.id);
|
||||
} on DioException catch (e, s) {
|
||||
final statusCode = e.response?.statusCode;
|
||||
if (statusCode != null && statusCode >= 400 && statusCode < 500) {
|
||||
await Sentry.captureException(e, stackTrace: s);
|
||||
rethrow;
|
||||
}
|
||||
await Sentry.captureException(e, stackTrace: s);
|
||||
await localDataSource.enqueueOperation(type: 'delete_photo', payload: payload);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> finishDiaryDay({required int diaryId, required String wakeUp, required String retire, String? comment}) async {
|
||||
@@ -320,16 +462,26 @@ class DiaryRepository {
|
||||
}
|
||||
}
|
||||
|
||||
/// Комментарий консультанта — только онлайн.
|
||||
Future<void> commentUserDay({required int diaryId, required ConsultantCommentModel commentModel}) async {
|
||||
if (!_isOnline) {
|
||||
throw Exception('Комментирование невозможно без интернета');
|
||||
}
|
||||
await diaryService.commentUserDay(id: diaryId, body: commentModel);
|
||||
_diaryForceFetchController.add('force');
|
||||
}
|
||||
|
||||
/// Получить комментарии — только онлайн.
|
||||
Future<ConsultantReviewModel> getDiaryComments({required int planId, required int diaryId}) async {
|
||||
if (!_isOnline) {
|
||||
throw Exception('Просмотр комментариев невозможен без интернета');
|
||||
}
|
||||
return diaryService.getDiaryComments(planId: planId, diaryId: diaryId);
|
||||
}
|
||||
|
||||
/// Отметить просмотр комментария — только онлайн.
|
||||
Future<void> viewCommentOfDiaryDayByConsultant({required int diaryId}) async {
|
||||
if (!_isOnline) return; // Тихо игнорируем — не критично
|
||||
await diaryService.viewCommentOfDiaryDayByConsultant(diaryId: diaryId);
|
||||
}
|
||||
|
||||
@@ -370,12 +522,28 @@ class DiaryRepository {
|
||||
}
|
||||
}
|
||||
|
||||
/// Write-Behind: создаём день локально + ставим в очередь если онлайн.
|
||||
/// Write-Behind: создаём день локально (с 5 пустыми meals) + отправляем на сервер.
|
||||
/// Офлайн → ставим в очередь для повторной отправки.
|
||||
Future<void> createDiaryDay({required String day}) async {
|
||||
final dateOnly = day.substring(0, 10);
|
||||
// Всегда кэшируем локально
|
||||
// Всегда кэшируем локально — полную структуру с 5 meals
|
||||
await localDataSource.cacheDiaryDay(date: dateOnly);
|
||||
|
||||
// Создаём 5 пустых meals (как делает сервер)
|
||||
final cachedDay = await localDataSource.getCachedDay(dateOnly);
|
||||
if (cachedDay != null) {
|
||||
// Проверяем, есть ли уже meals — если нет, создаём
|
||||
final existingMeals = await localDataSource.getCachedMeals(cachedDay.id);
|
||||
if (existingMeals.isEmpty) {
|
||||
for (int typeNo = 1; typeNo <= 5; typeNo++) {
|
||||
await localDataSource.cacheMeal(
|
||||
diaryDayId: cachedDay.id,
|
||||
typeNo: typeNo,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Всегда пробуем сеть (connectivity может ошибаться)
|
||||
try {
|
||||
final idempotencyKey = _uuid.v4();
|
||||
@@ -470,6 +638,16 @@ class DiaryRepository {
|
||||
fromDiet: portion.fromDiet,
|
||||
);
|
||||
}
|
||||
|
||||
// 5. Кэшируем фото приёма пищи
|
||||
await localDataSource.clearCachedMedia(cachedMeal.id);
|
||||
for (final photo in meal.photos) {
|
||||
await localDataSource.cacheMedia(
|
||||
mealId: cachedMeal.id,
|
||||
serverId: photo.id,
|
||||
url: photo.path,
|
||||
);
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
// Ошибка кэширования не должна ломать основной флоу
|
||||
@@ -477,7 +655,8 @@ class DiaryRepository {
|
||||
}
|
||||
|
||||
/// Загрузить DiaryDayModel из локального кэша (Fallback).
|
||||
/// Возвращает null если данных нет или кэш устарел.
|
||||
/// Возвращает null если данных нет.
|
||||
/// Для офлайн-дней (serverId == null) использует отрицательный временный ID.
|
||||
Future<DiaryDayModel?> _loadCachedDiaryDay(String date) async {
|
||||
try {
|
||||
final cached = await localDataSource.getCachedDay(date);
|
||||
@@ -502,6 +681,18 @@ class DiaryRepository {
|
||||
),
|
||||
)).toList();
|
||||
|
||||
// Загружаем фото из локального кэша
|
||||
final media = await localDataSource.getCachedMedia(meal.id);
|
||||
final photoModels = media
|
||||
.where((m) => m.status != 'pending_delete')
|
||||
.map((m) => DiaryPhotoModel(
|
||||
id: m.serverId ?? m.id,
|
||||
originalName: '',
|
||||
path: m.url ?? m.localPath ?? '',
|
||||
size: 0,
|
||||
))
|
||||
.toList();
|
||||
|
||||
mealModels.add(MealModel(
|
||||
id: meal.id,
|
||||
time: meal.time ?? '',
|
||||
@@ -509,16 +700,17 @@ class DiaryRepository {
|
||||
satiety: meal.satiety,
|
||||
mood: meal.mood ?? 0,
|
||||
portions: portionModels,
|
||||
photos: [],
|
||||
photos: photoModels,
|
||||
));
|
||||
}
|
||||
|
||||
// Если день создан офлайн (serverId == null), возвращаем null —
|
||||
// нельзя использовать local id для API-запросов.
|
||||
if (cached.serverId == null) return null;
|
||||
// Если день создан офлайн (serverId == null) — используем отрицательный
|
||||
// временный ID, чтобы отличить от серверных. Операции с таким ID
|
||||
// автоматически попадут в очередь pending_operations.
|
||||
final diaryId = cached.serverId ?? -cached.id;
|
||||
|
||||
return DiaryDayModel(
|
||||
id: cached.serverId!,
|
||||
id: diaryId,
|
||||
date: cached.date,
|
||||
wakeup: cached.wakeup,
|
||||
retire: cached.retire,
|
||||
|
||||
Reference in New Issue
Block a user