fix: Make transactions atomic / AutoLogout
This commit is contained in:
@@ -130,31 +130,48 @@ class DriftProductService implements ProductService {
|
||||
|
||||
@override
|
||||
Future<void> decreaseStock(String productId, int amount) async {
|
||||
final product = await getProductById(productId);
|
||||
_validateStockAmount(amount);
|
||||
|
||||
if (product == null) {
|
||||
throw Exception('Product not found');
|
||||
}
|
||||
|
||||
if (product.stockQuantity < amount) {
|
||||
throw const InsufficientStockException();
|
||||
}
|
||||
|
||||
await updateProduct(
|
||||
product.copyWith(stockQuantity: product.stockQuantity - amount),
|
||||
final updatedRows = await database.customUpdate(
|
||||
'UPDATE products '
|
||||
'SET stock_quantity = stock_quantity - ? '
|
||||
'WHERE id = ? AND stock_quantity >= ?',
|
||||
variables: [
|
||||
Variable.withInt(amount),
|
||||
Variable.withString(productId),
|
||||
Variable.withInt(amount),
|
||||
],
|
||||
updates: {database.products},
|
||||
);
|
||||
|
||||
if (updatedRows == 1) return;
|
||||
|
||||
final product = await getProductById(productId);
|
||||
if (product == null) throw Exception('Product not found');
|
||||
|
||||
throw const InsufficientStockException();
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> increaseStock(String productId, int amount) async {
|
||||
final product = await getProductById(productId);
|
||||
_validateStockAmount(amount);
|
||||
|
||||
if (product == null) {
|
||||
throw Exception('Product not found');
|
||||
}
|
||||
|
||||
await updateProduct(
|
||||
product.copyWith(stockQuantity: product.stockQuantity + amount),
|
||||
final updatedRows = await database.customUpdate(
|
||||
'UPDATE products '
|
||||
'SET stock_quantity = stock_quantity + ? '
|
||||
'WHERE id = ?',
|
||||
variables: [Variable.withInt(amount), Variable.withString(productId)],
|
||||
updates: {database.products},
|
||||
);
|
||||
|
||||
if (updatedRows == 1) return;
|
||||
|
||||
throw Exception('Product not found');
|
||||
}
|
||||
|
||||
void _validateStockAmount(int amount) {
|
||||
if (amount <= 0) {
|
||||
throw ArgumentError.value(amount, 'amount', 'Must be greater than zero');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user