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

41 lines
1.1 KiB
Python

from ..extensions import db
from ..models.product import Product
from sqlalchemy.exc import IntegrityError
from decimal import Decimal
class ProductService:
@staticmethod
def get_all_products():
return Product.query.order_by(Product.created_at.desc()).all()
@staticmethod
def get_product(product_id):
return Product.query.get_or_404(product_id)
@staticmethod
def create_product(data):
try:
product = Product(
name=data['name'],
price=data['price'],
min_quantity=data['min_quantity']
)
db.session.add(product)
db.session.commit()
return product
except IntegrityError:
db.session.rollback()
raise ValueError("商品創建失敗")
@staticmethod
def calculate_total_value(products=None):
"""計算商品總值"""
if products is None:
products = ProductService.get_all_products()
return sum(
float(product.price * Decimal(str(product.quantity)))
for product in products
)