forked from eatvio/eatvio_app
fix(diary): some fixes offline-diary
This commit is contained in:
@@ -156,7 +156,14 @@ class DiaryCubit extends Cubit<DiaryState> {
|
||||
}
|
||||
} catch (e, st) {
|
||||
await reportFrom(e, st, this);
|
||||
log(e.toString());
|
||||
log('updateCurrentDiary error: $e');
|
||||
// BUG-1 fix: офлайн fallback — перезагружаем из кэша, чтобы UI
|
||||
// отразил изменения, выполненные пользователем.
|
||||
try {
|
||||
await fetchDiaryV2(needLoading: false, diaryId: diaryId);
|
||||
} catch (_) {
|
||||
// Не критично — UI останется на текущем состоянии
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -351,8 +358,9 @@ class DiaryCubit extends Cubit<DiaryState> {
|
||||
planDuration = chosenPlanModel.plan.duration;
|
||||
planName = chosenPlanModel.plan.name;
|
||||
currentPlanDay = consultantReview.currentPlanDay;
|
||||
} catch (_) {
|
||||
// Офлайн — данные плана недоступны
|
||||
} catch (e) {
|
||||
// BUG-9 fix: офлайн — данные плана недоступны, логируем для отладки
|
||||
log('[setDiary] Plan/comments data unavailable (offline?): $e');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -431,7 +439,11 @@ class DiaryCubit extends Cubit<DiaryState> {
|
||||
required int quantity,
|
||||
int? productNutritionalValueId,
|
||||
}) async {
|
||||
emit((state as DiaryStateLoaded).copyWith(isLoadingAddingProductInMeal: true));
|
||||
// BUG-2 fix: безопасная проверка типа стейта перед кастом
|
||||
final currentState = state;
|
||||
if (currentState is DiaryStateLoaded) {
|
||||
emit(currentState.copyWith(isLoadingAddingProductInMeal: true));
|
||||
}
|
||||
try {
|
||||
await diaryRepository.addPortionToMeal(
|
||||
diaryId: diaryId,
|
||||
|
||||
@@ -159,8 +159,8 @@ class _DiaryScreenContentState extends State<DiaryScreenContent> {
|
||||
});
|
||||
final isFinished = await context.read<DiaryCubit>().finishDiaryDay(
|
||||
diaryId: state.diary.id,
|
||||
wakeUp: state.diary.wakeup.toString(),
|
||||
retire: state.diary.retire.toString(),
|
||||
wakeUp: state.diary.wakeup ?? '06:30:00',
|
||||
retire: state.diary.retire ?? '22:30:00',
|
||||
);
|
||||
if (!isFinished && context.mounted) {
|
||||
showErrorDialog(context);
|
||||
|
||||
@@ -170,10 +170,19 @@ class _AddProductModalState extends State<AddProductModal> {
|
||||
if (widget.portion != null) const SizedBox(width: 8),
|
||||
InkWell(
|
||||
onTap: () {
|
||||
// BUG-4 fix: валидация полей перед отправкой
|
||||
final productName = productNameController.text.trim();
|
||||
if (productName.isEmpty) return;
|
||||
|
||||
final isGrams = selectedGlossary == null || selectedGlossary!.grInPortion == 0;
|
||||
final portionType = isGrams ? 'gr' : 'pcs';
|
||||
// BUG-4 fix: безопасный парсинг количества с дефолтом
|
||||
final quantity = int.tryParse(quantityController.text) ?? (isGrams ? 100 : 1);
|
||||
|
||||
// Автоматически выбираем первый элемент, если текст точно совпадает
|
||||
if (selectedGlossary == null &&
|
||||
glossariesList.isNotEmpty &&
|
||||
productNameController.text.trim().toLowerCase() == glossariesList[0].name.toLowerCase()) {
|
||||
productName.toLowerCase() == glossariesList[0].name.toLowerCase()) {
|
||||
selectedGlossary = glossariesList[0];
|
||||
}
|
||||
|
||||
@@ -181,13 +190,9 @@ class _AddProductModalState extends State<AddProductModal> {
|
||||
widget.diaryCubit.addProductToMeal(
|
||||
diaryId: widget.state.diary.id,
|
||||
mealId: widget.state.selectedMeal,
|
||||
productName: productNameController.text,
|
||||
portion: selectedGlossary == null
|
||||
? 'gr'
|
||||
: selectedGlossary!.grInPortion == 0
|
||||
? 'gr'
|
||||
: 'pcs',
|
||||
quantity: int.parse(quantityController.text),
|
||||
productName: productName,
|
||||
portion: portionType,
|
||||
quantity: quantity,
|
||||
productNutritionalValueId: selectedGlossary?.id,
|
||||
);
|
||||
} else {
|
||||
@@ -195,26 +200,22 @@ class _AddProductModalState extends State<AddProductModal> {
|
||||
diaryId: widget.state.diary.id,
|
||||
mealId: widget.state.selectedMeal,
|
||||
portionId: widget.portion!.id,
|
||||
productName: productNameController.text,
|
||||
portion: selectedGlossary == null
|
||||
? 'gr'
|
||||
: selectedGlossary!.grInPortion == 0
|
||||
? 'gr'
|
||||
: 'pcs',
|
||||
quantity: int.parse(quantityController.text),
|
||||
productName: productName,
|
||||
portion: portionType,
|
||||
quantity: quantity,
|
||||
productNutritionalValueId: selectedGlossary?.id,
|
||||
portionState: widget.portion!.portionState,
|
||||
);
|
||||
}
|
||||
Navigator.of(context).pop();
|
||||
if (selectedGlossary == null && _previousProductName != productNameController.text) {
|
||||
if (selectedGlossary == null && _previousProductName != productName) {
|
||||
showModalBottomSheet(
|
||||
isScrollControlled: true,
|
||||
useRootNavigator: true,
|
||||
context: context,
|
||||
builder: (context) => Padding(
|
||||
padding: EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom),
|
||||
child: GlossaryModerationRequestModalWidget(productName: productNameController.text, diaryCubit: widget.diaryCubit),
|
||||
child: GlossaryModerationRequestModalWidget(productName: productName, diaryCubit: widget.diaryCubit),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -116,7 +116,13 @@ class _PhotoGalleryWidgetState extends State<PhotoGalleryWidget> {
|
||||
builder: (context, state) {
|
||||
if (state is DiaryStateLoaded) {
|
||||
int mealIndex = state.selectedMeal - 1;
|
||||
if (state.diary.meals[mealIndex].photos.isEmpty && !state.isConsultantView && !state.isDiaryFinished && !state.isDiaryCommented) {
|
||||
final photos = state.diary.meals[mealIndex].photos;
|
||||
// BUG-5 fix: сбросить индекс, если он вышел за пределы
|
||||
// (например, после переключения на meal с меньшим числом фото)
|
||||
if (currentSelectedPhotoIndex >= photos.length) {
|
||||
currentSelectedPhotoIndex = 0;
|
||||
}
|
||||
if (photos.isEmpty && !state.isConsultantView && !state.isDiaryFinished && !state.isDiaryCommented) {
|
||||
return GestureDetector(
|
||||
onTap: () async {
|
||||
showImagePicker(state.diary);
|
||||
|
||||
@@ -25,6 +25,7 @@ class ProductWidget extends StatefulWidget {
|
||||
class _ProductWidgetState extends State<ProductWidget> {
|
||||
late final DiaryCubit diaryCubit;
|
||||
late String portionName;
|
||||
// BUG-8 fix: инициализируем из актуального state порции
|
||||
late bool isEaten;
|
||||
bool showCommentWidget = false;
|
||||
@override
|
||||
@@ -32,7 +33,7 @@ class _ProductWidgetState extends State<ProductWidget> {
|
||||
super.initState();
|
||||
diaryCubit = context.read<DiaryCubit>();
|
||||
portionName = widget.portion.portion == 'gr' ? 'гр' : 'шт';
|
||||
isEaten = widget.portion.portionState == PortionState.eatenFromDiet ? true : false;
|
||||
isEaten = widget.portion.portionState == PortionState.eatenFromDiet;
|
||||
}
|
||||
|
||||
Widget _buildNutritionalInfo() {
|
||||
@@ -93,7 +94,8 @@ class _ProductWidgetState extends State<ProductWidget> {
|
||||
void didUpdateWidget(ProductWidget oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
portionName = widget.portion.portion == 'gr' ? 'гр' : 'шт';
|
||||
isEaten = widget.portion.portionState == PortionState.eatenFromDiet ? true : false;
|
||||
// BUG-8 fix: синхронизируем isEaten с актуальным state порции
|
||||
isEaten = widget.portion.portionState == PortionState.eatenFromDiet;
|
||||
}
|
||||
|
||||
Future updateProductInMeal(DiaryStateLoaded state, PortionModel portion) {
|
||||
|
||||
@@ -23,6 +23,12 @@ class _TimeOfMealPickerWidgetState extends State<TimeOfMealPickerWidget> {
|
||||
diaryCubit = context.read<DiaryCubit>();
|
||||
}
|
||||
|
||||
/// Безопасное форматирование времени (HH:MM:SS → HH:MM, пустое → '--:--')
|
||||
String _formatTime(String time) {
|
||||
if (time.isEmpty || time.length < 5) return '--:--';
|
||||
return time.substring(0, 5);
|
||||
}
|
||||
|
||||
void showTimePicker(int diaryId) {
|
||||
showModalBottomSheet<void>(
|
||||
context: context,
|
||||
@@ -110,7 +116,7 @@ class _TimeOfMealPickerWidgetState extends State<TimeOfMealPickerWidget> {
|
||||
alignment: Alignment.center,
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16),
|
||||
child: Text(
|
||||
state.diary.meals[state.selectedMeal - 1].time.substring(0, state.diary.meals[state.selectedMeal - 1].time.length - 3),
|
||||
_formatTime(state.diary.meals[state.selectedMeal - 1].time),
|
||||
style: const TextStyle(
|
||||
color: Color(0xFF6D6F71),
|
||||
fontSize: 17,
|
||||
|
||||
@@ -26,6 +26,12 @@ class _WakeupAndRetireWidgetState extends State<WakeupAndRetireWidget> {
|
||||
diaryCubit = context.read<DiaryCubit>();
|
||||
}
|
||||
|
||||
/// BUG-3 fix: безопасное форматирование времени (HH:MM:SS → HH:MM, null → '--:--')
|
||||
String _formatTime(String? time) {
|
||||
if (time == null || time.length < 5) return '--:--';
|
||||
return time.substring(0, 5);
|
||||
}
|
||||
|
||||
void showTimePicker(int diaryId, bool isWakeup) {
|
||||
showModalBottomSheet<void>(
|
||||
context: context,
|
||||
@@ -142,10 +148,7 @@ class _WakeupAndRetireWidgetState extends State<WakeupAndRetireWidget> {
|
||||
alignment: Alignment.center,
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16),
|
||||
child: Text(
|
||||
state.diary.wakeup.toString().substring(
|
||||
0,
|
||||
state.diary.wakeup.toString().length - 3,
|
||||
),
|
||||
_formatTime(state.diary.wakeup),
|
||||
style: const TextStyle(
|
||||
color: Color(0xFF6D6F71),
|
||||
fontSize: 17,
|
||||
@@ -201,10 +204,7 @@ class _WakeupAndRetireWidgetState extends State<WakeupAndRetireWidget> {
|
||||
alignment: Alignment.center,
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16),
|
||||
child: Text(
|
||||
state.diary.retire.toString().substring(
|
||||
0,
|
||||
state.diary.retire.toString().length - 3,
|
||||
),
|
||||
_formatTime(state.diary.retire),
|
||||
style: const TextStyle(
|
||||
color: Color(0xFF6D6F71),
|
||||
fontSize: 17,
|
||||
|
||||
@@ -29,6 +29,11 @@ class DiaryRepository {
|
||||
|
||||
bool get _isOnline => connectionCubit.state.isInternetAvailable;
|
||||
|
||||
/// BUG-7 fix: отрицательный ID означает, что день был создан офлайн
|
||||
/// и ещё не синхронизирован с сервером. Операции с таким ID нельзя
|
||||
/// ставить в очередь — они будут отклонены сервером.
|
||||
bool _isOfflineDiaryId(int diaryId) => diaryId < 0;
|
||||
|
||||
DiaryRepository({
|
||||
required this.diaryService,
|
||||
required this.localDataSource,
|
||||
@@ -124,6 +129,11 @@ class DiaryRepository {
|
||||
required int quantity,
|
||||
int? productNutritionalValueId,
|
||||
}) async {
|
||||
// BUG-7 fix: нельзя мутировать офлайн-день без серверного ID
|
||||
if (_isOfflineDiaryId(diaryId)) {
|
||||
throw Exception('Для добавления продукта необходим интернет (день ещё не синхронизирован)');
|
||||
}
|
||||
|
||||
final payload = {
|
||||
'diary_id': diaryId,
|
||||
'meal_id': mealId,
|
||||
@@ -175,6 +185,11 @@ class DiaryRepository {
|
||||
int? productNutritionalValueId,
|
||||
required PortionState portionState,
|
||||
}) async {
|
||||
// BUG-7 fix: нельзя мутировать офлайн-день без серверного ID
|
||||
if (_isOfflineDiaryId(diaryId)) {
|
||||
throw Exception('Для редактирования продукта необходим интернет (день ещё не синхронизирован)');
|
||||
}
|
||||
|
||||
final payload = {
|
||||
'diary_id': diaryId,
|
||||
'meal_id': mealId,
|
||||
@@ -209,6 +224,7 @@ class DiaryRepository {
|
||||
|
||||
/// Write-Behind: отметить порцию как съеденную.
|
||||
Future<void> markEaten({required int diaryId, required int mealId, required int portionId}) async {
|
||||
if (_isOfflineDiaryId(diaryId)) return; // BUG-7 fix
|
||||
final payload = {'diary_id': diaryId, 'meal_id': mealId, 'portion_id': portionId};
|
||||
|
||||
if (!_isOnline) {
|
||||
@@ -231,6 +247,7 @@ class DiaryRepository {
|
||||
|
||||
/// Write-Behind: снять отметку "съедено".
|
||||
Future<void> unmarkEaten({required int diaryId, required int mealId, required int portionId}) async {
|
||||
if (_isOfflineDiaryId(diaryId)) return; // BUG-7 fix
|
||||
final payload = {'diary_id': diaryId, 'meal_id': mealId, 'portion_id': portionId};
|
||||
|
||||
if (!_isOnline) {
|
||||
@@ -253,6 +270,7 @@ class DiaryRepository {
|
||||
|
||||
/// Write-Behind: восстановить удалённую порцию.
|
||||
Future<void> restore({required int diaryId, required int mealId, required int portionId}) async {
|
||||
if (_isOfflineDiaryId(diaryId)) return; // BUG-7 fix
|
||||
final payload = {'diary_id': diaryId, 'meal_id': mealId, 'portion_id': portionId};
|
||||
|
||||
if (!_isOnline) {
|
||||
@@ -276,6 +294,11 @@ class DiaryRepository {
|
||||
/// Write-Behind: удалить порцию из приёма пищи.
|
||||
/// Использует idempotent API вариант для предотвращения дубликатов.
|
||||
Future<void> deleteProductFromMeal({required int diaryId, required int mealId, required int portionId}) async {
|
||||
// BUG-7 fix: нельзя мутировать офлайн-день без серверного ID
|
||||
if (_isOfflineDiaryId(diaryId)) {
|
||||
throw Exception('Для удаления продукта необходим интернет (день ещё не синхронизирован)');
|
||||
}
|
||||
|
||||
final payload = {
|
||||
'diary_id': diaryId,
|
||||
'meal_id': mealId,
|
||||
@@ -309,6 +332,7 @@ class DiaryRepository {
|
||||
/// Write-Behind: загрузить фото приёма пищи.
|
||||
/// Офлайн → сохраняем файл локально и ставим в очередь.
|
||||
Future<void> uploadPhotos({required int diaryId, required int mealId, required List<File> files}) async {
|
||||
if (_isOfflineDiaryId(diaryId)) return; // BUG-7 fix
|
||||
for (var i = 0; i < files.length; i++) {
|
||||
final file = files[i];
|
||||
final payload = {'diary_id': diaryId, 'type_no': mealId};
|
||||
@@ -348,6 +372,7 @@ class DiaryRepository {
|
||||
|
||||
/// Write-Behind: удалить фото приёма пищи.
|
||||
Future<void> deletePhoto({required int diaryId, required int mealId, required DiaryPhotoModel photo}) async {
|
||||
if (_isOfflineDiaryId(diaryId)) return; // BUG-7 fix
|
||||
final payload = {'diary_id': diaryId, 'type_no': mealId, 'media_id': photo.id};
|
||||
|
||||
if (!_isOnline) {
|
||||
@@ -388,6 +413,7 @@ class DiaryRepository {
|
||||
}
|
||||
|
||||
Future<void> fillSatiety({required int diaryId, required int mealId, required int satiety}) async {
|
||||
if (_isOfflineDiaryId(diaryId)) return; // BUG-7 fix
|
||||
if (!_isOnline) {
|
||||
await localDataSource.enqueueOperation(type: 'fill_satiety', payload: {'diary_id': diaryId, 'type_no': mealId, 'satiety': satiety});
|
||||
return;
|
||||
@@ -403,6 +429,7 @@ class DiaryRepository {
|
||||
}
|
||||
|
||||
Future<void> fillMood({required int diaryId, required int mealId, required int mood}) async {
|
||||
if (_isOfflineDiaryId(diaryId)) return; // BUG-7 fix
|
||||
if (!_isOnline) {
|
||||
await localDataSource.enqueueOperation(type: 'fill_mood', payload: {'diary_id': diaryId, 'type_no': mealId, 'mood': mood});
|
||||
return;
|
||||
@@ -418,6 +445,7 @@ class DiaryRepository {
|
||||
}
|
||||
|
||||
Future<void> fillTime({required int diaryId, required int mealId, required String time}) async {
|
||||
if (_isOfflineDiaryId(diaryId)) return; // BUG-7 fix
|
||||
if (!_isOnline) {
|
||||
await localDataSource.enqueueOperation(type: 'fill_time', payload: {'diary_id': diaryId, 'type_no': mealId, 'time': time});
|
||||
return;
|
||||
@@ -433,6 +461,7 @@ class DiaryRepository {
|
||||
}
|
||||
|
||||
Future<void> fillWakeup({required int diaryId, required String time}) async {
|
||||
if (_isOfflineDiaryId(diaryId)) return; // BUG-7 fix
|
||||
if (!_isOnline) {
|
||||
await localDataSource.enqueueOperation(type: 'fill_wakeup', payload: {'diary_id': diaryId, 'wakeup': time});
|
||||
return;
|
||||
@@ -448,6 +477,7 @@ class DiaryRepository {
|
||||
}
|
||||
|
||||
Future<void> fillRetire({required int diaryId, required String time}) async {
|
||||
if (_isOfflineDiaryId(diaryId)) return; // BUG-7 fix
|
||||
if (!_isOnline) {
|
||||
await localDataSource.enqueueOperation(type: 'fill_retire', payload: {'diary_id': diaryId, 'retire': time});
|
||||
return;
|
||||
@@ -608,10 +638,12 @@ class DiaryRepository {
|
||||
final cachedDay = await localDataSource.getCachedDay(date);
|
||||
if (cachedDay == null) return;
|
||||
|
||||
// 3. Очищаем старые meals (и каскадно portions) перед записью свежих данных
|
||||
await localDataSource.clearCachedMeals(cachedDay.id);
|
||||
// BUG-6 fix: НЕ удаляем все meals разом — это приводит к потере данных
|
||||
// при ошибке записи. Вместо этого upsert-им каждый meal отдельно
|
||||
// (uniqueKeys [diaryDayId, typeNo] обеспечивают корректный upsert),
|
||||
// а порции очищаем и перезаписываем на уровне каждого meal.
|
||||
|
||||
// 4. Для каждого приёма пищи — сохраняем и его порции
|
||||
// 3. Для каждого приёма пищи — сохраняем и его порции
|
||||
for (final meal in model.meals) {
|
||||
await localDataSource.cacheMeal(
|
||||
diaryDayId: cachedDay.id,
|
||||
@@ -626,7 +658,9 @@ class DiaryRepository {
|
||||
final cachedMeal = cachedMeals.where((m) => m.typeNo == meal.typeNumber).firstOrNull;
|
||||
if (cachedMeal == null) continue;
|
||||
|
||||
// 4. Удаляем старые порции этого meal и записываем актуальные
|
||||
// 4. Очищаем порции ТОЛЬКО этого meal и записываем актуальные
|
||||
// (если запись одного meal упадёт, остальные не пострадают)
|
||||
await localDataSource.clearCachedPortions(cachedMeal.id);
|
||||
for (final portion in meal.portions) {
|
||||
await localDataSource.cachePortion(
|
||||
mealId: cachedMeal.id,
|
||||
@@ -651,6 +685,7 @@ class DiaryRepository {
|
||||
}
|
||||
} catch (e) {
|
||||
// Ошибка кэширования не должна ломать основной флоу
|
||||
Sentry.captureException(e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user