出库操作逻辑上面实现,成功跑通

This commit is contained in:
dxc
2026-02-05 10:20:52 +08:00
parent 797b611530
commit f3b60dfc54
8 changed files with 337 additions and 117 deletions

View File

@ -1,12 +1,13 @@
from flask import Blueprint, request, jsonify from flask import Blueprint, request, jsonify
from app.services.outbound_service import OutboundService from app.services.outbound_service import OutboundService
from flask_jwt_extended import jwt_required, get_jwt_identity from flask_jwt_extended import jwt_required, get_jwt_identity
import traceback
outbound_bp = Blueprint('outbound', __name__, url_prefix='/outbound') outbound_bp = Blueprint('outbound', __name__, url_prefix='/outbound')
# -------------------------------------------------------- # --------------------------------------------------------
# 1. 扫码查询库存接口 # 1. 扫码查询库存接口 (关联三个库存表)
# GET /api/v1/outbound/scan?barcode=... # GET /api/v1/outbound/scan?barcode=...
# -------------------------------------------------------- # --------------------------------------------------------
@outbound_bp.route('/scan', methods=['GET']) @outbound_bp.route('/scan', methods=['GET'])
@ -17,13 +18,24 @@ def scan_barcode():
return jsonify({'code': 400, 'msg': '请提供条码'}), 400 return jsonify({'code': 400, 'msg': '请提供条码'}), 400
try: try:
# 调用 Service 层去三个表中查找
result = OutboundService.get_stock_by_barcode(barcode) result = OutboundService.get_stock_by_barcode(barcode)
if result: if result:
return jsonify({'code': 200, 'data': result, 'msg': '扫描成功'}) return jsonify({
'code': 200,
'msg': '扫描成功',
'data': result
})
else: else:
return jsonify({'code': 404, 'msg': '未找到对应的库存记录'}), 404 return jsonify({
'code': 404,
'msg': '未找到对应的库存记录,请确认条码是否正确'
}), 404
except Exception as e: except Exception as e:
return jsonify({'code': 500, 'msg': str(e)}), 500 traceback.print_exc()
return jsonify({'code': 500, 'msg': f'扫描查询出错: {str(e)}'}), 500
# -------------------------------------------------------- # --------------------------------------------------------
@ -37,24 +49,37 @@ def create_outbound():
if not data: if not data:
return jsonify({'code': 400, 'msg': '无有效数据'}), 400 return jsonify({'code': 400, 'msg': '无有效数据'}), 400
current_user = get_jwt_identity() # 获取当前登录用户作为操作员 # 获取当前登录用户名 (JWT identity)
current_user_name = get_jwt_identity()
if not current_user_name:
current_user_name = 'Unknown'
# 简单的必填校验 (更复杂的校验可放入 Schema) # ★ [修改] 获取最终的操作员名称
# 优先取前端传来的 operator_name (你在前端下拉框选的人)
# 如果前端没传,则回退使用当前登录用户的名字
final_operator = data.get('operator_name')
if not final_operator:
final_operator = current_user_name
# 必填校验
required_fields = ['stock_id', 'source_table', 'quantity', 'consumer_name', 'signature_path'] required_fields = ['stock_id', 'source_table', 'quantity', 'consumer_name', 'signature_path']
for field in required_fields: for field in required_fields:
if field not in data or not data[field]: if field not in data or not data[field]:
return jsonify({'code': 400, 'msg': f'缺少必填字段: {field}'}), 400 return jsonify({'code': 400, 'msg': f'缺少必填字段: {field}'}), 400
try: try:
outbound_record = OutboundService.create_outbound(data, operator_name=current_user) # ★ [修改] 将确认后的操作员名称传给 Service
outbound_record = OutboundService.create_outbound(data, operator_name=final_operator)
return jsonify({ return jsonify({
'code': 200, 'code': 200,
'msg': '出库成功', 'msg': '出库成功',
'data': outbound_record.to_dict() 'data': outbound_record.to_dict()
}) })
except ValueError as e: except ValueError as e:
# 业务逻辑错误 (如库存不足)
return jsonify({'code': 400, 'msg': str(e)}), 400 return jsonify({'code': 400, 'msg': str(e)}), 400
except Exception as e: except Exception as e:
traceback.print_exc()
return jsonify({'code': 500, 'msg': f'服务器内部错误: {str(e)}'}), 500 return jsonify({'code': 500, 'msg': f'服务器内部错误: {str(e)}'}), 500
@ -67,11 +92,10 @@ def create_outbound():
def get_outbound_list(): def get_outbound_list():
try: try:
page = int(request.args.get('page', 1)) page = int(request.args.get('page', 1))
per_page = int(request.args.get('limit', 10)) limit = int(request.args.get('limit', 10))
keyword = request.args.get('keyword', '') keyword = request.args.get('keyword', '')
# 日期范围处理可根据前端传参格式调整
result = OutboundService.get_list(page, per_page, keyword) result = OutboundService.get_list(page, limit, keyword)
return jsonify({ return jsonify({
'code': 200, 'code': 200,
@ -79,4 +103,5 @@ def get_outbound_list():
'data': result 'data': result
}) })
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

View File

@ -10,17 +10,17 @@ class TransOutbound(db.Model):
# 关联源库存信息 # 关联源库存信息
sku = db.Column(db.String(100)) sku = db.Column(db.String(100))
source_table = db.Column(db.String(50)) # 'stock_buy', 'stock_product', etc. source_table = db.Column(db.String(50)) # 'stock_buy', 'stock_product', 'stock_semi'
stock_id = db.Column(db.Integer) # 对应源表的主键ID stock_id = db.Column(db.Integer) # 对应源表的主键ID
barcode = db.Column(db.String(100)) # 实际扫码内容 barcode = db.Column(db.String(100)) # 实际扫码内容
# 业务信息 # 业务信息
outbound_type = db.Column(db.String(50), default='SALES') # SALES, USE, TRANSFER outbound_type = db.Column(db.String(50), default='SALES') # SALES(销售), USE(领用), TRANSFER(调拨)
quantity = db.Column(db.Numeric(19, 4), nullable=False) quantity = db.Column(db.Numeric(19, 4), nullable=False)
# 签字与追溯 # 签字与追溯
consumer_name = db.Column(db.String(100)) # 领用人/客户 consumer_name = db.Column(db.String(100)) # 领用人/客户
signature_path = db.Column(db.Text) # 签名图片路径 signature_path = db.Column(db.Text) # 电子签名图片路径
outbound_time = db.Column(db.DateTime, default=datetime.now) outbound_time = db.Column(db.DateTime, default=datetime.now)
operator_name = db.Column(db.String(100)) # 操作员 operator_name = db.Column(db.String(100)) # 操作员

View File

@ -4,10 +4,12 @@ from sqlalchemy import or_
from app.extensions import db from app.extensions import db
from app.models.outbound import TransOutbound from app.models.outbound import TransOutbound
# 入所有库存实体模型,用于查找和扣减 # 入所有库存模型以进行查询
from app.models.inbound.buy import StockBuy from app.models.inbound.buy import StockBuy
from app.models.inbound.semi import StockSemi from app.models.inbound.semi import StockSemi
from app.models.inbound.product import StockProduct from app.models.inbound.product import StockProduct
# ★★★ [关键] 引入基础信息表,用于手动补全名称
from app.models.base import MaterialBase
class OutboundService: class OutboundService:
@ -22,58 +24,92 @@ class OutboundService:
@staticmethod @staticmethod
def get_stock_by_barcode(barcode): def get_stock_by_barcode(barcode):
""" """
根据条码在各个库存表中查找 [核心逻辑] 根据扫码内容查找对应的库存物品
优先级: 成品 -> 半成品 -> 采购件 查找顺序: 成品 (StockProduct) -> 半成品 (StockSemi) -> 采购件 (StockBuy)
匹配逻辑: 匹配 barcode 字段 OR sku 字段
""" """
if not barcode: if not barcode:
return None return None
# 1. 查成品 clean_code = barcode.strip()
prod = StockProduct.query.filter_by(barcode=barcode).first()
# --- 1. 查找成品表 (StockProduct) ---
prod = StockProduct.query.filter(
or_(StockProduct.barcode == clean_code, StockProduct.sku == clean_code)
).first()
if prod: if prod:
return OutboundService._format_scan_result(prod, 'stock_product', prod.sku) return OutboundService._format_scan_result(prod, 'stock_product')
# 2. 查半成品 # --- 2. 查半成品表 (StockSemi) ---
semi = StockSemi.query.filter_by(barcode=barcode).first() semi = StockSemi.query.filter(
or_(StockSemi.barcode == clean_code, StockSemi.sku == clean_code)
).first()
if semi: if semi:
return OutboundService._format_scan_result(semi, 'stock_semi', semi.sku) return OutboundService._format_scan_result(semi, 'stock_semi')
# 3. 查采购件 # --- 3. 查采购件表 (StockBuy) ---
buy = StockBuy.query.filter_by(barcode=barcode).first() buy = StockBuy.query.filter(
or_(StockBuy.barcode == clean_code, StockBuy.sku == clean_code)
).first()
if buy: if buy:
# 采购件可能需要关联 material_base 获取名称,这里假设 base_id 关联已建立 return OutboundService._format_scan_result(buy, 'stock_buy')
name = buy.base.name if buy.base else "未知采购件"
spec = buy.base.spec_model if buy.base else ""
return OutboundService._format_scan_result(buy, 'stock_buy', buy.sku, name, spec)
return None return None
@staticmethod @staticmethod
def _format_scan_result(item, table_name, sku, name=None, spec=None): def _format_scan_result(item, table_name):
"""格式化返回给前端的数据结构""" """
# 如果没有传 name (例如成品/半成品),尝试通过关联获取,或者直接用 SKU 代替 [核心修复] 格式化返回数据,确保名称和规格一定能取到
item_name = name """
item_spec = spec base_name = ""
base_spec = ""
if not item_name and hasattr(item, 'base') and item.base: # -------------------------------------------------------
item_name = item.base.name # 修复逻辑:强制获取基础信息
item_spec = item.base.spec_model # -------------------------------------------------------
# 步骤 1: 尝试通过 ORM 关联获取 (如果有定义 relationship)
if hasattr(item, 'base') and item.base:
base_name = item.base.name
base_spec = item.base.spec_model
# 步骤 2: [关键] 如果步骤1失败但有 base_id则手动查询 MaterialBase 表
# 这能解决“扫码有库存但显示未知物品”的问题
if not base_name and hasattr(item, 'base_id') and item.base_id:
try:
# 手动查基础表
base_info = MaterialBase.query.get(item.base_id)
if base_info:
base_name = base_info.name
base_spec = base_info.spec_model
except Exception as e:
print(f"基础信息查询失败: {e}")
# 步骤 3: 兜底逻辑,某些旧表可能直接存了 material_name 字段
if not base_name and hasattr(item, 'material_name'):
base_name = item.material_name
stock_qty = float(item.stock_quantity) if item.stock_quantity else 0
avail_qty = float(item.available_quantity) if item.available_quantity else 0
return { return {
'id': item.id, 'id': item.id,
'sku': sku, 'sku': item.sku,
'name': item_name or sku, 'name': base_name or "未知物品", # 此时应该能正确显示名称了
'spec_model': item_spec or '', 'spec_model': base_spec or "", # 此时应该能正确显示规格了
'source_table': table_name, 'source_table': table_name, # 标记来源表
'stock_quantity': float(item.stock_quantity), 'stock_quantity': stock_qty, # 当前库存
'available_quantity': float(item.available_quantity), 'available_quantity': avail_qty, # 可用库存
'batch_number': getattr(item, 'batch_number', ''), 'batch_number': getattr(item, 'batch_number', ''),
'warehouse_location': getattr(item, 'warehouse_location', '') 'warehouse_location': getattr(item, 'warehouse_location', ''),
'barcode': getattr(item, 'barcode', '')
} }
@staticmethod @staticmethod
def create_outbound(data, operator_name='System'): def create_outbound(data, operator_name='System'):
"""执行出库逻辑:扣减库存 + 记录日志""" """
[核心逻辑] 执行出库:扣减对应表的库存 + 创建记录
"""
source_table = data.get('source_table') source_table = data.get('source_table')
stock_id = data.get('stock_id') stock_id = data.get('stock_id')
quantity = float(data.get('quantity', 0)) quantity = float(data.get('quantity', 0))
@ -81,7 +117,7 @@ class OutboundService:
if quantity <= 0: if quantity <= 0:
raise ValueError("出库数量必须大于0") raise ValueError("出库数量必须大于0")
# 1. 获取对应的库存记录模型 # 1. 动态映射表模型
model_map = { model_map = {
'stock_buy': StockBuy, 'stock_buy': StockBuy,
'stock_semi': StockSemi, 'stock_semi': StockSemi,
@ -90,22 +126,24 @@ class OutboundService:
ModelClass = model_map.get(source_table) ModelClass = model_map.get(source_table)
if not ModelClass: if not ModelClass:
raise ValueError(f"未知的库存来源表: {source_table}") raise ValueError(f"无效的数据来源表: {source_table}")
# 2. 锁定并查询库存 (使用 with_for_update 防止并发扣减) # 2. 锁定并查询库存 (使用 with_for_update 防止并发超卖)
stock_item = ModelClass.query.with_for_update().get(stock_id) stock_item = ModelClass.query.with_for_update().get(stock_id)
if not stock_item: if not stock_item:
raise ValueError("库存记录不存在") raise ValueError("库存记录不存在或已被删除")
if stock_item.available_quantity < quantity: # 3. 校验库存充足
raise ValueError(f"库存不足!当前可用: {stock_item.available_quantity}, 请求出库: {quantity}") current_avail = float(stock_item.available_quantity)
if current_avail < quantity:
raise ValueError(f"库存不足!当前可用: {current_avail}, 请求出库: {quantity}")
try: try:
# 3. 扣减库存 # 4. 扣减库存
stock_item.stock_quantity -= quantity stock_item.stock_quantity = float(stock_item.stock_quantity) - quantity
stock_item.available_quantity -= quantity stock_item.available_quantity = float(stock_item.available_quantity) - quantity
# 4. 创建出库记录 # 5. 创建出库记录
new_outbound = TransOutbound( new_outbound = TransOutbound(
outbound_no=OutboundService.generate_outbound_no(), outbound_no=OutboundService.generate_outbound_no(),
sku=data.get('sku'), sku=data.get('sku'),
@ -131,6 +169,7 @@ class OutboundService:
@staticmethod @staticmethod
def get_list(page=1, per_page=10, keyword=None, start_date=None, end_date=None): def get_list(page=1, per_page=10, keyword=None, start_date=None, end_date=None):
"""查询出库历史记录"""
query = TransOutbound.query.order_by(TransOutbound.outbound_time.desc()) query = TransOutbound.query.order_by(TransOutbound.outbound_time.desc())
if keyword: if keyword:
@ -141,10 +180,10 @@ class OutboundService:
)) ))
if start_date and end_date: if start_date and end_date:
# 假设传入的是 'YYYY-MM-DD',需要处理时间范围
query = query.filter(TransOutbound.outbound_time.between(start_date, end_date)) query = query.filter(TransOutbound.outbound_time.between(start_date, end_date))
pagination = query.paginate(page=page, per_page=per_page, error_out=False) pagination = query.paginate(page=page, per_page=per_page, error_out=False)
return { return {
'items': [item.to_dict() for item in pagination.items], 'items': [item.to_dict() for item in pagination.items],
'total': pagination.total, 'total': pagination.total,

View File

@ -9,7 +9,8 @@ export function uploadFile(file: File) {
formData.append('file', file) formData.append('file', file)
return request({ return request({
url: '/api/v1/common/upload', // ★★★ [修改] 去掉开头的 /api适配 request.ts 的 baseURL
url: '/v1/common/upload',
method: 'post', method: 'post',
data: formData, data: formData,
headers: { headers: {

View File

@ -22,6 +22,7 @@ export interface ScanResult {
available_quantity: number available_quantity: number
batch_number?: string batch_number?: string
warehouse_location?: string warehouse_location?: string
barcode?: string
} }
/** /**
@ -30,7 +31,8 @@ export interface ScanResult {
*/ */
export function getStockByBarcode(barcode: string) { export function getStockByBarcode(barcode: string) {
return request<any, ScanResult>({ return request<any, ScanResult>({
url: '/api/v1/outbound/scan', // ★★★ [修改] 去掉开头的 /apiAxios 会自动拼接 baseURL
url: '/v1/outbound/scan',
method: 'get', method: 'get',
params: { barcode } params: { barcode }
}) })
@ -41,7 +43,8 @@ export function getStockByBarcode(barcode: string) {
*/ */
export function submitOutbound(data: OutboundSubmitData) { export function submitOutbound(data: OutboundSubmitData) {
return request({ return request({
url: '/api/v1/outbound', // ★★★ [修改] 去掉开头的 /api
url: '/v1/outbound',
method: 'post', method: 'post',
data data
}) })
@ -52,7 +55,8 @@ export function submitOutbound(data: OutboundSubmitData) {
*/ */
export function getOutboundList(params: any) { export function getOutboundList(params: any) {
return request({ return request({
url: '/api/v1/outbound', // ★★★ [修改] 去掉开头的 /api
url: '/v1/outbound',
method: 'get', method: 'get',
params params
}) })

View File

@ -35,7 +35,11 @@
<el-descriptions title="货物信息" border :column="1"> <el-descriptions title="货物信息" border :column="1">
<el-descriptions-item label="名称">{{ currentItem.name }}</el-descriptions-item> <el-descriptions-item label="名称">{{ currentItem.name }}</el-descriptions-item>
<el-descriptions-item label="规格/型号">{{ currentItem.spec_model }}</el-descriptions-item> <el-descriptions-item label="规格/型号">{{ currentItem.spec_model }}</el-descriptions-item>
<el-descriptions-item label="当前库存">{{ currentItem.stock_quantity }}</el-descriptions-item> <el-descriptions-item label="当前库存">
<el-tag :type="currentItem.available_quantity > 0 ? 'success' : 'danger'">
{{ currentItem.stock_quantity }} (可用: {{ currentItem.available_quantity }})
</el-tag>
</el-descriptions-item>
<el-descriptions-item label="库位">{{ currentItem.warehouse_location || '暂无' }}</el-descriptions-item> <el-descriptions-item label="库位">{{ currentItem.warehouse_location || '暂无' }}</el-descriptions-item>
</el-descriptions> </el-descriptions>
@ -52,14 +56,37 @@
</el-col> </el-col>
<el-col :span="12"> <el-col :span="12">
<el-form-item label="出库数量" prop="quantity"> <el-form-item label="出库数量" prop="quantity">
<el-input-number v-model="form.quantity" :min="1" :max="currentItem.available_quantity" /> <el-input-number v-model="form.quantity" :min="1" :max="currentItem.available_quantity" style="width: 100%" />
</el-form-item> </el-form-item>
</el-col> </el-col>
</el-row> </el-row>
<el-form-item label="领用人/客户姓名" prop="consumer_name"> <el-row :gutter="20">
<el-input v-model="form.consumer_name" placeholder="请输入姓名" /> <el-col :span="12">
</el-form-item> <el-form-item label="领用人/客户姓名" prop="consumer_name">
<el-input v-model="form.consumer_name" placeholder="请输入姓名" />
</el-form-item>
</el-col>
<el-col :span="12">
<el-form-item label="操作员 (库管)" prop="operator_name">
<el-select
v-model="form.operator_name"
filterable
allow-create
default-first-option
placeholder="请选择或输入操作员"
style="width: 100%"
>
<el-option
v-for="item in operatorOptions"
:key="item"
:label="item"
:value="item"
/>
</el-select>
</el-form-item>
</el-col>
</el-row>
<el-form-item label="备注" prop="remark"> <el-form-item label="备注" prop="remark">
<el-input v-model="form.remark" type="textarea" /> <el-input v-model="form.remark" type="textarea" />
@ -80,13 +107,16 @@
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { ref, reactive, nextTick, onUnmounted } from 'vue' import { ref, reactive, nextTick, onUnmounted, onMounted } from 'vue'
import { ElMessage } from 'element-plus' import { ElMessage } from 'element-plus'
// ★ [修改] 引入 Html5QrcodeSupportedFormats 以支持 Code 128
import { Html5Qrcode, Html5QrcodeSupportedFormats } from 'html5-qrcode' import { Html5Qrcode, Html5QrcodeSupportedFormats } from 'html5-qrcode'
import { getStockByBarcode, submitOutbound, type ScanResult } from '@/api/outbound' // 引入接口
import { getStockByBarcode, submitOutbound, getOutboundList, type ScanResult } from '@/api/outbound'
import { uploadFile } from '@/api/common/upload' import { uploadFile } from '@/api/common/upload'
// 引入组件
import Signature from '@/components/Signature/index.vue' import Signature from '@/components/Signature/index.vue'
// 引入 Store 以获取当前登录用户
import { useUserStore } from '@/stores/user'
// --- 状态定义 --- // --- 状态定义 ---
const barcodeInput = ref('') const barcodeInput = ref('')
@ -96,18 +126,58 @@ const showCamera = ref(false)
const html5QrCode = ref<Html5Qrcode | null>(null) const html5QrCode = ref<Html5Qrcode | null>(null)
const barcodeRef = ref() const barcodeRef = ref()
const signatureRef = ref() const signatureRef = ref()
const formRef = ref() // ★ [修复] 补充 formRef 定义 const formRef = ref()
const userStore = useUserStore()
// 操作员选项列表
const operatorOptions = ref<string[]>([])
const form = reactive({ const form = reactive({
outbound_type: 'SALES', outbound_type: 'SALES',
quantity: 1, quantity: 1,
consumer_name: '', consumer_name: '',
operator_name: '', // 新增字段
remark: '' remark: ''
}) })
const rules = { const rules = {
consumer_name: [{ required: true, message: '请输入领用人姓名', trigger: 'blur' }], consumer_name: [{ required: true, message: '请输入领用人姓名', trigger: 'blur' }],
quantity: [{ required: true, message: '请输入数量', trigger: 'blur' }] quantity: [{ required: true, message: '请输入数量', trigger: 'blur' }],
operator_name: [{ required: true, message: '请指定操作员', trigger: 'change' }]
}
// --- 初始化逻辑 ---
onMounted(() => {
// 1. 默认操作员为当前登录用户
if (userStore.username) {
form.operator_name = userStore.username
operatorOptions.value.push(userStore.username)
}
// 2. 加载历史操作员记录
loadHistoryOperators()
})
// 加载历史操作员列表 (用于自动补全)
const loadHistoryOperators = async () => {
try {
// 获取最近的 50 条出库记录
const res = await getOutboundList({ page: 1, limit: 50 })
if (res.data && res.data.items) {
const names = new Set<string>()
// 加入当前用户
if (userStore.username) names.add(userStore.username)
// 加入历史记录中的操作员
res.data.items.forEach((item: any) => {
if (item.operator_name) {
names.add(item.operator_name)
}
})
operatorOptions.value = Array.from(names)
}
} catch (e) {
console.error('加载历史操作员失败', e)
}
} }
// --- 扫码逻辑 --- // --- 扫码逻辑 ---
@ -117,17 +187,35 @@ const handleScan = async () => {
try { try {
loading.value = true loading.value = true
const res = await getStockByBarcode(barcodeInput.value) const res = await getStockByBarcode(barcodeInput.value)
// 1. 成功找到记录
if (res.data) { if (res.data) {
currentItem.value = res.data const item = res.data
// 停止摄像头
// ★ [逻辑修改] 检查库存状态
if (item.available_quantity <= 0) {
ElMessage.warning(`该商品库存不足或已出库!(当前库存: ${item.available_quantity})`)
// 播放一个错误提示音或清空输入框让用户重新扫,但不进入表单
barcodeInput.value = ''
return
}
// 库存充足,进入确认界面
currentItem.value = item
// 如果开启了摄像头,识别成功后关闭
if (html5QrCode.value && html5QrCode.value.isScanning) { if (html5QrCode.value && html5QrCode.value.isScanning) {
await stopCamera() await stopCamera()
} }
} else {
ElMessage.warning('未找到对应库存条码')
} }
} catch (error) { } catch (error: any) {
console.error(error) // 2. 处理 404 未找到 (即没有入库记录)
if (error.response && error.response.status === 404) {
ElMessage.error(`未找到条码 ${barcodeInput.value} 的入库记录,请先入库!`)
} else {
console.error(error)
ElMessage.error('查询出错,请重试')
}
} finally { } finally {
loading.value = false loading.value = false
} }
@ -146,31 +234,27 @@ const toggleCamera = async () => {
} }
const startCamera = () => { const startCamera = () => {
// ★ [关键修改] 初始化时指定只支持 CODE_128这是提高条码识别率的关键
html5QrCode.value = new Html5Qrcode("reader", { html5QrCode.value = new Html5Qrcode("reader", {
formatsToSupport: [ Html5QrcodeSupportedFormats.CODE_128 ], formatsToSupport: [ Html5QrcodeSupportedFormats.CODE_128 ],
verbose: false verbose: false
}) })
html5QrCode.value.start( html5QrCode.value.start(
{ facingMode: "environment" }, // 后置摄像头 { facingMode: "environment" },
{ {
fps: 10, fps: 10,
// ★ [修改] 扫一维码时,扫描区域设置为长方形效果更好
qrbox: { width: 250, height: 150 }, qrbox: { width: 250, height: 150 },
aspectRatio: 1.0 aspectRatio: 1.0
}, },
(decodedText) => { (decodedText) => {
// 扫码成功回调
console.log("扫码成功:", decodedText) console.log("扫码成功:", decodedText)
barcodeInput.value = decodedText barcodeInput.value = decodedText
handleScan() // 自动触发查询 handleScan()
}, },
(errorMessage) => { (errorMessage) => {
// 扫描中错误忽略 // 忽略扫描过程中的每帧错误
} }
).catch(err => { ).catch(err => {
// 如果还报错,大概率是因为没有使用 HTTPS 访问
ElMessage.error('无法启动摄像头: ' + err) ElMessage.error('无法启动摄像头: ' + err)
}) })
} }
@ -178,7 +262,6 @@ const startCamera = () => {
const stopCamera = async () => { const stopCamera = async () => {
if (html5QrCode.value) { if (html5QrCode.value) {
try { try {
// 先判断是否在运行,避免报错
if (html5QrCode.value.isScanning) { if (html5QrCode.value.isScanning) {
await html5QrCode.value.stop() await html5QrCode.value.stop()
} }
@ -186,7 +269,6 @@ const stopCamera = async () => {
showCamera.value = false showCamera.value = false
} catch (err) { } catch (err) {
console.log('停止摄像头失败', err) console.log('停止摄像头失败', err)
// 强制关闭 UI 状态
showCamera.value = false showCamera.value = false
} }
} }
@ -194,14 +276,13 @@ const stopCamera = async () => {
// --- 提交逻辑 --- // --- 提交逻辑 ---
const submitForm = async () => { const submitForm = async () => {
if (!formRef.value) return // 确保 formRef 存在 if (!formRef.value) return
await formRef.value.validate(async (valid: boolean) => { await formRef.value.validate(async (valid: boolean) => {
if (!valid) return if (!valid) return
if (!currentItem.value) return if (!currentItem.value) return
// 1. 获取签名图片
const file = await signatureRef.value.generateFile() const file = await signatureRef.value.generateFile()
if (!file) { if (!file) {
ElMessage.error('请先进行电子签名') ElMessage.error('请先进行电子签名')
@ -211,11 +292,11 @@ const submitForm = async () => {
try { try {
loading.value = true loading.value = true
// 2. 上传签名 // 1. 上传签名
const uploadRes = await uploadFile(file) const uploadRes = await uploadFile(file)
const signatureUrl = uploadRes.data.url const signatureUrl = uploadRes.data.url
// 3. 提交业务单据 // 2. 提交业务单据
await submitOutbound({ await submitOutbound({
sku: currentItem.value.sku, sku: currentItem.value.sku,
source_table: currentItem.value.source_table, source_table: currentItem.value.source_table,
@ -224,12 +305,17 @@ const submitForm = async () => {
outbound_type: form.outbound_type, outbound_type: form.outbound_type,
quantity: form.quantity, quantity: form.quantity,
consumer_name: form.consumer_name, consumer_name: form.consumer_name,
// ★ 传递操作员信息 (注需要确保后端接收此字段否则后端可能仍使用当前JWT用户)
// 建议在后端 create_outbound 接口中优先使用前端传来的 operator_name
operator_name: form.operator_name,
remark: form.remark, remark: form.remark,
signature_path: signatureUrl signature_path: signatureUrl
}) })
ElMessage.success('出库成功') ElMessage.success('出库成功')
resetScan() resetScan()
// 提交成功后,刷新一次操作员列表,以便下次能选到新名字
loadHistoryOperators()
} catch (error) { } catch (error) {
console.error(error) console.error(error)
@ -245,9 +331,12 @@ const resetScan = () => {
form.consumer_name = '' form.consumer_name = ''
form.quantity = 1 form.quantity = 1
form.remark = '' form.remark = ''
signatureRef.value?.clear() // 清空签名 // 重置为当前用户,但不清空选项
if (userStore.username) {
form.operator_name = userStore.username
}
// 重新聚焦输入框 signatureRef.value?.clear()
nextTick(() => { nextTick(() => {
barcodeRef.value?.focus() barcodeRef.value?.focus()
}) })
@ -264,8 +353,8 @@ onUnmounted(() => {
padding: 20px; padding: 20px;
} }
.camera-box { .camera-box {
width: 100%; /* 响应式宽度 */ width: 100%;
max-width: 400px; /* 限制最大宽度 */ max-width: 400px;
height: 300px; height: 300px;
margin: 0 auto 20px; margin: 0 auto 20px;
background: #000; background: #000;

View File

@ -1,7 +1,14 @@
<template> <template>
<div class="app-container"> <div class="app-container">
<div class="filter-container"> <div class="filter-container">
<el-input v-model="listQuery.keyword" placeholder="单号/姓名/SKU" style="width: 200px;" class="filter-item" /> <el-input
v-model="listQuery.keyword"
placeholder="单号/姓名/SKU"
style="width: 200px;"
class="filter-item"
clearable
@keyup.enter="fetchData"
/>
<el-date-picker <el-date-picker
v-model="listQuery.dateRange" v-model="listQuery.dateRange"
type="daterange" type="daterange"
@ -10,44 +17,75 @@
end-placeholder="结束日期" end-placeholder="结束日期"
class="filter-item" class="filter-item"
style="margin-left: 10px;" style="margin-left: 10px;"
value-format="YYYY-MM-DD"
/> />
<el-button type="primary" class="filter-item" style="margin-left: 10px;" @click="fetchData">查询</el-button> <el-button type="primary" class="filter-item" style="margin-left: 10px;" @click="fetchData">查询</el-button>
<el-button type="success" class="filter-item" @click="$router.push('/stock/outbound/create')">新建出库</el-button> <el-button type="success" class="filter-item" @click="$router.push('/outbound/create')">新建出库</el-button>
</div> </div>
<el-table :data="list" v-loading="loading" border style="width: 100%; margin-top: 20px;"> <el-table
<el-table-column prop="outbound_no" label="出库单号" width="180" /> :data="list"
<el-table-column prop="outbound_time" label="出库时间" width="180" /> v-loading="loading"
<el-table-column prop="outbound_type" label="类型" width="100"> border
style="width: 100%; margin-top: 20px;"
:header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
>
<el-table-column prop="outbound_no" label="出库单号" min-width="180" show-overflow-tooltip />
<el-table-column prop="outbound_time" label="出库时间" width="170" align="center">
<template #default="{ row }"> <template #default="{ row }">
<el-tag>{{ formatType(row.outbound_type) }}</el-tag> <span>{{ row.outbound_time ? row.outbound_time.substring(0, 16) : '' }}</span>
</template> </template>
</el-table-column> </el-table-column>
<el-table-column prop="sku" label="SKU" width="150" />
<el-table-column prop="quantity" label="数量" width="100" /> <el-table-column prop="outbound_type" label="类型" width="100" align="center">
<el-table-column prop="consumer_name" label="领用/客户" width="120" />
<el-table-column prop="operator_name" label="操作员" width="120" />
<el-table-column label="签名" width="100" align="center">
<template #default="{ row }"> <template #default="{ row }">
<el-button type="primary" link @click="viewSignature(row.signature_path)">查看</el-button> <el-tag :type="getTagType(row.outbound_type)">{{ formatType(row.outbound_type) }}</el-tag>
</template>
</el-table-column>
<el-table-column prop="sku" label="SKU" min-width="140" show-overflow-tooltip />
<el-table-column prop="quantity" label="数量" width="90" align="center" />
<el-table-column prop="consumer_name" label="领用/客户" min-width="120" show-overflow-tooltip />
<el-table-column prop="operator_name" label="操作员" min-width="100" show-overflow-tooltip />
<el-table-column prop="remark" label="备注" min-width="150" show-overflow-tooltip />
<el-table-column label="签名" width="120" align="center">
<template #default="{ row }">
<div v-if="row.signature_path" class="signature-cell">
<el-image
style="width: 80px; height: 40px; border-radius: 4px; border: 1px solid #dcdfe6;"
:src="row.signature_path"
:preview-src-list="[row.signature_path]"
preview-teleported
fit="contain"
hide-on-click-modal
>
<template #error>
<div class="image-slot">
<el-icon><Picture /></el-icon>
</div>
</template>
</el-image>
</div>
<span v-else style="color: #909399; font-size: 12px;">未签名</span>
</template> </template>
</el-table-column> </el-table-column>
</el-table> </el-table>
<el-dialog v-model="dialogVisible" title="电子签名凭证" width="500px">
<img :src="currentSignature" style="width: 100%; border: 1px solid #eee;" alt="Signature" />
</el-dialog>
</div> </div>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { ref, onMounted, reactive } from 'vue' import { ref, onMounted, reactive } from 'vue'
import { getOutboundList } from '@/api/outbound' import { getOutboundList } from '@/api/outbound'
import { Picture } from '@element-plus/icons-vue' // 引入图标用于图片加载失败显示
const list = ref([]) const list = ref([])
const loading = ref(false) const loading = ref(false)
const dialogVisible = ref(false)
const currentSignature = ref('')
const listQuery = reactive({ const listQuery = reactive({
keyword: '', keyword: '',
@ -58,7 +96,7 @@ const fetchData = async () => {
loading.value = true loading.value = true
try { try {
const res = await getOutboundList(listQuery) const res = await getOutboundList(listQuery)
list.value = res.data.items || [] // 假设后端返回 { items: [] } list.value = res.data.items || []
} catch (e) { } catch (e) {
console.error(e) console.error(e)
} finally { } finally {
@ -76,12 +114,36 @@ const formatType = (type: string) => {
return map[type] || type return map[type] || type
} }
const viewSignature = (url: string) => { // 辅助函数:根据类型返回 Tag 颜色
currentSignature.value = url // 这里可能需要拼接 BaseURL取决于你 upload 接口返回的是相对路径还是绝对路径 const getTagType = (type: string) => {
dialogVisible.value = true const map: any = {
'SALES': 'success',
'USE': 'warning',
'TRANSFER': 'info',
'SCRAP': 'danger'
}
return map[type] || ''
} }
onMounted(() => { onMounted(() => {
fetchData() fetchData()
}) })
</script> </script>
<style scoped>
.signature-cell {
display: flex;
justify-content: center;
align-items: center;
padding: 2px 0;
}
.image-slot {
display: flex;
justify-content: center;
align-items: center;
width: 100%;
height: 100%;
background: #f5f7fa;
color: #909399;
}
</style>

View File

@ -17,7 +17,7 @@ export default defineConfig({
// 允许局域网访问前端页面 // 允许局域网访问前端页面
host: '0.0.0.0', host: '0.0.0.0',
port: 5173, port: 5173,
https: true, // ★ [新增] 强制开启 HTTPS否则浏览器会拦截摄像头 https: false, // ★ [新增] 强制开启 HTTPS否则浏览器会拦截摄像头
proxy: { proxy: {
// 拦截所有以 /api 开头的请求 // 拦截所有以 /api 开头的请求
'/api': { '/api': {