对于成品的条形码进行功能实现
This commit is contained in:
@ -1,11 +1,14 @@
|
|||||||
|
# inventory-backend/app/api/v1/inbound/product.py
|
||||||
from flask import Blueprint, request, jsonify
|
from flask import Blueprint, request, jsonify
|
||||||
# 引用更名后的服务
|
|
||||||
from app.services.inbound.product_service import ProductInboundService
|
from app.services.inbound.product_service import ProductInboundService
|
||||||
import traceback
|
import traceback
|
||||||
|
|
||||||
# 蓝图命名改为 inbound_product_bp
|
|
||||||
inbound_product_bp = Blueprint('inbound_product', __name__)
|
inbound_product_bp = Blueprint('inbound_product', __name__)
|
||||||
|
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# 0. 基础物料搜索
|
||||||
|
# ------------------------------------------------------------------
|
||||||
@inbound_product_bp.route('/search-base', methods=['GET'])
|
@inbound_product_bp.route('/search-base', methods=['GET'])
|
||||||
def search_base():
|
def search_base():
|
||||||
try:
|
try:
|
||||||
@ -14,6 +17,10 @@ def search_base():
|
|||||||
except Exception as e:
|
except Exception as e:
|
||||||
return jsonify({"code": 500, "msg": str(e)}), 500
|
return jsonify({"code": 500, "msg": str(e)}), 500
|
||||||
|
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# 1. 获取列表
|
||||||
|
# ------------------------------------------------------------------
|
||||||
@inbound_product_bp.route('/list', methods=['GET'])
|
@inbound_product_bp.route('/list', methods=['GET'])
|
||||||
def get_list():
|
def get_list():
|
||||||
try:
|
try:
|
||||||
@ -25,14 +32,30 @@ def get_list():
|
|||||||
except Exception as e:
|
except Exception as e:
|
||||||
return jsonify({"code": 500, "msg": str(e)}), 500
|
return jsonify({"code": 500, "msg": str(e)}), 500
|
||||||
|
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# 2. 新增入库 (修改:返回创建的对象数据,用于打印)
|
||||||
|
# ------------------------------------------------------------------
|
||||||
@inbound_product_bp.route('/submit', methods=['POST'])
|
@inbound_product_bp.route('/submit', methods=['POST'])
|
||||||
def submit():
|
def submit():
|
||||||
try:
|
try:
|
||||||
ProductInboundService.handle_inbound(request.get_json())
|
# 调用 Service 处理入库,获取新创建的对象
|
||||||
return jsonify({"code": 200, "msg": "入库成功"})
|
new_stock = ProductInboundService.handle_inbound(request.get_json())
|
||||||
|
|
||||||
|
# 返回成功信息以及新创建的数据(包含生成的ID和SKU),供前端打印使用
|
||||||
|
return jsonify({
|
||||||
|
"code": 200,
|
||||||
|
"msg": "入库成功",
|
||||||
|
"data": new_stock.to_dict()
|
||||||
|
})
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
|
traceback.print_exc()
|
||||||
return jsonify({"code": 500, "msg": str(e)}), 500
|
return jsonify({"code": 500, "msg": str(e)}), 500
|
||||||
|
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# 3. 更新入库
|
||||||
|
# ------------------------------------------------------------------
|
||||||
@inbound_product_bp.route('/<int:id>', methods=['PUT'])
|
@inbound_product_bp.route('/<int:id>', methods=['PUT'])
|
||||||
def update(id):
|
def update(id):
|
||||||
try:
|
try:
|
||||||
@ -41,6 +64,10 @@ def update(id):
|
|||||||
except Exception as e:
|
except Exception as e:
|
||||||
return jsonify({"code": 500, "msg": str(e)}), 500
|
return jsonify({"code": 500, "msg": str(e)}), 500
|
||||||
|
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# 4. 删除
|
||||||
|
# ------------------------------------------------------------------
|
||||||
@inbound_product_bp.route('/<int:id>', methods=['DELETE'])
|
@inbound_product_bp.route('/<int:id>', methods=['DELETE'])
|
||||||
def delete(id):
|
def delete(id):
|
||||||
try:
|
try:
|
||||||
|
|||||||
@ -12,11 +12,12 @@ class StockProduct(db.Model):
|
|||||||
id = db.Column(db.Integer, primary_key=True)
|
id = db.Column(db.Integer, primary_key=True)
|
||||||
base_id = db.Column(db.Integer, db.ForeignKey('material_base.id'), nullable=False)
|
base_id = db.Column(db.Integer, db.ForeignKey('material_base.id'), nullable=False)
|
||||||
|
|
||||||
|
# 身份标识
|
||||||
sku = db.Column(db.String(100))
|
sku = db.Column(db.String(100))
|
||||||
production_date = db.Column(db.Date)
|
production_date = db.Column(db.Date)
|
||||||
barcode = db.Column(db.String(100))
|
barcode = db.Column(db.String(100))
|
||||||
serial_number = db.Column(db.String(100))
|
serial_number = db.Column(db.String(100))
|
||||||
# SQL 无 batch_number
|
# Note: 成品通常按SN管理,SQL定义无 batch_number
|
||||||
|
|
||||||
# 数量
|
# 数量
|
||||||
in_quantity = db.Column(db.Numeric(19, 4), default=0)
|
in_quantity = db.Column(db.Numeric(19, 4), default=0)
|
||||||
@ -48,6 +49,9 @@ class StockProduct(db.Model):
|
|||||||
inspection_report_link = db.Column(db.Text)
|
inspection_report_link = db.Column(db.Text)
|
||||||
order_id = db.Column(db.String(100))
|
order_id = db.Column(db.String(100))
|
||||||
|
|
||||||
|
# [新增] 全局打印流水号 (用于跨表连续编号,对应 Sequence: global_print_seq)
|
||||||
|
global_print_id = db.Column(db.Integer)
|
||||||
|
|
||||||
# 关系定义
|
# 关系定义
|
||||||
material = db.relationship('MaterialBase', back_populates='stock_products')
|
material = db.relationship('MaterialBase', back_populates='stock_products')
|
||||||
|
|
||||||
@ -98,5 +102,9 @@ class StockProduct(db.Model):
|
|||||||
|
|
||||||
'sale_price': float(self.sale_price or 0),
|
'sale_price': float(self.sale_price or 0),
|
||||||
'inspection_report_link': self.inspection_report_link,
|
'inspection_report_link': self.inspection_report_link,
|
||||||
'order_id': self.order_id
|
'order_id': self.order_id,
|
||||||
|
|
||||||
|
# [新增] 返回全局打印ID及其格式化字符串
|
||||||
|
'global_print_id': self.global_print_id,
|
||||||
|
'global_print_id_str': f"{self.global_print_id:010d}" if self.global_print_id else ""
|
||||||
}
|
}
|
||||||
@ -1,9 +1,9 @@
|
|||||||
|
# app/services/inbound/product_service.py
|
||||||
from app.extensions import db
|
from app.extensions import db
|
||||||
from app.models.base import MaterialBase
|
from app.models.base import MaterialBase
|
||||||
# 引用新的 product 路径
|
|
||||||
from app.models.inbound.product import StockProduct
|
from app.models.inbound.product import StockProduct
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from sqlalchemy import or_, func
|
from sqlalchemy import or_, func, text
|
||||||
import traceback
|
import traceback
|
||||||
|
|
||||||
|
|
||||||
@ -11,11 +11,16 @@ class ProductInboundService:
|
|||||||
@staticmethod
|
@staticmethod
|
||||||
def search_base_material(keyword):
|
def search_base_material(keyword):
|
||||||
try:
|
try:
|
||||||
if not keyword: return []
|
if not keyword:
|
||||||
query = MaterialBase.query.filter(
|
# 如果没有关键词,返回最新的20条
|
||||||
MaterialBase.is_enabled == True,
|
query = MaterialBase.query.filter(MaterialBase.is_enabled == True).order_by(
|
||||||
or_(MaterialBase.name.ilike(f'%{keyword}%'), MaterialBase.spec_model.ilike(f'%{keyword}%'))
|
MaterialBase.id.desc()).limit(20)
|
||||||
).limit(20)
|
else:
|
||||||
|
query = MaterialBase.query.filter(
|
||||||
|
MaterialBase.is_enabled == True,
|
||||||
|
or_(MaterialBase.name.ilike(f'%{keyword}%'), MaterialBase.spec_model.ilike(f'%{keyword}%'))
|
||||||
|
).limit(20)
|
||||||
|
|
||||||
results = []
|
results = []
|
||||||
for item in query.all():
|
for item in query.all():
|
||||||
results.append({
|
results.append({
|
||||||
@ -23,7 +28,8 @@ class ProductInboundService:
|
|||||||
'category': item.category, 'unit': item.unit, 'type': item.material_type
|
'category': item.category, 'unit': item.unit, 'type': item.material_type
|
||||||
})
|
})
|
||||||
return results
|
return results
|
||||||
except:
|
except Exception:
|
||||||
|
traceback.print_exc()
|
||||||
return []
|
return []
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
@ -37,21 +43,47 @@ class ProductInboundService:
|
|||||||
in_date_val = datetime.utcnow().date()
|
in_date_val = datetime.utcnow().date()
|
||||||
if data.get('in_date'):
|
if data.get('in_date'):
|
||||||
try:
|
try:
|
||||||
in_date_val = datetime.strptime(str(data['in_date'])[:10], '%Y-%m-%d').date()
|
# 兼容字符串格式日期处理
|
||||||
|
date_str = str(data['in_date'])
|
||||||
|
if len(date_str) > 10:
|
||||||
|
date_str = date_str[:10]
|
||||||
|
in_date_val = datetime.strptime(date_str, '%Y-%m-%d').date()
|
||||||
except:
|
except:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
in_qty = float(data.get('in_quantity') or 0)
|
in_qty = float(data.get('in_quantity') or 0)
|
||||||
|
|
||||||
|
# 处理生产时间范围
|
||||||
p_start = data.get('production_start_time', '')
|
p_start = data.get('production_start_time', '')
|
||||||
p_end = data.get('production_end_time', '')
|
p_end = data.get('production_end_time', '')
|
||||||
time_range = f"{p_start} ~ {p_end}" if p_start or p_end else None
|
time_range = f"{p_start} ~ {p_end}" if p_start or p_end else None
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# 1. 获取全局打印流水号 (跨表唯一,用于打印逻辑)
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
seq_sql = text("SELECT nextval('global_print_seq')")
|
||||||
|
result = db.session.execute(seq_sql)
|
||||||
|
next_global_id = result.scalar()
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# 2. 自动生成 SKU (格式: 10位数字,补零)
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
generated_sku = str(next_global_id).zfill(10)
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# 3. 条码逻辑处理
|
||||||
|
# 如果前端没传条码,则默认使用 SKU 作为条码
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
final_barcode = data.get('barcode')
|
||||||
|
if not final_barcode:
|
||||||
|
final_barcode = generated_sku
|
||||||
|
|
||||||
new_stock = StockProduct(
|
new_stock = StockProduct(
|
||||||
base_id=material.id,
|
base_id=material.id,
|
||||||
sku=data.get('sku'),
|
global_print_id=next_global_id, # 新增全局打印ID
|
||||||
|
sku=generated_sku, # 使用自动生成的SKU
|
||||||
production_date=in_date_val,
|
production_date=in_date_val,
|
||||||
barcode=data.get('barcode'),
|
barcode=final_barcode,
|
||||||
serial_number=data.get('serial_number'),
|
serial_number=data.get('serial_number'),
|
||||||
|
|
||||||
status='在库',
|
status='在库',
|
||||||
@ -81,6 +113,8 @@ class ProductInboundService:
|
|||||||
|
|
||||||
db.session.add(new_stock)
|
db.session.add(new_stock)
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
|
|
||||||
|
# 返回对象实例以便上层调用 to_dict()
|
||||||
return new_stock
|
return new_stock
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
db.session.rollback()
|
db.session.rollback()
|
||||||
@ -92,8 +126,9 @@ class ProductInboundService:
|
|||||||
stock = StockProduct.query.get(stock_id)
|
stock = StockProduct.query.get(stock_id)
|
||||||
if not stock: raise ValueError("记录不存在")
|
if not stock: raise ValueError("记录不存在")
|
||||||
|
|
||||||
|
# 允许更新的字段列表
|
||||||
fields = [
|
fields = [
|
||||||
'sku', 'barcode', 'serial_number', 'warehouse_location',
|
'barcode', 'serial_number', 'warehouse_location',
|
||||||
'status', 'quality_status', 'bom_code', 'bom_version',
|
'status', 'quality_status', 'bom_code', 'bom_version',
|
||||||
'work_order_code', 'production_manager', 'quality_report_link',
|
'work_order_code', 'production_manager', 'quality_report_link',
|
||||||
'detail_link', 'inspection_report_link', 'order_id'
|
'detail_link', 'inspection_report_link', 'order_id'
|
||||||
@ -101,22 +136,31 @@ class ProductInboundService:
|
|||||||
for f in fields:
|
for f in fields:
|
||||||
if f in data: setattr(stock, f, data[f])
|
if f in data: setattr(stock, f, data[f])
|
||||||
|
|
||||||
|
# 数值类型处理
|
||||||
if 'sale_price' in data: stock.sale_price = float(data['sale_price'])
|
if 'sale_price' in data: stock.sale_price = float(data['sale_price'])
|
||||||
if 'raw_material_cost' in data: stock.raw_material_cost = float(data['raw_material_cost'])
|
if 'raw_material_cost' in data: stock.raw_material_cost = float(data['raw_material_cost'])
|
||||||
if 'manual_cost' in data: stock.manual_cost = float(data['manual_cost'])
|
if 'manual_cost' in data: stock.manual_cost = float(data['manual_cost'])
|
||||||
|
|
||||||
|
# 数量更新逻辑 (同步更新库存和可用量)
|
||||||
if 'in_quantity' in data:
|
if 'in_quantity' in data:
|
||||||
new_qty = float(data['in_quantity'])
|
new_qty = float(data['in_quantity'])
|
||||||
diff = new_qty - float(stock.in_quantity)
|
old_qty = float(stock.in_quantity)
|
||||||
stock.in_quantity = new_qty
|
if new_qty != old_qty:
|
||||||
stock.stock_quantity = float(stock.stock_quantity) + diff
|
diff = new_qty - old_qty
|
||||||
stock.available_quantity = float(stock.available_quantity) + diff
|
stock.in_quantity = new_qty
|
||||||
|
stock.stock_quantity = float(stock.stock_quantity) + diff
|
||||||
|
stock.available_quantity = float(stock.available_quantity) + diff
|
||||||
|
|
||||||
|
# 时间范围处理
|
||||||
if 'production_start_time' in data or 'production_end_time' in data:
|
if 'production_start_time' in data or 'production_end_time' in data:
|
||||||
old_range = stock.production_time_range or " ~ "
|
old_range = stock.production_time_range or " ~ "
|
||||||
parts = old_range.split(' ~ ')
|
parts = old_range.split(' ~ ')
|
||||||
start = data.get('production_start_time', parts[0] if len(parts) > 0 else '')
|
# 获取原值防止越界
|
||||||
end = data.get('production_end_time', parts[1] if len(parts) > 1 else '')
|
old_start = parts[0] if len(parts) > 0 else ''
|
||||||
|
old_end = parts[1] if len(parts) > 1 else ''
|
||||||
|
|
||||||
|
start = data.get('production_start_time', old_start)
|
||||||
|
end = data.get('production_end_time', old_end)
|
||||||
stock.production_time_range = f"{start} ~ {end}"
|
stock.production_time_range = f"{start} ~ {end}"
|
||||||
|
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
@ -132,6 +176,7 @@ class ProductInboundService:
|
|||||||
if stock:
|
if stock:
|
||||||
db.session.delete(stock)
|
db.session.delete(stock)
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
|
return True
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
db.session.rollback()
|
db.session.rollback()
|
||||||
raise e
|
raise e
|
||||||
@ -139,17 +184,24 @@ class ProductInboundService:
|
|||||||
@staticmethod
|
@staticmethod
|
||||||
def get_list(page, limit, keyword=None):
|
def get_list(page, limit, keyword=None):
|
||||||
try:
|
try:
|
||||||
|
# 联表查询
|
||||||
query = db.session.query(StockProduct).outerjoin(MaterialBase, StockProduct.base_id == MaterialBase.id)
|
query = db.session.query(StockProduct).outerjoin(MaterialBase, StockProduct.base_id == MaterialBase.id)
|
||||||
|
|
||||||
if keyword:
|
if keyword:
|
||||||
query = query.filter(or_(
|
query = query.filter(or_(
|
||||||
MaterialBase.name.ilike(f'%{keyword}%'),
|
MaterialBase.name.ilike(f'%{keyword}%'),
|
||||||
|
MaterialBase.spec_model.ilike(f'%{keyword}%'),
|
||||||
StockProduct.serial_number.ilike(f'%{keyword}%'),
|
StockProduct.serial_number.ilike(f'%{keyword}%'),
|
||||||
StockProduct.work_order_code.ilike(f'%{keyword}%'),
|
StockProduct.work_order_code.ilike(f'%{keyword}%'),
|
||||||
StockProduct.order_id.ilike(f'%{keyword}%')
|
StockProduct.order_id.ilike(f'%{keyword}%'),
|
||||||
|
StockProduct.sku.ilike(f'%{keyword}%')
|
||||||
))
|
))
|
||||||
|
|
||||||
pagination = query.order_by(StockProduct.id.desc()).paginate(page=page, per_page=limit, error_out=False)
|
pagination = query.order_by(StockProduct.id.desc()).paginate(page=page, per_page=limit, error_out=False)
|
||||||
|
|
||||||
base_ids = list(set([i.base_id for i in pagination.items]))
|
# 计算聚合库存
|
||||||
|
current_items = pagination.items
|
||||||
|
base_ids = list(set([i.base_id for i in current_items]))
|
||||||
stock_map = {}
|
stock_map = {}
|
||||||
if base_ids:
|
if base_ids:
|
||||||
aggs = db.session.query(
|
aggs = db.session.query(
|
||||||
@ -157,10 +209,11 @@ class ProductInboundService:
|
|||||||
func.sum(StockProduct.stock_quantity).label('s'),
|
func.sum(StockProduct.stock_quantity).label('s'),
|
||||||
func.sum(StockProduct.available_quantity).label('a')
|
func.sum(StockProduct.available_quantity).label('a')
|
||||||
).filter(StockProduct.base_id.in_(base_ids)).group_by(StockProduct.base_id).all()
|
).filter(StockProduct.base_id.in_(base_ids)).group_by(StockProduct.base_id).all()
|
||||||
for a in aggs: stock_map[a.base_id] = {'s': float(a.s or 0), 'a': float(a.a or 0)}
|
for a in aggs:
|
||||||
|
stock_map[a.base_id] = {'s': float(a.s or 0), 'a': float(a.a or 0)}
|
||||||
|
|
||||||
items = []
|
items = []
|
||||||
for item in pagination.items:
|
for item in current_items:
|
||||||
d = item.to_dict()
|
d = item.to_dict()
|
||||||
stats = stock_map.get(item.base_id, {'s': 0, 'a': 0})
|
stats = stock_map.get(item.base_id, {'s': 0, 'a': 0})
|
||||||
d['sum_stock'] = stats['s']
|
d['sum_stock'] = stats['s']
|
||||||
|
|||||||
@ -54,8 +54,11 @@
|
|||||||
</el-table-column>
|
</el-table-column>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<el-table-column label="操作" width="160" fixed="right" align="center">
|
<el-table-column label="操作" width="220" fixed="right" align="center">
|
||||||
<template #default="{ row }">
|
<template #default="{ row }">
|
||||||
|
<el-button link type="warning" size="default" @click="handlePrint(row)">
|
||||||
|
<el-icon><Printer/></el-icon> 打印
|
||||||
|
</el-button>
|
||||||
<el-button link type="primary" @click="handleUpdate(row)">编辑</el-button>
|
<el-button link type="primary" @click="handleUpdate(row)">编辑</el-button>
|
||||||
<el-popconfirm title="确定删除?" @confirm="handleDelete(row)"><template #reference><el-button link type="danger">删除</el-button></template></el-popconfirm>
|
<el-popconfirm title="确定删除?" @confirm="handleDelete(row)"><template #reference><el-button link type="danger">删除</el-button></template></el-popconfirm>
|
||||||
</template>
|
</template>
|
||||||
@ -117,8 +120,8 @@
|
|||||||
<div class="card-title"><el-icon class="icon"><House /></el-icon><span>2. 入库详情</span></div>
|
<div class="card-title"><el-icon class="icon"><House /></el-icon><span>2. 入库详情</span></div>
|
||||||
<div class="card-content">
|
<div class="card-content">
|
||||||
<el-row :gutter="24">
|
<el-row :gutter="24">
|
||||||
<el-col :span="6"><el-form-item label="SKU" prop="sku"><el-input v-model="form.sku" /></el-form-item></el-col>
|
<el-col :span="6"><el-form-item label="SKU" prop="sku"><el-input v-model="form.sku" placeholder="自动生成" disabled /></el-form-item></el-col>
|
||||||
<el-col :span="6"><el-form-item label="条码" prop="barcode"><el-input v-model="form.barcode" /></el-form-item></el-col>
|
<el-col :span="6"><el-form-item label="条码" prop="barcode"><el-input v-model="form.barcode" placeholder="自动生成" /></el-form-item></el-col>
|
||||||
<el-col :span="6"><el-form-item label="库位" prop="warehouse_location"><el-input v-model="form.warehouse_location" /></el-form-item></el-col>
|
<el-col :span="6"><el-form-item label="库位" prop="warehouse_location"><el-input v-model="form.warehouse_location" /></el-form-item></el-col>
|
||||||
<el-col :span="6"><el-form-item label="入库日期"><el-date-picker v-model="form.in_date" type="date" value-format="YYYY-MM-DD" style="width:100%" disabled /></el-form-item></el-col>
|
<el-col :span="6"><el-form-item label="入库日期"><el-date-picker v-model="form.in_date" type="date" value-format="YYYY-MM-DD" style="width:100%" disabled /></el-form-item></el-col>
|
||||||
</el-row>
|
</el-row>
|
||||||
@ -197,20 +200,51 @@
|
|||||||
<template #footer>
|
<template #footer>
|
||||||
<div class="dialog-footer">
|
<div class="dialog-footer">
|
||||||
<el-button @click="visible = false" size="large">取消</el-button>
|
<el-button @click="visible = false" size="large">取消</el-button>
|
||||||
<el-button type="primary" :loading="submitting" @click="submitForm" size="large">提交</el-button>
|
<el-button type="primary" :loading="submitting" @click="submitForm" size="large" class="confirm-btn">
|
||||||
|
{{ dialogStatus === 'create' ? '提交并打印' : '保存修改' }}
|
||||||
|
</el-button>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
</el-dialog>
|
</el-dialog>
|
||||||
|
|
||||||
|
<el-dialog
|
||||||
|
v-model="printVisible"
|
||||||
|
title="标签打印预览"
|
||||||
|
width="400px"
|
||||||
|
destroy-on-close
|
||||||
|
append-to-body
|
||||||
|
>
|
||||||
|
<div style="text-align: center;">
|
||||||
|
<div v-loading="printLoading" class="preview-box">
|
||||||
|
<img v-if="previewUrl" :src="previewUrl" alt="Label Preview" style="width: 100%; border: 1px solid #ccc;"/>
|
||||||
|
<div v-else class="empty-preview">正在生成预览...</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div style="margin-top: 20px; font-size: 14px; color: #666;">
|
||||||
|
<p>打印机 IP: 192.168.9.205</p>
|
||||||
|
<p>尺寸: 40mm x 30mm</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<template #footer>
|
||||||
|
<div class="dialog-footer">
|
||||||
|
<el-button @click="printVisible = false">取消</el-button>
|
||||||
|
<el-button type="primary" :loading="printing" @click="confirmPrint">
|
||||||
|
<el-icon><Printer/></el-icon> 确认打印
|
||||||
|
</el-button>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
</el-dialog>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { ref, reactive, onMounted, watch } from 'vue'
|
import { ref, reactive, onMounted, watch } from 'vue'
|
||||||
import { Plus, Setting, Refresh, Search, Box, House, Link, InfoFilled } from '@element-plus/icons-vue'
|
import { Plus, Setting, Refresh, Search, Box, House, Link, InfoFilled, Printer } from '@element-plus/icons-vue'
|
||||||
import { ElMessage } from 'element-plus'
|
import { ElMessage } from 'element-plus'
|
||||||
import dayjs from 'dayjs'
|
import dayjs from 'dayjs'
|
||||||
// 引用更新后的 product.ts
|
|
||||||
import { getProductList, createProductInbound, updateProductInbound, deleteProductInbound, searchMaterialBase } from '@/api/inbound/product'
|
import { getProductList, createProductInbound, updateProductInbound, deleteProductInbound, searchMaterialBase } from '@/api/inbound/product'
|
||||||
|
import { getLabelPreview, executePrint } from '@/api/common/print'
|
||||||
|
|
||||||
const loading = ref(false)
|
const loading = ref(false)
|
||||||
const submitting = ref(false)
|
const submitting = ref(false)
|
||||||
@ -223,6 +257,13 @@ const formRef = ref()
|
|||||||
const queryParams = reactive({ page: 1, pageSize: 15, keyword: '' })
|
const queryParams = reactive({ page: 1, pageSize: 15, keyword: '' })
|
||||||
const materialOptions = ref<any[]>([])
|
const materialOptions = ref<any[]>([])
|
||||||
|
|
||||||
|
// 打印相关变量
|
||||||
|
const printVisible = ref(false)
|
||||||
|
const printLoading = ref(false)
|
||||||
|
const printing = ref(false)
|
||||||
|
const previewUrl = ref('')
|
||||||
|
const currentPrintData = ref<any>({})
|
||||||
|
|
||||||
const allColumns = [
|
const allColumns = [
|
||||||
{ prop: 'material_name', label: '名称', minWidth: '120' },
|
{ prop: 'material_name', label: '名称', minWidth: '120' },
|
||||||
{ prop: 'spec_model', label: '规格', minWidth: '120' },
|
{ prop: 'spec_model', label: '规格', minWidth: '120' },
|
||||||
@ -246,7 +287,7 @@ const allColumns = [
|
|||||||
const visibleColumnProps = ref(allColumns.map(c => c.prop))
|
const visibleColumnProps = ref(allColumns.map(c => c.prop))
|
||||||
|
|
||||||
const form = reactive({
|
const form = reactive({
|
||||||
id: undefined, base_id: undefined, material_name: '', spec_model: '', material_type: '',
|
id: undefined, base_id: undefined, material_name: '', spec_model: '', material_type: '', category: '',
|
||||||
sku: '', barcode: '', serial_number: '', in_date: '',
|
sku: '', barcode: '', serial_number: '', in_date: '',
|
||||||
in_quantity: 1, stock_quantity: 1, available_quantity: 1,
|
in_quantity: 1, stock_quantity: 1, available_quantity: 1,
|
||||||
warehouse_location: '', status: '在库', quality_status: '合格',
|
warehouse_location: '', status: '在库', quality_status: '合格',
|
||||||
@ -386,6 +427,7 @@ const onMaterialSelected = (val: number) => {
|
|||||||
form.material_name = item.name
|
form.material_name = item.name
|
||||||
form.spec_model = item.spec
|
form.spec_model = item.spec
|
||||||
form.material_type = item.type
|
form.material_type = item.type
|
||||||
|
form.category = item.category
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -411,11 +453,15 @@ const handleUpdate = (row: any) => {
|
|||||||
id: row.base_id,
|
id: row.base_id,
|
||||||
name: row.material_name,
|
name: row.material_name,
|
||||||
spec: row.spec_model,
|
spec: row.spec_model,
|
||||||
|
category: row.category,
|
||||||
isHistory: false
|
isHistory: false
|
||||||
}]
|
}]
|
||||||
visible.value = true
|
visible.value = true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ------------------------------------
|
||||||
|
// 提交逻辑 (含自动打印)
|
||||||
|
// ------------------------------------
|
||||||
const submitForm = async () => {
|
const submitForm = async () => {
|
||||||
await formRef.value.validate(async (valid: boolean) => {
|
await formRef.value.validate(async (valid: boolean) => {
|
||||||
if(valid) {
|
if(valid) {
|
||||||
@ -425,13 +471,33 @@ const submitForm = async () => {
|
|||||||
production_start_time: form.production_time_range?.[0],
|
production_start_time: form.production_time_range?.[0],
|
||||||
production_end_time: form.production_time_range?.[1]
|
production_end_time: form.production_time_range?.[1]
|
||||||
}
|
}
|
||||||
if(dialogStatus.value === 'create') await createProductInbound(payload)
|
|
||||||
else await updateProductInbound(form.id!, payload)
|
if(dialogStatus.value === 'create') {
|
||||||
|
// 1. 创建入库
|
||||||
|
const res: any = await createProductInbound(payload)
|
||||||
|
ElMessage.success('入库成功')
|
||||||
|
|
||||||
|
// 2. 自动打印
|
||||||
|
const newItem = res.data
|
||||||
|
if (newItem) {
|
||||||
|
ElMessage.info('正在发送打印指令...')
|
||||||
|
try {
|
||||||
|
await executePrint(newItem)
|
||||||
|
ElMessage.success('打印指令已发送')
|
||||||
|
} catch (printErr: any) {
|
||||||
|
console.error(printErr)
|
||||||
|
ElMessage.warning('入库成功,但自动打印失败:' + (printErr.msg || '未知错误'))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
await updateProductInbound(form.id!, payload)
|
||||||
|
ElMessage.success('更新成功')
|
||||||
|
}
|
||||||
|
|
||||||
// 保存历史
|
// 保存历史
|
||||||
saveToHistory(HISTORY_KEYS.PRODUCTION_MANAGER, form.production_manager)
|
saveToHistory(HISTORY_KEYS.PRODUCTION_MANAGER, form.production_manager)
|
||||||
|
|
||||||
ElMessage.success('操作成功')
|
|
||||||
visible.value = false
|
visible.value = false
|
||||||
fetchData()
|
fetchData()
|
||||||
} catch(e:any) { ElMessage.error(e.msg || '失败') }
|
} catch(e:any) { ElMessage.error(e.msg || '失败') }
|
||||||
@ -445,10 +511,54 @@ const handleDelete = async (row: any) => {
|
|||||||
catch(e) { ElMessage.error('删除失败') }
|
catch(e) { ElMessage.error('删除失败') }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ------------------------------------
|
||||||
|
// 打印逻辑 (手动 & 预览)
|
||||||
|
// ------------------------------------
|
||||||
|
const handlePrint = async (row: any) => {
|
||||||
|
printVisible.value = true
|
||||||
|
printLoading.value = true
|
||||||
|
previewUrl.value = ''
|
||||||
|
|
||||||
|
// 构造产品特有的打印数据
|
||||||
|
const printData = {
|
||||||
|
global_print_id: row.global_print_id, // 需后端模型支持
|
||||||
|
material_name: row.material_name,
|
||||||
|
spec_model: row.spec_model,
|
||||||
|
category: row.category,
|
||||||
|
material_type: row.material_type,
|
||||||
|
warehouse_loc: row.warehouse_loc,
|
||||||
|
serial_number: row.serial_number,
|
||||||
|
sku: row.sku
|
||||||
|
}
|
||||||
|
currentPrintData.value = printData
|
||||||
|
|
||||||
|
try {
|
||||||
|
const res: any = await getLabelPreview(printData)
|
||||||
|
previewUrl.value = res.data
|
||||||
|
} catch (e) {
|
||||||
|
ElMessage.error('预览生成失败')
|
||||||
|
} finally {
|
||||||
|
printLoading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const confirmPrint = async () => {
|
||||||
|
printing.value = true
|
||||||
|
try {
|
||||||
|
await executePrint(currentPrintData.value)
|
||||||
|
ElMessage.success('指令已发送')
|
||||||
|
printVisible.value = false
|
||||||
|
} catch (e: any) {
|
||||||
|
ElMessage.error(e.msg || '打印失败')
|
||||||
|
} finally {
|
||||||
|
printing.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const resetForm = () => {
|
const resetForm = () => {
|
||||||
materialOptions.value = []
|
materialOptions.value = []
|
||||||
Object.assign(form, {
|
Object.assign(form, {
|
||||||
id: undefined, base_id: undefined, material_name: '', spec_model: '', material_type: '',
|
id: undefined, base_id: undefined, material_name: '', spec_model: '', material_type: '', category: '',
|
||||||
sku: '', barcode: '', serial_number: '', in_date: '',
|
sku: '', barcode: '', serial_number: '', in_date: '',
|
||||||
in_quantity: 1, stock_quantity: 1, available_quantity: 1,
|
in_quantity: 1, stock_quantity: 1, available_quantity: 1,
|
||||||
warehouse_location: '', status: '在库', quality_status: '合格',
|
warehouse_location: '', status: '在库', quality_status: '合格',
|
||||||
@ -484,4 +594,17 @@ onMounted(() => fetchData())
|
|||||||
.opt-spec { color: #8492a6; font-size: 12px; margin-right: 10px; }
|
.opt-spec { color: #8492a6; font-size: 12px; margin-right: 10px; }
|
||||||
.is-text-view :deep(.el-input__wrapper) { box-shadow: none !important; background: #f5f7fa; border-bottom: 1px solid #dcdfe6; }
|
.is-text-view :deep(.el-input__wrapper) { box-shadow: none !important; background: #f5f7fa; border-bottom: 1px solid #dcdfe6; }
|
||||||
.search-tip { color: #909399; font-size: 12px; margin-left: 10px; display: flex; align-items: center; gap: 4px; }
|
.search-tip { color: #909399; font-size: 12px; margin-left: 10px; display: flex; align-items: center; gap: 4px; }
|
||||||
|
|
||||||
|
/* 打印预览样式 */
|
||||||
|
.preview-box {
|
||||||
|
min-height: 150px;
|
||||||
|
display: flex;
|
||||||
|
justify-content: center;
|
||||||
|
align-items: center;
|
||||||
|
background: #f5f7fa;
|
||||||
|
border-radius: 4px;
|
||||||
|
}
|
||||||
|
.empty-preview {
|
||||||
|
color: #909399;
|
||||||
|
}
|
||||||
</style>
|
</style>
|
||||||
Reference in New Issue
Block a user