forked from eatvio/eatvio_app
feat(diary): fixes
This commit is contained in:
@@ -9,6 +9,7 @@ import 'package:eatvio_app/core/interceptors/token_interceptor.dart';
|
||||
import 'package:eatvio_app/core/local_db/app_database.dart';
|
||||
import 'package:eatvio_app/core/local_db/dao/diary_dao.dart';
|
||||
import 'package:eatvio_app/core/local_db/dao/glossary_dao.dart';
|
||||
import 'package:eatvio_app/core/local_db/dao/media_dao.dart';
|
||||
import 'package:eatvio_app/core/local_db/dao/pending_ops_dao.dart';
|
||||
import 'package:eatvio_app/core/local_db/dao/sync_meta_dao.dart';
|
||||
import 'package:eatvio_app/core/local_db/diary_local_data_source.dart';
|
||||
@@ -53,12 +54,14 @@ class ExternalRegistrations {
|
||||
sl.registerLazySingleton<AppDatabase>(() => AppDatabase());
|
||||
sl.registerLazySingleton<DiaryDao>(() => sl<AppDatabase>().diaryDao);
|
||||
sl.registerLazySingleton<GlossaryDao>(() => sl<AppDatabase>().glossaryDao);
|
||||
sl.registerLazySingleton<MediaDao>(() => sl<AppDatabase>().mediaDao);
|
||||
sl.registerLazySingleton<PendingOpsDao>(() => sl<AppDatabase>().pendingOpsDao);
|
||||
sl.registerLazySingleton<SyncMetaDao>(() => sl<AppDatabase>().syncMetaDao);
|
||||
sl.registerLazySingleton<DiaryLocalDataSource>(
|
||||
() => DiaryLocalDataSource(
|
||||
diaryDao: sl(),
|
||||
glossaryDao: sl(),
|
||||
mediaDao: sl(),
|
||||
pendingOpsDao: sl(),
|
||||
syncMetaDao: sl(),
|
||||
),
|
||||
|
||||
@@ -2,11 +2,13 @@ import 'package:drift/drift.dart';
|
||||
import 'package:drift_flutter/drift_flutter.dart';
|
||||
import 'dao/diary_dao.dart';
|
||||
import 'dao/glossary_dao.dart';
|
||||
import 'dao/media_dao.dart';
|
||||
import 'dao/pending_ops_dao.dart';
|
||||
import 'dao/sync_meta_dao.dart';
|
||||
import 'tables/diary_days_table.dart';
|
||||
import 'tables/glossary_cache_table.dart';
|
||||
import 'tables/meals_table.dart';
|
||||
import 'tables/media_table.dart';
|
||||
import 'tables/pending_operations_table.dart';
|
||||
import 'tables/portions_table.dart';
|
||||
import 'tables/sync_meta_table.dart';
|
||||
@@ -23,12 +25,14 @@ part 'app_database.g.dart';
|
||||
GlossaryCacheTable,
|
||||
PendingOperationsTable,
|
||||
SyncMetaTable,
|
||||
MediaTable,
|
||||
],
|
||||
daos: [
|
||||
DiaryDao,
|
||||
GlossaryDao,
|
||||
PendingOpsDao,
|
||||
SyncMetaDao,
|
||||
MediaDao,
|
||||
],
|
||||
)
|
||||
class AppDatabase extends _$AppDatabase {
|
||||
@@ -38,7 +42,7 @@ class AppDatabase extends _$AppDatabase {
|
||||
AppDatabase.forTesting(super.executor);
|
||||
|
||||
@override
|
||||
int get schemaVersion => 2;
|
||||
int get schemaVersion => 3;
|
||||
|
||||
@override
|
||||
MigrationStrategy get migration => MigrationStrategy(
|
||||
@@ -58,6 +62,10 @@ class AppDatabase extends _$AppDatabase {
|
||||
);
|
||||
} catch (_) {}
|
||||
}
|
||||
if (from < 3) {
|
||||
// Таблица медиа для фото дневника (добавлена в v3)
|
||||
await m.createTable(mediaTable);
|
||||
}
|
||||
},
|
||||
beforeOpen: (details) async {
|
||||
// WAL mode — позволяет параллельные чтение/запись из разных изолятов
|
||||
|
||||
31
lib/core/local_db/dao/media_dao.dart
Normal file
31
lib/core/local_db/dao/media_dao.dart
Normal file
@@ -0,0 +1,31 @@
|
||||
import 'package:drift/drift.dart';
|
||||
import 'package:eatvio_app/core/local_db/app_database.dart';
|
||||
import 'package:eatvio_app/core/local_db/tables/media_table.dart';
|
||||
|
||||
part 'media_dao.g.dart';
|
||||
|
||||
/// DAO для работы с медиа-файлами (фото) приёмов пищи в локальной БД.
|
||||
@DriftAccessor(tables: [MediaTable])
|
||||
class MediaDao extends DatabaseAccessor<AppDatabase> with _$MediaDaoMixin {
|
||||
MediaDao(super.db);
|
||||
|
||||
/// Получить все медиа для конкретного meal.
|
||||
Future<List<MediaTableData>> getMediaForMeal(int mealId) {
|
||||
return (select(db.mediaTable)..where((t) => t.mealId.equals(mealId))).get();
|
||||
}
|
||||
|
||||
/// Вставить или обновить медиа-запись.
|
||||
Future<int> upsertMedia(MediaTableCompanion media) {
|
||||
return into(db.mediaTable).insertOnConflictUpdate(media);
|
||||
}
|
||||
|
||||
/// Удалить все медиа для конкретного meal.
|
||||
Future<void> clearMediaForMeal(int mealId) async {
|
||||
await (delete(db.mediaTable)..where((t) => t.mealId.equals(mealId))).go();
|
||||
}
|
||||
|
||||
/// Удалить конкретную медиа-запись по серверному ID.
|
||||
Future<void> deleteByServerId(int serverId) async {
|
||||
await (delete(db.mediaTable)..where((t) => t.serverId.equals(serverId))).go();
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import 'package:drift/drift.dart';
|
||||
import 'package:eatvio_app/core/local_db/app_database.dart';
|
||||
import 'package:eatvio_app/core/local_db/dao/diary_dao.dart';
|
||||
import 'package:eatvio_app/core/local_db/dao/glossary_dao.dart';
|
||||
import 'package:eatvio_app/core/local_db/dao/media_dao.dart';
|
||||
import 'package:eatvio_app/core/local_db/dao/pending_ops_dao.dart';
|
||||
import 'package:eatvio_app/core/local_db/dao/sync_meta_dao.dart';
|
||||
import 'package:uuid/uuid.dart';
|
||||
@@ -12,6 +13,7 @@ import 'package:uuid/uuid.dart';
|
||||
class DiaryLocalDataSource {
|
||||
final DiaryDao _diaryDao;
|
||||
final GlossaryDao _glossaryDao;
|
||||
final MediaDao _mediaDao;
|
||||
final PendingOpsDao _pendingOpsDao;
|
||||
final SyncMetaDao _syncMetaDao;
|
||||
final _uuid = const Uuid();
|
||||
@@ -19,10 +21,12 @@ class DiaryLocalDataSource {
|
||||
DiaryLocalDataSource({
|
||||
required DiaryDao diaryDao,
|
||||
required GlossaryDao glossaryDao,
|
||||
required MediaDao mediaDao,
|
||||
required PendingOpsDao pendingOpsDao,
|
||||
required SyncMetaDao syncMetaDao,
|
||||
}) : _diaryDao = diaryDao,
|
||||
_glossaryDao = glossaryDao,
|
||||
_mediaDao = mediaDao,
|
||||
_pendingOpsDao = pendingOpsDao,
|
||||
_syncMetaDao = syncMetaDao;
|
||||
|
||||
@@ -185,6 +189,33 @@ class DiaryLocalDataSource {
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Медиа (фото дневника) ─────────────────────────────────────────────
|
||||
|
||||
Future<List<MediaTableData>> getCachedMedia(int mealId) {
|
||||
return _mediaDao.getMediaForMeal(mealId);
|
||||
}
|
||||
|
||||
Future<void> cacheMedia({
|
||||
required int mealId,
|
||||
int? serverId,
|
||||
String? url,
|
||||
String? localPath,
|
||||
String status = 'synced',
|
||||
}) async {
|
||||
await _mediaDao.upsertMedia(MediaTableCompanion(
|
||||
mealId: Value(mealId),
|
||||
serverId: Value(serverId),
|
||||
url: Value(url),
|
||||
localPath: Value(localPath),
|
||||
status: Value(status),
|
||||
createdAt: Value(DateTime.now().toIso8601String()),
|
||||
));
|
||||
}
|
||||
|
||||
Future<void> clearCachedMedia(int mealId) {
|
||||
return _mediaDao.clearMediaForMeal(mealId);
|
||||
}
|
||||
|
||||
// ─── Утилиты ─────────────────────────────────────────────────────────────
|
||||
|
||||
String _encodePayload(Map<String, dynamic> payload) {
|
||||
|
||||
@@ -156,6 +156,44 @@ class DiarySyncRunner {
|
||||
portionModel: payload['portion_id'] as int,
|
||||
);
|
||||
|
||||
case 'update_portion':
|
||||
final data = <String, dynamic>{
|
||||
'product_name': payload['product_name'] as String,
|
||||
'portion': payload['portion'] as String,
|
||||
'quantity': payload['quantity'] as int,
|
||||
};
|
||||
if (payload['product_nutritional_value_id'] != null) {
|
||||
data['product_nutritional_value_id'] = payload['product_nutritional_value_id'] as int;
|
||||
}
|
||||
data['state'] = payload['state'] as String;
|
||||
await _diaryService.updateProductInMeal(
|
||||
diary: payload['diary_id'] as int,
|
||||
typeNo: payload['meal_id'] as int,
|
||||
portionModel: payload['portion_id'] as int,
|
||||
productInMeal: data,
|
||||
);
|
||||
|
||||
case 'mark_eaten':
|
||||
await _diaryService.markEaten(
|
||||
diary: payload['diary_id'] as int,
|
||||
typeNo: payload['meal_id'] as int,
|
||||
portionModel: payload['portion_id'] as int,
|
||||
);
|
||||
|
||||
case 'unmark_eaten':
|
||||
await _diaryService.unmarkEaten(
|
||||
diary: payload['diary_id'] as int,
|
||||
typeNo: payload['meal_id'] as int,
|
||||
portionModel: payload['portion_id'] as int,
|
||||
);
|
||||
|
||||
case 'restore':
|
||||
await _diaryService.restore(
|
||||
diary: payload['diary_id'] as int,
|
||||
typeNo: payload['meal_id'] as int,
|
||||
portionModel: payload['portion_id'] as int,
|
||||
);
|
||||
|
||||
case 'fill_satiety':
|
||||
await _diaryService.fillSatiety(
|
||||
diary: payload['diary_id'] as int,
|
||||
|
||||
35
lib/core/local_db/tables/media_table.dart
Normal file
35
lib/core/local_db/tables/media_table.dart
Normal file
@@ -0,0 +1,35 @@
|
||||
import 'package:drift/drift.dart';
|
||||
import 'meals_table.dart';
|
||||
|
||||
/// Кэш медиа-файлов (фото) приёмов пищи.
|
||||
/// Хранит мета-данные фотографий для офлайн-доступа.
|
||||
///
|
||||
/// status:
|
||||
/// 'synced' — фото загружено на сервер
|
||||
/// 'pending_upload' — фото создано офлайн, ожидает загрузки
|
||||
/// 'pending_delete' — фото помечено на удаление, ожидает синхронизации
|
||||
class MediaTable extends Table {
|
||||
@override
|
||||
String get tableName => 'media';
|
||||
|
||||
IntColumn get id => integer().autoIncrement()();
|
||||
|
||||
// Ссылка на локальный приём пищи
|
||||
IntColumn get mealId => integer().named('meal_id')
|
||||
.references(MealsTable, #id, onDelete: KeyAction.cascade)();
|
||||
|
||||
// ID записи на сервере (null до синхронизации)
|
||||
IntColumn get serverId => integer().nullable().named('server_id')();
|
||||
|
||||
// URL фото на сервере (null для неотправленных)
|
||||
TextColumn get url => text().nullable()();
|
||||
|
||||
// Локальный путь к файлу (null для фото только с сервера)
|
||||
TextColumn get localPath => text().nullable().named('local_path')();
|
||||
|
||||
// Статус синхронизации: 'synced', 'pending_upload', 'pending_delete'
|
||||
TextColumn get status => text().withDefault(const Constant('synced'))();
|
||||
|
||||
// Время создания записи (ISO 8601 string)
|
||||
TextColumn get createdAt => text().named('created_at')();
|
||||
}
|
||||
Reference in New Issue
Block a user