import 'package:flutter/widgets.dart'; import 'package:mobile_scanner/mobile_scanner.dart'; import 'package:seshat/data/repositories/bal_repository.dart'; import 'package:seshat/domain/models/bal.dart'; import 'package:seshat/domain/models/book_instance.dart'; import 'package:seshat/utils/command.dart'; import 'package:seshat/utils/result.dart'; class SellViewModel extends ChangeNotifier { SellViewModel({required BalRepository balRepository}) : _balRepository = balRepository { load = Command0(_load)..execute(); } final BalRepository _balRepository; bool _showScan = false; bool get showScan => _showScan; set showScan(bool newValue) { _showScan = newValue; notifyListeners(); } /* * =============================== * =====[ BOOKS & INSTANCES ]===== * =============================== */ final List _scannedBooks = []; List get scannedBooks => _scannedBooks; void scanBook(BarcodeCapture barcode) { final addedBook = BookInstance( balId: 5, bookId: 5, id: _scannedBooks.length, ownerId: 5, price: 5, available: true, ); _scannedBooks.add(addedBook); notifyListeners(); } void sendSell() { _scannedBooks.clear(); notifyListeners(); } void deleteBook(int id) { _scannedBooks.removeWhere((book) => book.id == id); notifyListeners(); } Future scanBook(BarcodeCapture barcode) async { int ean = int.parse(barcode.barcodes.first.rawValue!); Bal? bal = await _balRepository.ongoingBal(); _scannedBooks.clear(); final result = await _bookInstanceRepository.getByEan(bal!.id, ean); switch (result) { case Ok(): for (BookInstance instance in result.value) { Book book; final result2 = await _bookRepository.getBookById(instance.bookId); switch (result2) { case Ok(): book = result2.value; break; case Error(): continue; } Owner owner; final result3 = await _ownerRepository.getOwnerById(instance.ownerId); switch (result3) { case Ok(): owner = result3.value; break; case Error(): continue; } _scannedBooks.add( BookStack(instance: instance, book: book, owner: owner), ); } break; case Error(): break; } isScanLoaded = true; notifyListeners(); return; } /* * ================= * =====[ BAL ]===== * ================= */ Bal? _currentBal; get currentBal => _currentBal; /* * ================================= * =====[ COMMAND AND LOADING ]===== * ================================= */ late final Command0 load; bool isLoaded = false; Future> _load() async { final result1 = await _loadBal(); switch (result1) { case Ok(): isLoaded = true; break; default: break; } notifyListeners(); return result1; } Future> _loadBal() async { final result = await _balRepository.getBals(); switch (result) { case Ok(): _currentBal = result.value .where((bal) => bal.state == BalState.ongoing) .firstOrNull; break; case Error(): break; } return result; } }