part of '../database.dart'; extension ProductCrud on AppDatabase { Stream> get productsSubscription => managers.product .orderBy((o) => o.expiryDate.asc()) .withReferences((prefetch) => prefetch( category: true, storage: true, )) .watch() .asyncMap( (products) async => [ for (final (item, refs) in products) ( item, await refs.category.getSingle(), await refs.storage.getSingle(), ), ], ); Stream> get soonExpirySubscription => managers.product .filter((f) => f.expiryDate.isAfter(DateTime.now().add(const Duration(days: 3)))) .orderBy((o) => o.expiryDate.asc()) .withReferences((prefetch) => prefetch( category: true, storage: true, )) .watch() .asyncMap( (products) async => [ for (final (item, refs) in products) ( item, await refs.category.getSingle(), await refs.storage.getSingle(), ), ], ); Future addProduct({ required String name, required ProductCategoryData category, required StorageLocationData storage, required double quantity, required String unit, DateTime? purchaseDate, required DateTime expiryDate, required String barcode, }) async { await managers.product.create((c) => c( name: name, category: category.id, storage: storage.id, quantity: quantity, unit: unit, barcode: barcode, purchaseDate: Value(purchaseDate ?? DateTime.now()), expiryDate: Value(expiryDate), )); } Future updateProduct({ required int id, String? name, ProductCategoryData? category, StorageLocationData? storage, double? quantity, String? unit, DateTime? purchaseDate, DateTime? expiryDate, String? barcode, }) async { await managers.product.filter((f) => f.id(id)).update((u) => u( name: Value.absentIfNull(name), category: Value.absentIfNull(category?.id), storage: Value.absentIfNull(storage?.id), quantity: Value.absentIfNull(quantity), unit: Value.absentIfNull(unit), barcode: Value.absentIfNull(barcode), purchaseDate: Value.absentIfNull(purchaseDate), expiryDate: Value.absentIfNull(expiryDate), )); } Future deleteProduct(ProductData item) async { await managers.product.filter((f) => f.id(item.id)).delete(); } Future> getProducts() async { final products = await managers.product .orderBy((o) => o.purchaseDate.asc()) .withReferences((prefetch) => prefetch( category: true, storage: true, )) .get(); return [ for (final (item, refs) in products) ( item, await refs.category.getSingle(), await refs.storage.getSingle(), ), ]; } Future> getSoonExpiryProducts() async { final now = DateTime.now(); final today = DateTime(now.year, now.month, now.day); final products = await managers.product .filter( (f) => f.expiryDate.isBefore(today.add(const Duration(days: 3))), ) .orderBy((o) => o.expiryDate.desc()) .withReferences((prefetch) => prefetch( category: true, storage: true, )) .get(); return [ for (final (item, refs) in products) ( item, await refs.category.getSingle(), await refs.storage.getSingle(), ), ]; } }