Files
KCGL/inventory-backend/app/models/inbound/service.py

70 lines
3.1 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# inventory-backend/app/models/inbound/service.py
from app.extensions import db
from datetime import datetime
class StockService(db.Model):
"""
服务权益库存表
对应数据库表: stock_service
"""
__tablename__ = 'stock_service'
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
# 关联基础物料信息
# 注意:这里使用了 db.ForeignKey 指向 material_base 表的 id
base_id = db.Column(db.Integer, db.ForeignKey('material_base.id'), nullable=False)
# 系统生成的SKU格式 SRV-YYYYMMDD-XXXX
sku = db.Column(db.String(64), unique=True, nullable=False)
# 售价
sale_price = db.Column(db.Numeric(10, 2), nullable=False)
# 服务商名称
provider_name = db.Column(db.String(255), nullable=False, default='')
# 服务详情/简介
description = db.Column(db.Text, default='')
# ==========================================================================
# 【新增】库存数量字段
# 上一轮的 Service 代码中尝试累加这两个字段,如果模型里没有,程序会报错
# ==========================================================================
actual_quantity = db.Column(db.Integer, default=0, nullable=False, comment='库存数量')
available_quantity = db.Column(db.Integer, default=0, nullable=False, comment='可用数量')
# 创建时间与更新时间
created_at = db.Column(db.DateTime, default=datetime.now, nullable=False)
updated_at = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now, nullable=False)
# 软删除标志
is_deleted = db.Column(db.Boolean, default=False, nullable=False)
# ==========================================================================
# 【修复】关系映射
# 1. 属性名必须叫 'base',因为 MaterialBase 里定义了 back_populates='base'
# 2. back_populates 指向 MaterialBase 里的属性名 'stock_services'
# ==========================================================================
base = db.relationship('MaterialBase', back_populates='stock_services', lazy='joined')
def to_dict(self):
"""转为字典,用于 API 响应"""
return {
'id': self.id,
'base_id': self.base_id,
'sku': self.sku,
'sale_price': float(self.sale_price) if self.sale_price is not None else 0,
'provider_name': self.provider_name,
'description': self.description,
'actual_quantity': self.actual_quantity, # 返回库存数
'available_quantity': self.available_quantity, # 返回可用数
'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S') if self.created_at else None,
'updated_at': self.updated_at.strftime('%Y-%m-%d %H:%M:%S') if self.updated_at else None,
# 注意:这里通过 self.base 访问关联对象,而不是 self.material_base
'material_name': self.base.name if self.base else None,
'spec_model': self.base.spec_model if self.base else None,
'unit': self.base.unit if self.base else None,
}