63 lines
2.0 KiB
Python
63 lines
2.0 KiB
Python
from . import db, BaseModel
|
||
from datetime import datetime
|
||
from sqlalchemy import event
|
||
from decimal import Decimal
|
||
|
||
|
||
class Product(BaseModel):
|
||
"""商品模型"""
|
||
__tablename__ = 'products'
|
||
|
||
code = db.Column(db.String(50), unique=True, nullable=False, comment='商品代碼')
|
||
name = db.Column(db.String(100), nullable=False, comment='商品名稱')
|
||
price = db.Column(db.Numeric(10, 2), nullable=False, comment='單價')
|
||
quantity = db.Column(db.Integer, default=0, comment='庫存數量')
|
||
min_quantity = db.Column(db.Integer, default=0, comment='最低庫存量')
|
||
|
||
def __repr__(self):
|
||
return f'<Product {self.code}: {self.name}>'
|
||
|
||
@property
|
||
def stock_value(self):
|
||
"""計算庫存價值"""
|
||
return float(self.price * Decimal(str(self.quantity)))
|
||
|
||
@property
|
||
def stock_status(self):
|
||
"""獲取庫存狀態"""
|
||
if self.quantity <= self.min_quantity:
|
||
return 'danger'
|
||
return 'normal'
|
||
|
||
@staticmethod
|
||
def generate_code(prefix='P'):
|
||
"""生成商品代碼"""
|
||
# 獲取當前日期作為代碼的一部分
|
||
date_str = datetime.now().strftime('%y%m%d')
|
||
|
||
# 查詢今天的最後一個代碼
|
||
latest_product = Product.query.filter(
|
||
Product.code.like(f'{prefix}{date_str}%')
|
||
).order_by(Product.code.desc()).first()
|
||
|
||
if latest_product:
|
||
# 如果存在,則提取序號並加1
|
||
try:
|
||
serial = int(latest_product.code[-4:]) + 1
|
||
except ValueError:
|
||
serial = 1
|
||
else:
|
||
# 如果不存在,從1開始
|
||
serial = 1
|
||
|
||
# 生成新代碼(格式:P2311060001)
|
||
new_code = f'{prefix}{date_str}{serial:04d}'
|
||
return new_code
|
||
|
||
|
||
@event.listens_for(Product, 'before_insert')
|
||
def set_product_code(mapper, connection, target):
|
||
"""在插入前自動設置商品代碼"""
|
||
if not target.code:
|
||
target.code = Product.generate_code()
|