Evo-ERP/app/services/transaction_service.py
2024-11-06 02:39:48 +08:00

32 lines
968 B
Python

from ..extensions import db
from ..models.transaction import Transaction
from ..models.product import Product
class TransactionService:
@staticmethod
def get_all_transactions():
return Transaction.query.order_by(Transaction.created_at.desc()).all()
@staticmethod
def create_transaction(data):
try:
product = Product.query.get_or_404(data['product_id'])
if data['type'] == 'out' and product.quantity < data['quantity']:
raise ValueError("庫存不足")
transaction = Transaction(**data)
if data['type'] == 'in':
product.quantity += data['quantity']
else:
product.quantity -= data['quantity']
db.session.add(transaction)
db.session.commit()
return transaction
except Exception as e:
db.session.rollback()
raise ValueError(f"交易建立失敗: {str(e)}")