借库逻辑实现

This commit is contained in:
dxc
2026-02-06 17:11:47 +08:00
parent 387c8973d6
commit 04ee938cd1
15 changed files with 1766 additions and 268 deletions

View File

@ -1,9 +1,8 @@
from app.extensions import db
# 引用新的模型类 StockBuy
from app.models.inbound.buy import StockBuy
from app.models.base import MaterialBase
# 尝试导入出库模型,如果不存在则忽略(防止报错影响入库功能)
# 尝试导入出库模型,如果不存在则忽略
try:
from app.models.outbound import TransOutbound
except ImportError:
@ -17,28 +16,70 @@ import json
class BuyInboundService:
# ============================================================
# 0. 辅助:唯一性校验 (核心修复)
# ============================================================
@staticmethod
def _check_unique(base_id, serial_number, batch_number, exclude_id=None):
"""
校验序列号和批号的唯一性逻辑
:param base_id: 当前物料的基础ID
:param serial_number: 序列号
:param batch_number: 批号
:param exclude_id: 排除的ID (用于编辑模式)
"""
# 1. 序列号 (SN) 全局唯一校验
# 解释: 不同规格的物料通常也不应该有相同的SN防止扫码混淆
if serial_number:
query = StockBuy.query.filter(StockBuy.serial_number == serial_number)
if exclude_id:
query = query.filter(StockBuy.id != exclude_id)
exists = query.first()
if exists:
# 获取占用该SN的物料名称提示更友好
occupied_name = exists.material.name if exists.material else "未知物料"
raise ValueError(f"序列号【{serial_number}】已存在!被物料 [{occupied_name}] 占用,请核查。")
# 2. 批号 (BN) 同物料唯一校验
# 解释: 不同规格的物料可以有相同的批号(如都有 001 批次),但同一个物料不能重复建单
if batch_number and base_id:
query = StockBuy.query.filter(
StockBuy.base_id == base_id,
StockBuy.batch_number == batch_number
)
if exclude_id:
query = query.filter(StockBuy.id != exclude_id)
if query.first():
raise ValueError(f"该物料已存在批号【{batch_number}】,请勿重复录入,可直接在该批次下追加库存。")
# ============================================================
# 1. 基础物料搜索
# ============================================================
@staticmethod
def search_base_material(keyword):
"""搜索基础物料"""
try:
query = MaterialBase.query.filter(MaterialBase.is_enabled == True)
if keyword:
query = query.filter(
or_(
MaterialBase.name.ilike(f'%{keyword}%'),
MaterialBase.spec_model.ilike(f'%{keyword}%')
MaterialBase.spec_model.ilike(f'%{keyword}%'),
MaterialBase.pinyin.ilike(f'%{keyword}%') # 假设有拼音搜索
)
)
query = query.order_by(MaterialBase.id.desc()).limit(20)
results = []
for item in query.all():
results.append({
'id': item.id, 'name': item.name, 'spec': item.spec_model,
'category': item.category, 'unit': item.unit,
'type': item.material_type, 'status': '启用'
'id': item.id,
'name': item.name,
'spec': item.spec_model, # 确保这里字段对应正确
'category': item.category,
'unit': item.unit,
'type': item.material_type,
'status': '启用'
})
return results
except Exception as e:
@ -46,76 +87,76 @@ class BuyInboundService:
return []
# ============================================================
# 2. 新增入库逻辑 (强制北京时间)
# 2. 新增入库逻辑
# ============================================================
@staticmethod
def handle_inbound(data):
"""新增入库"""
try:
base_id = data.get('base_id')
if not base_id: raise ValueError("必须选择基础物料")
material = MaterialBase.query.get(base_id)
if not material: raise ValueError("物料不存在")
if not base_id:
raise ValueError("必须选择基础物料")
# [核心修改] 获取当前北京时间 (UTC+8)
# 无论服务器在 UTC 还是其他时区,这里强制转换为 UTC+8 并去掉时区信息存入数据库
material = MaterialBase.query.get(base_id)
if not material:
raise ValueError("所选物料不存在")
# --- [修复点] 执行唯一性校验 ---
BuyInboundService._check_unique(
base_id=base_id,
serial_number=data.get('serial_number'),
batch_number=data.get('batch_number')
)
# 时间处理 (强制北京时间)
beijing_tz = timezone(timedelta(hours=8))
current_time = datetime.now(beijing_tz).replace(tzinfo=None)
in_date_val = current_time
if data.get('in_date'):
try:
date_str = str(data['in_date'])
# 如果前端传了时分秒,尝试直接解析
if len(date_str) > 10:
in_date_val = datetime.strptime(date_str, '%Y-%m-%d %H:%M:%S')
else:
# 如果只传了日期,使用该日期 + 当前北京时间的时分秒
d_temp = datetime.strptime(date_str, '%Y-%m-%d')
in_date_val = datetime(d_temp.year, d_temp.month, d_temp.day,
current_time.hour, current_time.minute, current_time.second)
except:
# 解析失败则使用当前北京时间
in_date_val = current_time
in_qty = float(data.get('in_quantity') or 0)
u_price = float(data.get('unit_price') or 0)
# [核心逻辑] 获取全局打印流水号
# 获取全局打印ID
try:
seq_sql = text("SELECT nextval('global_print_seq')")
result = db.session.execute(seq_sql)
next_global_id = result.scalar()
except Exception:
# 如果序列不存在,回退处理(或在数据库创建序列)
print("Warning: Sequence global_print_seq not found.")
except:
next_global_id = None
# SKU 生成逻辑:如果没有 ID用临时随机数或空通常应该依赖 next_global_id
# SKU 生成
if next_global_id:
generated_sku = str(next_global_id).zfill(10)
else:
generated_sku = datetime.now().strftime('%Y%m%d%H%M%S') # 降级方案
generated_sku = datetime.now().strftime('%Y%m%d%H%M%S')
final_barcode = data.get('barcode') or generated_sku
arrival_list = data.get('arrival_photo', [])
report_list = data.get('inspection_report', [])
if not isinstance(arrival_list, list): arrival_list = []
if not isinstance(report_list, list): report_list = []
new_stock = StockBuy(
base_id=material.id,
global_print_id=next_global_id,
sku=generated_sku,
barcode=final_barcode,
in_date=in_date_val, # 存入 DateTime 对象
in_date=in_date_val,
serial_number=data.get('serial_number'),
batch_number=data.get('batch_number'),
status=data.get('status', '在库'),
in_quantity=in_qty,
stock_quantity=in_qty,
stock_quantity=in_qty, # 初始库存等于入库数
available_quantity=in_qty,
inspection_status=data.get('inspection_status', '未检'),
warehouse_location=data.get('warehouse_location'),
@ -143,13 +184,27 @@ class BuyInboundService:
# ============================================================
@staticmethod
def update_inbound(stock_id, data):
"""更新入库"""
try:
stock = StockBuy.query.get(stock_id)
if not stock: raise ValueError("记录不存在")
if not stock:
raise ValueError("记录不存在")
# --- [修复点] 编辑时也要校验唯一性 (排除自身ID) ---
# 如果修改了物料(base_id)或者修改了SN/BN都需要校验
new_base_id = data.get('base_id', stock.base_id)
new_sn = data.get('serial_number', stock.serial_number)
new_bn = data.get('batch_number', stock.batch_number)
BuyInboundService._check_unique(
base_id=new_base_id,
serial_number=new_sn,
batch_number=new_bn,
exclude_id=stock_id
)
# 更新字段
field_mapping = {
'sku': 'sku', 'barcode': 'barcode',
'sku': 'sku', 'barcode': 'barcode', 'base_id': 'base_id',
'warehouse_location': 'warehouse_location',
'serial_number': 'serial_number', 'batch_number': 'batch_number',
'status': 'status', 'inspection_status': 'inspection_status',
@ -166,9 +221,9 @@ class BuyInboundService:
if 'inspection_report' in data and isinstance(data['inspection_report'], list):
stock.inspection_report = json.dumps(data['inspection_report'])
# 库存数量变更逻辑
if 'in_quantity' in data:
new_qty = float(data['in_quantity'])
# 计算差值,同步更新库存量和可用量
diff = new_qty - float(stock.in_quantity)
if diff != 0:
stock.in_quantity = new_qty
@ -190,7 +245,6 @@ class BuyInboundService:
# ============================================================
@staticmethod
def delete_inbound(stock_id):
"""删除入库"""
try:
stock = StockBuy.query.get(stock_id)
if not stock: raise ValueError("记录不存在")
@ -202,34 +256,13 @@ class BuyInboundService:
raise e
# ============================================================
# 5. 获取出库流转历史
# ============================================================
@staticmethod
def get_outbound_history(stock_id):
"""获取出库历史"""
if not TransOutbound:
return []
try:
records = TransOutbound.query.filter_by(
source_table='stock_buy', stock_id=stock_id
).order_by(TransOutbound.outbound_time.desc()).all()
return [r.to_dict() for r in records]
except:
return []
# ============================================================
# 6. 获取列表 (修改:按时间倒序排序 + 展示只显示日期)
# 5. 获取列表
# ============================================================
@staticmethod
def get_list(page, limit, keyword=None, statuses=None):
"""
获取列表
:param statuses: 状态列表 (e.g. ['在库', '借库', '已出库'])
"""
try:
query = db.session.query(StockBuy).outerjoin(MaterialBase, StockBuy.base_id == MaterialBase.id)
# 1. 关键词搜索
if keyword:
kw = f'%{keyword}%'
query = query.filter(
@ -243,23 +276,14 @@ class BuyInboundService:
)
)
# 2. 状态筛选
if not statuses:
statuses = ['在库', '借库']
if '已出库' in statuses:
# 如果明确查已出库可以包含库存为0的
query = query.filter(StockBuy.status.in_(statuses))
else:
# 默认查在库,必须保证库存 > 0
query = query.filter(
and_(
StockBuy.status.in_(statuses),
StockBuy.stock_quantity > 0
)
)
query = query.filter(and_(StockBuy.status.in_(statuses), StockBuy.stock_quantity > 0))
# [核心修改] 按照入库时间倒序排序 (从近到远)
pagination = query.order_by(StockBuy.in_date.desc()).paginate(page=page, per_page=limit, error_out=False)
current_items = pagination.items
@ -275,7 +299,6 @@ class BuyInboundService:
qty_stock = float(item.stock_quantity or 0)
qty_avail = float(item.available_quantity or 0)
# [核心修改] 格式化展示日期,去掉时分秒
date_display = ''
if item.in_date:
try:
@ -286,6 +309,7 @@ class BuyInboundService:
d = {
'id': item.id,
'base_id': item.base_id,
# 确保这里从关联的 MaterialBase 获取规格型号
'material_name': item.material.name if item.material else '',
'spec_model': item.material.spec_model if item.material else '',
'category': item.material.category if item.material else '',
@ -293,21 +317,15 @@ class BuyInboundService:
'material_type': item.material.material_type if item.material else '',
'sku': item.sku,
'inbound_date': date_display, # 前端展示用的日期字符串
'inbound_date': date_display,
'barcode': item.barcode,
'serial_number': item.serial_number,
'batch_number': item.batch_number,
'status': item.status,
'inspection_status': item.inspection_status,
'qty_inbound': float(item.in_quantity or 0),
'qty_stock': qty_stock,
'qty_available': qty_avail,
'sum_stock': qty_stock,
'sum_available': qty_avail,
'warehouse_loc': item.warehouse_location,
'unit_price': float(item.unit_price or 0),
'total_price': float(item.total_price or 0),
@ -320,8 +338,7 @@ class BuyInboundService:
'detail_link': item.detail_link,
'arrival_photo': parse_img(item.arrival_photo),
'inspection_report': parse_img(item.inspection_report),
'global_print_id': item.global_print_id,
'global_print_id_str': f"{item.global_print_id:08d}" if item.global_print_id else ""
'global_print_id': item.global_print_id
}
items.append(d)