275 lines
11 KiB
Python
275 lines
11 KiB
Python
from app.extensions import db
|
|
from app.models.inbound.buy import StockBuy
|
|
from app.models.material import MaterialBase
|
|
from datetime import datetime
|
|
from sqlalchemy import or_, func
|
|
import traceback
|
|
|
|
|
|
class BuyInboundService:
|
|
@staticmethod
|
|
def search_base_material(keyword):
|
|
try:
|
|
if not keyword:
|
|
return []
|
|
query = MaterialBase.query.filter(
|
|
MaterialBase.is_enabled == True,
|
|
or_(
|
|
MaterialBase.name.ilike(f'%{keyword}%'),
|
|
MaterialBase.spec_model.ilike(f'%{keyword}%')
|
|
)
|
|
).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': '启用'
|
|
})
|
|
return results
|
|
except Exception as e:
|
|
traceback.print_exc()
|
|
return []
|
|
|
|
@staticmethod
|
|
def handle_inbound(data):
|
|
try:
|
|
base_id = data.get('base_id')
|
|
if not base_id:
|
|
raise ValueError("必须选择基础物料进行入库 (缺少 base_id)")
|
|
|
|
material = MaterialBase.query.get(base_id)
|
|
if not material:
|
|
raise ValueError(f"ID为 {base_id} 的基础物料不存在")
|
|
|
|
in_date_val = datetime.utcnow().date()
|
|
if data.get('in_date'):
|
|
try:
|
|
if len(str(data['in_date'])) > 10:
|
|
in_date_val = datetime.strptime(str(data['in_date'])[:10], '%Y-%m-%d').date()
|
|
else:
|
|
in_date_val = datetime.strptime(str(data['in_date']), '%Y-%m-%d').date()
|
|
except ValueError:
|
|
pass
|
|
|
|
in_qty = float(data.get('in_quantity') or 0)
|
|
u_price = float(data.get('unit_price') or 0)
|
|
|
|
new_stock = StockBuy(
|
|
base_id=material.id,
|
|
sku=data.get('sku'),
|
|
in_date=in_date_val,
|
|
serial_number=data.get('serial_number'),
|
|
batch_number=data.get('batch_number'),
|
|
barcode=data.get('barcode'),
|
|
status='在库',
|
|
in_quantity=in_qty,
|
|
stock_quantity=in_qty,
|
|
available_quantity=in_qty,
|
|
inspection_status=data.get('inspection_status', '未检'),
|
|
warehouse_location=data.get('warehouse_location'),
|
|
unit_price=u_price,
|
|
total_price=in_qty * u_price,
|
|
currency=data.get('currency', 'CNY'),
|
|
exchange_rate=data.get('exchange_rate', 1.0),
|
|
supplier_name=data.get('supplier_name'),
|
|
buyer_name=data.get('purchaser'),
|
|
buyer_email=data.get('purchaser_email'),
|
|
original_link=data.get('source_link'),
|
|
detail_link=data.get('detail_link'),
|
|
arrival_photo=data.get('arrival_photo'),
|
|
remark=data.get('remark')
|
|
)
|
|
|
|
db.session.add(new_stock)
|
|
db.session.commit()
|
|
return new_stock
|
|
|
|
except Exception as e:
|
|
db.session.rollback()
|
|
raise e
|
|
|
|
@staticmethod
|
|
def update_inbound(stock_id, data):
|
|
try:
|
|
print(f"----- UPDATE DEBUG: ID={stock_id} -----")
|
|
print(f"Payload: {data}")
|
|
|
|
stock = StockBuy.query.get(stock_id)
|
|
if not stock:
|
|
raise ValueError("记录不存在")
|
|
|
|
field_mapping = {
|
|
'sku': 'sku',
|
|
'barcode': 'barcode',
|
|
'warehouse_location': 'warehouse_location',
|
|
'serial_number': 'serial_number',
|
|
'batch_number': 'batch_number',
|
|
'status': 'status',
|
|
'inspection_status': 'inspection_status',
|
|
'supplier_name': 'supplier_name',
|
|
'detail_link': 'detail_link',
|
|
'arrival_photo': 'arrival_photo',
|
|
'remark': 'remark',
|
|
'currency': 'currency',
|
|
'exchange_rate': 'exchange_rate',
|
|
'purchaser': 'buyer_name',
|
|
'purchaser_email': 'buyer_email',
|
|
'source_link': 'original_link'
|
|
}
|
|
|
|
for frontend_key, db_attr in field_mapping.items():
|
|
if frontend_key in data:
|
|
setattr(stock, db_attr, data[frontend_key])
|
|
|
|
qty_changed = False
|
|
price_changed = False
|
|
|
|
if 'in_quantity' in data:
|
|
new_qty = float(data['in_quantity'])
|
|
old_qty = float(stock.in_quantity)
|
|
if new_qty != old_qty:
|
|
diff = new_qty - old_qty
|
|
stock.in_quantity = new_qty
|
|
stock.stock_quantity = float(stock.stock_quantity) + diff
|
|
stock.available_quantity = float(stock.available_quantity) + diff
|
|
qty_changed = True
|
|
|
|
if 'unit_price' in data:
|
|
new_price = float(data['unit_price'])
|
|
old_price = float(stock.unit_price)
|
|
if new_price != old_price:
|
|
stock.unit_price = new_price
|
|
price_changed = True
|
|
|
|
if qty_changed or price_changed:
|
|
stock.total_price = float(stock.in_quantity) * float(stock.unit_price)
|
|
|
|
db.session.commit()
|
|
print("----- UPDATE SUCCESS -----")
|
|
return stock
|
|
|
|
except Exception as e:
|
|
db.session.rollback()
|
|
print(f"----- UPDATE FAILED: {str(e)} -----")
|
|
traceback.print_exc()
|
|
raise e
|
|
|
|
@staticmethod
|
|
def delete_inbound(stock_id):
|
|
try:
|
|
stock = StockBuy.query.get(stock_id)
|
|
if not stock:
|
|
raise ValueError("记录不存在")
|
|
db.session.delete(stock)
|
|
db.session.commit()
|
|
return True
|
|
except Exception as e:
|
|
db.session.rollback()
|
|
raise e
|
|
|
|
@staticmethod
|
|
def get_list(page, limit, keyword=None):
|
|
try:
|
|
# 1. 查询分页数据
|
|
query = db.session.query(StockBuy).outerjoin(MaterialBase, StockBuy.base_id == MaterialBase.id)
|
|
|
|
if keyword:
|
|
query = query.filter(
|
|
or_(
|
|
MaterialBase.name.ilike(f'%{keyword}%'),
|
|
MaterialBase.spec_model.ilike(f'%{keyword}%'),
|
|
StockBuy.batch_number.ilike(f'%{keyword}%'),
|
|
StockBuy.serial_number.ilike(f'%{keyword}%'),
|
|
StockBuy.sku.ilike(f'%{keyword}%')
|
|
)
|
|
)
|
|
|
|
pagination = query.order_by(StockBuy.id.desc()).paginate(page=page, per_page=limit, error_out=False)
|
|
|
|
# ---------------------------------------------------------------------
|
|
# 新增逻辑:计算总库存
|
|
# ---------------------------------------------------------------------
|
|
# 2. 提取当前页所有涉及的 base_id
|
|
current_items = pagination.items
|
|
base_ids = list(set([item.base_id for item in current_items if item.base_id]))
|
|
|
|
# 3. 聚合查询:一次性查出这些 base_id 对应的 stock_quantity 和 available_quantity 总和
|
|
stock_map = {}
|
|
if base_ids:
|
|
# SELECT base_id, SUM(stock_quantity), SUM(available_quantity) FROM stock_buy WHERE base_id IN (...) GROUP BY base_id
|
|
aggregates = db.session.query(
|
|
StockBuy.base_id,
|
|
func.sum(StockBuy.stock_quantity).label('total_stock'),
|
|
func.sum(StockBuy.available_quantity).label('total_avail')
|
|
).filter(StockBuy.base_id.in_(base_ids)).group_by(StockBuy.base_id).all()
|
|
|
|
for agg in aggregates:
|
|
stock_map[agg.base_id] = {
|
|
'total_stock': float(agg.total_stock or 0),
|
|
'total_avail': float(agg.total_avail or 0)
|
|
}
|
|
# ---------------------------------------------------------------------
|
|
|
|
items = []
|
|
for item in current_items:
|
|
mat_name = item.material.name if item.material else '未知物料'
|
|
mat_spec = item.material.spec_model if item.material else ''
|
|
mat_cat = item.material.category if item.material else ''
|
|
mat_unit = item.material.unit if item.material else ''
|
|
mat_type = item.material.material_type if item.material else ''
|
|
|
|
# 获取该物料的统计数据
|
|
stats = stock_map.get(item.base_id, {'total_stock': 0, 'total_avail': 0})
|
|
|
|
d = {
|
|
'id': item.id,
|
|
'base_id': item.base_id,
|
|
'material_name': mat_name,
|
|
'spec_model': mat_spec,
|
|
'category': mat_cat,
|
|
'unit': mat_unit,
|
|
'material_type': mat_type,
|
|
|
|
'sku': item.sku,
|
|
'inbound_date': str(item.in_date) if item.in_date else '',
|
|
'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': float(item.stock_quantity or 0),
|
|
'qty_available': float(item.available_quantity or 0),
|
|
|
|
# --- [新增] 聚合统计数据 (用于列表显示) ---
|
|
'sum_stock': stats['total_stock'],
|
|
'sum_available': stats['total_avail'],
|
|
|
|
'warehouse_loc': item.warehouse_location,
|
|
'unit_price': float(item.unit_price or 0),
|
|
'total_price': float(item.total_price or 0),
|
|
'currency': item.currency,
|
|
'exchange_rate': float(item.exchange_rate or 1),
|
|
'supplier_name': item.supplier_name,
|
|
'purchaser': item.buyer_name,
|
|
'purchaser_email': item.buyer_email,
|
|
'source_link': item.original_link,
|
|
'detail_link': item.detail_link,
|
|
'arrival_photo': item.arrival_photo,
|
|
'remark': item.remark
|
|
}
|
|
items.append(d)
|
|
|
|
return {"total": pagination.total, "items": items}
|
|
except Exception as e:
|
|
print(f"List Error: {e}")
|
|
traceback.print_exc()
|
|
return {"total": 0, "items": []} |