摄像头逻辑进行修改,更改分辨率进行快速的读取识别

This commit is contained in:
dxc
2026-02-06 11:28:48 +08:00
parent e027ebd4a9
commit 489e62e55b
7 changed files with 788 additions and 708 deletions

View File

@ -1,9 +1,10 @@
from flask import Blueprint, jsonify, request from flask import Blueprint, jsonify, request
# ★ [核心修复] 导入正确的模型类名 StockBuy (替换原来的 InboundBuy) from app.extensions import db
# 导入模型
from app.models.inbound.buy import StockBuy from app.models.inbound.buy import StockBuy
from app.models.inbound.stocktake import StocktakeDraft # 新增
# 尝试导入半成品和成品模型 (根据你的命名习惯修正为 StockSemi/StockProduct) # 尝试导入半成品和成品
# 使用 try-except 防止如果其他文件还没改名导致再次报错
try: try:
from app.models.inbound.semi import StockSemi from app.models.inbound.semi import StockSemi
except ImportError: except ImportError:
@ -22,30 +23,27 @@ bp = Blueprint('stock_ops', __name__)
@bp.route('/all', methods=['GET']) @bp.route('/all', methods=['GET'])
def get_all_stock(): def get_all_stock():
""" """
获取所有在库物品(采购件+半成品+成品 获取所有库存 > 0 的物品(无论状态是 在库 还是 部分出库
用于:盘点初始化、出库选单列表
""" """
try: try:
# 1. 获取采购件 # 1. 采购件 (核心修改:只看库存数量 > 0)
# ★ [核心修复] 使用 StockBuy 查询,并将状态条件改为 '在库' (匹配你的 Model 定义)
materials = [] materials = []
if StockBuy: if StockBuy:
materials = StockBuy.query.filter(StockBuy.status == '在库').all() materials = StockBuy.query.filter(StockBuy.stock_quantity > 0).all()
# 2. 获取半成品 # 2. 半成品
semis = [] semis = []
if StockSemi: if StockSemi:
try: try:
# 假设半成品也使用 '在库' 状态 semis = StockSemi.query.filter(StockSemi.stock_quantity > 0).all()
semis = StockSemi.query.filter(StockSemi.status == '在库').all()
except Exception: except Exception:
semis = [] semis = []
# 3. 获取成品 # 3. 成品
products = [] products = []
if StockProduct: if StockProduct:
try: try:
products = StockProduct.query.filter(StockProduct.status == '在库').all() products = StockProduct.query.filter(StockProduct.stock_quantity > 0).all()
except Exception: except Exception:
products = [] products = []
@ -55,44 +53,69 @@ def get_all_stock():
"products": [item.to_dict() for item in products] "products": [item.to_dict() for item in products]
}), 200 }), 200
except Exception as e: except Exception as e:
print(f"Error in get_all_stock: {e}") # 输出错误日志以便调试 print(f"Error: {e}")
return jsonify({"message": f"查询库存失败: {str(e)}"}), 500 return jsonify({"message": f"查询库存失败: {str(e)}"}), 500
# --- 草稿箱接口 (断点续传) ---
@bp.route('/draft/list', methods=['GET'])
def get_drafts():
"""获取当前用户的盘点进度"""
user_id = request.args.get('user_id', 'admin')
drafts = StocktakeDraft.query.filter_by(user_id=user_id).all()
return jsonify([d.to_dict() for d in drafts]), 200
@bp.route('/draft/add', methods=['POST'])
def add_draft():
"""扫码同步"""
data = request.json
user_id = data.get('user_id', 'admin')
uuid = data.get('uuid')
# 避免重复插入
exists = StocktakeDraft.query.filter_by(user_id=user_id, uuid=uuid).first()
if not exists:
draft = StocktakeDraft(user_id=user_id, uuid=uuid)
db.session.add(draft)
db.session.commit()
return jsonify({"message": "Saved"}), 200
@bp.route('/draft/clear', methods=['POST'])
def clear_draft():
"""清空进度 (开始新盘点或结束后)"""
data = request.json
user_id = data.get('user_id', 'admin')
StocktakeDraft.query.filter_by(user_id=user_id).delete()
db.session.commit()
return jsonify({"message": "Cleared"}), 200
# --- 打印接口 (保持不变) ---
@bp.route('/print/selection', methods=['POST']) @bp.route('/print/selection', methods=['POST'])
def print_selection(): def print_selection():
"""打印出库选单"""
try: try:
data = request.json data = request.json
items = data.get('items', []) items = data.get('items', [])
if not items: return jsonify({"message": "未选择任何物品"}), 400
if not items: printer = NetworkPrintService()
return jsonify({"message": "未选择任何物品"}), 400
printer = NetworkPrintService() # 默认连接 192.168.9.205
success, msg = printer.print_outbound_selection(items) success, msg = printer.print_outbound_selection(items)
return jsonify({"message": "打印指令已发送" if success else msg}), 200 if success else 500
if success:
return jsonify({"message": "打印指令已发送"}), 200
else:
return jsonify({"message": msg}), 500
except Exception as e: except Exception as e:
return jsonify({"message": f"打印服务错误: {str(e)}"}), 500 return jsonify({"message": str(e)}), 500
@bp.route('/print/stocktake', methods=['POST']) @bp.route('/print/stocktake', methods=['POST'])
def print_stocktake(): def print_stocktake():
"""打印盘点报告"""
try: try:
data = request.json data = request.json
# data 结构: { total, scanned, missing, missing_items: [] }
printer = NetworkPrintService() printer = NetworkPrintService()
success, msg = printer.print_stocktake_report(data) success, msg = printer.print_stocktake_report(data)
return jsonify({"message": "盘点报告已发送" if success else msg}), 200 if success else 500
if success:
return jsonify({"message": "盘点报告已发送"}), 200
else:
return jsonify({"message": msg}), 500
except Exception as e: except Exception as e:
return jsonify({"message": f"打印服务错误: {str(e)}"}), 500 return jsonify({"message": str(e)}), 500

View File

@ -0,0 +1,19 @@
from app.extensions import db
from datetime import datetime
class StocktakeDraft(db.Model):
"""盘点草稿表"""
__tablename__ = 'stocktake_draft'
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.String(100), default='admin')
uuid = db.Column(db.String(100))
scan_time = db.Column(db.DateTime, default=datetime.now)
def to_dict(self):
return {
'id': self.id,
'user_id': self.user_id,
'uuid': self.uuid,
'scan_time': self.scan_time.strftime('%Y-%m-%d %H:%M:%S')
}

View File

@ -139,8 +139,8 @@ class LabelPrintService:
CURRENT_Y = LabelPrintService.TOP_MARGIN_PX CURRENT_Y = LabelPrintService.TOP_MARGIN_PX
# --- A. 绘制条形码 (居中) --- # --- A. 绘制条形码 (居中) ---
bc_w = int(35 * LabelPrintService.DOTS_PER_MM) bc_w = int(37 * LabelPrintService.DOTS_PER_MM)
bc_h = int(7 * LabelPrintService.DOTS_PER_MM) # 高度 bc_h = int(8 * LabelPrintService.DOTS_PER_MM) # 高度
bc_img = LabelPrintService._generate_barcode_image(sku_code, bc_w, bc_h) bc_img = LabelPrintService._generate_barcode_image(sku_code, bc_w, bc_h)

View File

@ -13,6 +13,8 @@
"axios": "^1.13.3", "axios": "^1.13.3",
"element-plus": "^2.13.1", "element-plus": "^2.13.1",
"html5-qrcode": "^2.3.8", "html5-qrcode": "^2.3.8",
"jspdf": "^2.5.1",
"jspdf-autotable": "^3.8.2",
"pinia": "^3.0.4", "pinia": "^3.0.4",
"sass": "^1.97.3", "sass": "^1.97.3",
"vue": "^3.5.24", "vue": "^3.5.24",

View File

@ -4,9 +4,16 @@
<div v-if="errorMsg" class="error-msg">{{ errorMsg }}</div> <div v-if="errorMsg" class="error-msg">{{ errorMsg }}</div>
<div class="focus-tip" v-if="!errorMsg"> <div class="focus-tip" v-if="!errorMsg && !isPaused">
<div class="scan-line"></div> <div class="scan-line"></div>
<div class="scan-text">将条码对准取景</div> <div class="scan-text">将条码横向填满红</div>
</div>
<div class="focus-tip success" v-if="isPaused">
<div class="scan-text-success">
<el-icon><CircleCheckFilled /></el-icon>
扫描成功3秒后继续...
</div>
</div> </div>
</div> </div>
</template> </template>
@ -14,9 +21,13 @@
<script setup lang="ts"> <script setup lang="ts">
import { onMounted, onUnmounted, ref } from 'vue' import { onMounted, onUnmounted, ref } from 'vue'
import { Html5Qrcode, Html5QrcodeSupportedFormats } from 'html5-qrcode' import { Html5Qrcode, Html5QrcodeSupportedFormats } from 'html5-qrcode'
import { CircleCheckFilled } from '@element-plus/icons-vue' // 引入图标用于成功提示
// 定义事件
const emit = defineEmits(['decode', 'error']) const emit = defineEmits(['decode', 'error'])
const errorMsg = ref('') const errorMsg = ref('')
const isPaused = ref(false) // ★ 新增:控制暂停状态
let html5QrCode: Html5Qrcode | null = null let html5QrCode: Html5Qrcode | null = null
const scannerElementId = "qr-reader" const scannerElementId = "qr-reader"
@ -34,17 +45,15 @@ const startScanning = async () => {
// 2. 启动配置 // 2. 启动配置
const config = { const config = {
fps: 25, fps: 20,
qrbox: { width: 250, height: 100 }, // 扫描区域设置 qrbox: { width: 320, height: 60 },
// ★★★ 修复点1移除 aspectRatio让画面自适应容器长宽比 ★★★
// aspectRatio: 1.0,
disableFlip: false, disableFlip: false,
videoConstraints: { videoConstraints: {
facingMode: "environment", facingMode: "environment",
// 限制分辨率,保证速度 width: { min: 1280, ideal: 1920, max: 3840 },
width: { min: 640, ideal: 1280, max: 1920 }, height: { min: 720, ideal: 1080, max: 2160 },
height: { min: 480, ideal: 720, max: 1080 }, focusMode: "continuous",
focusMode: "continuous" advanced: [{ focusMode: "macro" }]
} }
} }
@ -53,8 +62,21 @@ const startScanning = async () => {
{ facingMode: "environment" }, { facingMode: "environment" },
config, config,
(decodedText) => { (decodedText) => {
// ★ 核心修改:如果处于暂停冷却期,直接忽略后续扫描结果
if (isPaused.value) return
console.log(`Scan: ${decodedText}`) console.log(`Scan: ${decodedText}`)
// 1. 锁定状态
isPaused.value = true
// 2. 发送数据
emit('decode', decodedText) emit('decode', decodedText)
// 3. 开启 3 秒倒计时解锁
setTimeout(() => {
isPaused.value = false
}, 3000)
}, },
(errorMessage) => { (errorMessage) => {
// ignore // ignore
@ -65,7 +87,8 @@ const startScanning = async () => {
const errStr = err.toString() const errStr = err.toString()
if (errStr.includes('Permission')) msg = '请允许摄像头权限' if (errStr.includes('Permission')) msg = '请允许摄像头权限'
else if (errStr.includes('Secure')) msg = '需要 HTTPS 或 localhost' else if (errStr.includes('Secure')) msg = '需要 HTTPS 或 localhost'
else if (errStr.includes('NotFound')) msg = '未检测到摄像头' else if (errStr.includes('NotFound')) msg = '未检测到后置摄像头'
else if (errStr.includes('OverconstrainedError')) msg = '摄像头不支持高分辨率'
console.error("Scanner Error:", err) console.error("Scanner Error:", err)
errorMsg.value = msg errorMsg.value = msg
@ -89,7 +112,7 @@ const stopScanning = async () => {
onMounted(() => { onMounted(() => {
setTimeout(() => { setTimeout(() => {
startScanning() startScanning()
}, 300) }, 500)
}) })
onUnmounted(() => { onUnmounted(() => {
@ -107,17 +130,15 @@ onUnmounted(() => {
flex-direction: column; flex-direction: column;
justify-content: center; justify-content: center;
align-items: center; align-items: center;
overflow: hidden; /* 关键:裁剪多余画面 */ overflow: hidden;
border-radius: 12px; /* 保持圆角 */ border-radius: 12px;
} }
.scanner-box { .scanner-box {
width: 100%; width: 100%;
height: 100%; height: 100%;
position: relative;
} }
/* ★★★ 修复点2强制 Video 元素填满容器 ★★★ */
:deep(#qr-reader) { :deep(#qr-reader) {
width: 100%; width: 100%;
height: 100%; height: 100%;
@ -128,17 +149,11 @@ onUnmounted(() => {
:deep(#qr-reader video) { :deep(#qr-reader video) {
width: 100% !important; width: 100% !important;
height: 100% !important; height: 100% !important;
object-fit: cover !important; /* 关键:保持比例铺满,裁剪多余部分 */ object-fit: cover !important;
border-radius: 12px;
display: block !important; display: block !important;
border-radius: 12px;
} }
/* 隐藏 html5-qrcode 可能自带的遮罩层,我们用自己的 */
:deep(#qr-reader__scan_region) {
display: none !important;
}
/* 自定义错误提示 */
.error-msg { .error-msg {
position: absolute; position: absolute;
top: 50%; top: 50%;
@ -158,62 +173,56 @@ onUnmounted(() => {
top: 50%; top: 50%;
left: 50%; left: 50%;
transform: translate(-50%, -50%); transform: translate(-50%, -50%);
width: 250px; width: 320px;
height: 120px; height: 60px;
/* 使用半透明黑边框模拟遮罩效果,突出中间区域 */ border: 2px solid rgba(255, 0, 0, 0.6);
box-shadow: 0 0 0 2000px rgba(0, 0, 0, 0.6); border-radius: 6px;
border: 1px solid rgba(255, 255, 255, 0.6);
border-radius: 8px;
pointer-events: none; pointer-events: none;
box-shadow: 0 0 0 2000px rgba(0, 0, 0, 0.6);
z-index: 10; z-index: 10;
display: flex; display: flex;
justify-content: center; justify-content: center;
align-items: center; align-items: center;
transition: all 0.3s;
} }
/* 四个角的装饰 */ /* ★ 扫描成功时的绿色框样式 */
.focus-tip::before, .focus-tip.success {
.focus-tip::after { border-color: #67c23a; /* 绿色边框 */
content: ''; background: rgba(103, 194, 58, 0.1);
position: absolute;
width: 20px;
height: 20px;
border-color: #409EFF;
border-style: solid;
border-width: 0;
}
.focus-tip::before {
top: -1px; left: -1px;
border-top-width: 3px;
border-left-width: 3px;
}
.focus-tip::after {
bottom: -1px; right: -1px;
border-bottom-width: 3px;
border-right-width: 3px;
} }
/* 红色扫描线动画 */
.scan-line { .scan-line {
width: 90%; width: 95%;
height: 2px; height: 2px;
background: #ff0000; background: #ff0000;
box-shadow: 0 0 4px #ff0000; box-shadow: 0 0 4px #ff0000;
animation: scan-move 2s infinite linear; position: absolute;
animation: scan-move 1.5s infinite ease-in-out;
} }
.scan-text { .scan-text {
position: absolute; position: absolute;
bottom: -30px; bottom: -35px;
color: #fff; color: rgba(255, 255, 255, 0.9);
font-size: 12px; font-size: 13px;
opacity: 0.8; white-space: nowrap;
text-shadow: 0 1px 2px #000;
}
.scan-text-success {
color: #67c23a;
font-size: 16px;
font-weight: bold;
display: flex;
align-items: center;
gap: 5px;
text-shadow: 0 1px 3px rgba(0,0,0,0.8);
} }
@keyframes scan-move { @keyframes scan-move {
0% { transform: translateY(-40px); opacity: 0; } 0% { top: 10%; opacity: 0.5; }
10% { opacity: 1; } 50% { top: 90%; opacity: 1; }
90% { opacity: 1; } 100% { top: 10%; opacity: 0.5; }
100% { transform: translateY(40px); opacity: 0; }
} }
</style> </style>

View File

@ -1,139 +1,150 @@
<template> <template>
<div class="app-container"> <div class="app-container mobile-optimized">
<el-card class="box-card"> <el-card class="box-card" shadow="never">
<template #header> <template #header>
<div class="card-header"> <div class="card-header">
<span>批量扫码出库作业台</span> <div class="title-box">
<div class="header-right"> <span>批量出库作业</span>
<span v-if="cartItems.length > 0" class="summary-text"> <el-tag v-if="cartItems.length > 0" type="warning" size="small" effect="dark">
已选: <span class="num">{{ cartItems.length }}</span> | 已选 {{ cartItems.length }}
总金额: <span class="price">¥{{ totalAmount.toFixed(2) }}</span> </el-tag>
</span> </div>
<el-button type="primary" @click="toggleCamera" style="margin-left: 10px;"> <div class="header-price" v-if="totalAmount > 0">
{{ showCamera ? '关闭摄像头' : '打开摄像头扫码' }} ¥{{ totalAmount.toFixed(2) }}
</el-button>
</div> </div>
</div> </div>
</template> </template>
<div class="scan-area"> <div class="scan-section">
<div v-if="showCamera" id="reader" class="camera-box"></div> <div v-if="showCamera" class="camera-wrapper">
<div v-if="isHttpAndNotLocal" class="http-warning"> <QrScanner @decode="onScanSuccess" />
注意当前为 HTTP 环境摄像头可能无法启动请使用 HTTPS localhost或配置浏览器安全白名单 <div class="scan-overlay">
<el-button type="info" size="small" bg text @click="showCamera = false" icon="Close">
关闭摄像头
</el-button>
</div>
</div>
<div v-else class="camera-placeholder" @click="showCamera = true">
<el-icon :size="40" color="#409EFF"><CameraFilled /></el-icon>
<span class="text">点击开启扫码</span>
</div> </div>
<div class="input-box"> <div class="input-box">
<el-input <el-input
v-model="barcodeInput" v-model="barcodeInput"
placeholder="请连续扫描条码或手动输入后回车" placeholder="扫描或输入条码回车"
@keyup.enter="handleScan" @keyup.enter="handleManualInput"
clearable clearable
ref="barcodeRef" ref="barcodeRef"
class="scan-input" size="large"
> >
<template #prefix> <template #prefix>
<el-icon><Scissor /></el-icon> <el-icon><Scissor /></el-icon>
</template> </template>
<template #append> <template #append>
<el-button @click="handleScan">添加商品</el-button> <el-button @click="handleManualInput">添加</el-button>
</template> </template>
</el-input> </el-input>
</div> </div>
</div> </div>
<div class="cart-area mt-20" v-if="cartItems.length > 0"> <div class="cart-section">
<el-table :data="cartItems" border stripe style="width: 100%"> <div v-if="cartItems.length > 0">
<el-table-column prop="name" label="名称" show-overflow-tooltip /> <el-table :data="cartItems" border stripe style="width: 100%">
<el-table-column prop="spec_model" label="规格" show-overflow-tooltip /> <el-table-column prop="name" label="物品名称" min-width="120" show-overflow-tooltip />
<el-table-column prop="sku" label="SKU" width="150" /> <el-table-column prop="spec_model" label="规格" min-width="100" show-overflow-tooltip />
<el-table-column label="单价" width="120"> <el-table-column prop="sku" label="SKU" width="120" show-overflow-tooltip />
<template #default="{row}">
¥{{ row.price }}
</template>
</el-table-column>
<el-table-column label="库存" width="100">
<template #default="{row}">
<el-tag :type="row.available_quantity > 0 ? 'success' : 'danger'">{{ row.available_quantity }}</el-tag>
</template>
</el-table-column>
<el-table-column label="出库数量" width="160">
<template #default="{row}">
<el-input-number v-model="row.out_quantity" :min="1" :max="row.available_quantity" size="small" />
</template>
</el-table-column>
<el-table-column label="小计" width="120">
<template #default="{row}">
<span style="color: #F56C6C; font-weight: bold;">¥{{ (row.price * row.out_quantity).toFixed(2) }}</span>
</template>
</el-table-column>
<el-table-column label="操作" width="80" align="center">
<template #default="{$index}">
<el-button type="danger" icon="Delete" circle size="small" @click="removeFromCart($index)" />
</template>
</el-table-column>
</el-table>
</div>
<el-empty v-else description="暂无扫描商品,请扫描上方条码进行添加" />
<div v-if="cartItems.length > 0" class="confirm-area mt-20"> <el-table-column label="库存" width="70" align="center">
<el-divider content-position="left">单据信息</el-divider> <template #default="{row}">
<el-tag :type="row.available_quantity > 0 ? 'success' : 'danger'" size="small">
{{ parseFloat(row.available_quantity) }}
</el-tag>
</template>
</el-table-column>
<el-table-column label="出库数" width="130" align="center">
<template #default="{row}">
<el-input-number
v-model="row.out_quantity"
:min="1"
:max="parseFloat(row.available_quantity)"
size="small"
style="width: 100px"
/>
</template>
</el-table-column>
<el-table-column label="操作" width="60" align="center" fixed="right">
<template #default="{$index}">
<el-button type="danger" icon="Delete" circle size="small" @click="removeFromCart($index)" />
</template>
</el-table-column>
</el-table>
</div>
<el-empty v-else description="暂无商品,请扫码添加" :image-size="80" />
</div>
<div v-if="cartItems.length > 0" class="form-section">
<el-divider content-position="left">出库单据信息</el-divider>
<el-form :model="form" ref="formRef" :rules="rules" label-position="top"> <el-form :model="form" ref="formRef" :rules="rules" label-position="top">
<el-row :gutter="20"> <el-row :gutter="15">
<el-col :span="8"> <el-col :span="24" :md="8">
<el-form-item label="出库类型" prop="outbound_type"> <el-form-item label="出库类型" prop="outbound_type">
<el-select v-model="form.outbound_type" placeholder="请选择" style="width: 100%"> <el-select v-model="form.outbound_type" placeholder="请选择类型" style="width: 100%">
<el-option label="销售出库" value="SALES" /> <el-option label="销售出库" value="SALES" />
<el-option label="内部领用" value="USE" /> <el-option label="内部领用" value="USE" />
<el-option label="调拨" value="TRANSFER" /> <el-option label="调拨出库" value="TRANSFER" />
</el-select> </el-select>
</el-form-item> </el-form-item>
</el-col> </el-col>
<el-col :span="8">
<el-form-item label="领用人/客户姓名" prop="consumer_name"> <el-col :span="24" :md="8">
<el-form-item label="领用人/客户" prop="consumer_name">
<el-input v-model="form.consumer_name" placeholder="请输入姓名" /> <el-input v-model="form.consumer_name" placeholder="请输入姓名" />
</el-form-item> </el-form-item>
</el-col> </el-col>
<el-col :span="8">
<el-form-item label="操作员 (库管)" prop="operator_name"> <el-col :span="24" :md="8">
<el-form-item label="经办人 (库管)" prop="operator_name">
<el-select <el-select
v-model="form.operator_name" v-model="form.operator_name"
filterable filterable
allow-create allow-create
default-first-option default-first-option
placeholder="选择或输入操作员" placeholder="选择或输入"
style="width: 100%" style="width: 100%"
> >
<el-option <el-option v-for="item in operatorOptions" :key="item" :label="item" :value="item" />
v-for="item in operatorOptions"
:key="item"
:label="item"
:value="item"
/>
</el-select> </el-select>
</el-form-item> </el-form-item>
</el-col> </el-col>
</el-row> </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" :rows="2" placeholder="可选填" />
</el-form-item> </el-form-item>
<el-form-item label="电子签名" required> <el-form-item label="电子签名确认" required>
<div class="signature-display-area"> <div class="signature-box" @click="openSignatureDialog">
<div v-if="signaturePreviewUrl" class="signed-image-box"> <div v-if="signaturePreviewUrl" class="signed-img">
<img :src="signaturePreviewUrl" alt="电子签名" /> <img :src="signaturePreviewUrl" alt="签名" />
<el-button type="text" @click="openSignatureDialog">重新签名</el-button> <span class="re-sign-tip">点击重签</span>
</div>
<div v-else class="unsigned-placeholder">
<el-icon :size="24"><EditPen /></el-icon>
<span>点击此处进行全屏签名</span>
</div> </div>
<el-button v-else type="primary" plain @click="openSignatureDialog" icon="EditPen">
点击进行全屏签名
</el-button>
</div> </div>
</el-form-item> </el-form-item>
<div class="form-actions"> <div class="bottom-actions">
<el-button @click="clearAll">清空重置</el-button> <el-button @click="clearAll" icon="Refresh">清空</el-button>
<el-button type="primary" size="large" :loading="loading" @click="submitForm">确认批量出库</el-button> <el-button type="primary" size="large" :loading="loading" @click="submitForm" icon="Select">
确认出库
</el-button>
</div> </div>
</el-form> </el-form>
</div> </div>
@ -160,14 +171,15 @@
@touchmove="draw" @touchmove="draw"
@touchend="stopDrawing" @touchend="stopDrawing"
></canvas> ></canvas>
<div class="canvas-tip">请在此区域横屏书写</div>
</div> </div>
<div class="signature-sidebar"> <div class="signature-sidebar">
<div class="sidebar-title">请在此区域书写</div> <div class="sidebar-title">电子签名</div>
<div class="sidebar-actions"> <div class="sidebar-actions">
<el-button type="warning" @click="clearCanvas"></el-button> <el-button type="warning" @click="clearCanvas"></el-button>
<el-button @click="handleSignCancel">取消</el-button> <el-button @click="handleSignCancel">取消</el-button>
<el-button type="success" class="confirm-btn" @click="handleSignConfirm">确认</el-button> <el-button type="success" class="confirm-btn" @click="handleSignConfirm">确认使用</el-button>
</div> </div>
</div> </div>
</div> </div>
@ -179,28 +191,25 @@
<script setup lang="ts"> <script setup lang="ts">
import { ref, reactive, nextTick, onUnmounted, onMounted, computed } from 'vue' import { ref, reactive, nextTick, onUnmounted, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus' import { ElMessage, ElMessageBox } from 'element-plus'
import { Html5Qrcode, Html5QrcodeSupportedFormats } from 'html5-qrcode' import { Scissor, EditPen, Delete, CameraFilled, Close, Refresh, Select } from '@element-plus/icons-vue'
import { Scissor, EditPen, Delete } from '@element-plus/icons-vue' import QrScanner from '@/components/QrScanner/index.vue'
import { getStockByBarcode, submitOutbound, getOutboundList } from '@/api/outbound' import { getStockByBarcode, submitOutbound, getOutboundList } from '@/api/outbound'
import { uploadFile } from '@/api/common/upload' import { uploadFile } from '@/api/common/upload'
import { useUserStore } from '@/stores/user' import { useUserStore } from '@/stores/user'
// --- 状态定义 --- // --- 状态定义 ---
const barcodeInput = ref('') const barcodeInput = ref('')
const cartItems = ref<any[]>([]) // 购物车列表 const cartItems = ref<any[]>([])
const loading = ref(false) const loading = ref(false)
const showCamera = ref(false) const showCamera = ref(false) // ★ 核心修改:默认改为 false
const html5QrCode = ref<Html5Qrcode | null>(null)
const barcodeRef = ref() const barcodeRef = ref()
const formRef = ref() const formRef = ref()
const userStore = useUserStore() const userStore = useUserStore()
// 签名相关状态 // 签名相关
const showSignatureDialog = ref(false) const showSignatureDialog = ref(false)
const signaturePreviewUrl = ref('') const signaturePreviewUrl = ref('')
const signatureFile = ref<File | null>(null) const signatureFile = ref<File | null>(null)
// 原生 Canvas 相关
const nativeCanvasRef = ref<HTMLCanvasElement | null>(null) const nativeCanvasRef = ref<HTMLCanvasElement | null>(null)
const canvasContainerRef = ref<HTMLElement | null>(null) const canvasContainerRef = ref<HTMLElement | null>(null)
const ctx = ref<CanvasRenderingContext2D | null>(null) const ctx = ref<CanvasRenderingContext2D | null>(null)
@ -222,18 +231,12 @@ const rules = {
operator_name: [{ required: true, message: '请指定操作员', trigger: 'change' }] operator_name: [{ required: true, message: '请指定操作员', trigger: 'change' }]
} }
const isHttpAndNotLocal = computed(() => {
const isHttps = window.location.protocol === 'https:'
const isLocal = ['localhost', '127.0.0.1'].includes(window.location.hostname)
return !isHttps && !isLocal
})
// 计算总金额 // 计算总金额
const totalAmount = computed(() => { const totalAmount = computed(() => {
return cartItems.value.reduce((sum, item) => sum + (item.price * item.out_quantity), 0) return cartItems.value.reduce((sum, item) => sum + (item.price * item.out_quantity), 0)
}) })
// --- 初始化逻辑 --- // --- 初始化 ---
onMounted(() => { onMounted(() => {
if (userStore.username) { if (userStore.username) {
form.operator_name = userStore.username form.operator_name = userStore.username
@ -248,11 +251,8 @@ const loadHistoryOperators = async () => {
if (res.data && res.data.items) { if (res.data && res.data.items) {
const names = new Set<string>() const names = new Set<string>()
if (userStore.username) names.add(userStore.username) if (userStore.username) names.add(userStore.username)
// 注意现在的列表结构变了operator_name 在外层
res.data.items.forEach((group: any) => { res.data.items.forEach((group: any) => {
if (group.operator_name) { if (group.operator_name) names.add(group.operator_name)
names.add(group.operator_name)
}
}) })
operatorOptions.value = Array.from(names) operatorOptions.value = Array.from(names)
} }
@ -261,56 +261,89 @@ const loadHistoryOperators = async () => {
} }
} }
// --- 扫码逻辑 (加入购物车) --- // --- 核心扫码逻辑 (适配 QrScanner 组件) ---
const handleScan = async () => { const onScanSuccess = (code: string) => {
if (!code) return
const trimCode = code.trim()
// ★★★ 核心修改:防误触校验 ★★★
// 1. 正则校验:只允许 数字、字母、横杠、点
// 这样可以屏蔽掉条码解析错误产生的 { } $ # 等乱码
const validPattern = /^[A-Za-z0-9\-\.]+$/
if (!validPattern.test(trimCode)) {
ElMessage.warning(`识别到异常符号,已忽略:${trimCode}`)
return
}
// 2. 长度校验:避免误扫到环境中的短数字
if (trimCode.length < 3) {
ElMessage.warning('扫描结果过短,请对准重试')
return
}
// 防抖:防止同一条码连续触发
if (loading.value) return
barcodeInput.value = trimCode
handleManualInput() // 复用手动输入逻辑
}
const handleManualInput = async () => {
const code = barcodeInput.value.trim() const code = barcodeInput.value.trim()
if (!code) return if (!code) return
try { try {
loading.value = true loading.value = true
// 1. 检查是否已经在购物车 // 1. 检查购物车重复
const existIndex = cartItems.value.findIndex(item => item.barcode === code || item.sku === code) const existIndex = cartItems.value.findIndex(item => item.barcode === code || item.sku === code)
if (existIndex > -1) { if (existIndex > -1) {
// 存在则数量+1
const item = cartItems.value[existIndex] const item = cartItems.value[existIndex]
if (item.out_quantity < item.available_quantity) { const maxQty = parseFloat(item.available_quantity)
if (item.out_quantity < maxQty) {
item.out_quantity++ item.out_quantity++
ElMessage.success(`商品 ${item.name} 数量+1`) ElMessage.success(`数量+1 (当前: ${item.out_quantity})`)
if (navigator.vibrate) navigator.vibrate(50)
} else { } else {
ElMessage.warning(`库存不足 (余: ${item.available_quantity})`) ElMessage.warning(`库存不足 (余: ${maxQty})`)
if (navigator.vibrate) navigator.vibrate([100, 50, 100])
} }
barcodeInput.value = '' barcodeInput.value = ''
return return
} }
// 2. 新商品调用 API // 2. 调用 API 查询
const res = await getStockByBarcode(code) const res = await getStockByBarcode(code)
if (res.data) { if (res.data) {
const item = res.data const item = res.data
if (item.available_quantity <= 0) { const availQty = parseFloat(item.available_quantity || 0)
ElMessage.warning(`该商品库存不足或已出库!(当前库存: ${item.available_quantity})`)
if (availQty <= 0) {
ElMessage.warning(`库存不足或已出库 (余: ${availQty})`)
if (navigator.vibrate) navigator.vibrate([100, 50, 100])
} else { } else {
// 加入购物车,默认出库 1 // 加入购物车
cartItems.value.push({ cartItems.value.push({
...item, ...item,
out_quantity: 1, out_quantity: 1,
price: item.price || 0 price: parseFloat(item.price || 0)
}) })
ElMessage.success('添加成功') ElMessage.success(`添加成功: ${item.name}`)
if (navigator.vibrate) navigator.vibrate(100)
} }
barcodeInput.value = '' barcodeInput.value = ''
} }
} catch (error: any) { } catch (error: any) {
if (error.response && error.response.status === 404) { if (error.response && error.response.status === 404) {
ElMessage.error(`未找到条码 ${barcodeInput.value} 的入库记录`) ElMessage.error(`未找到条码: ${code}`)
} else { } else {
console.error(error) ElMessage.error('查询出错')
ElMessage.error('查询出错,请重试')
} }
if (navigator.vibrate) navigator.vibrate([200, 100, 200])
} finally { } finally {
loading.value = false loading.value = false
// 聚焦输入框 // 聚焦输入框,方便连续扫
nextTick(() => { barcodeRef.value?.focus() }) nextTick(() => { barcodeRef.value?.focus() })
} }
} }
@ -320,25 +353,21 @@ const removeFromCart = (index: number) => {
} }
const clearAll = () => { const clearAll = () => {
ElMessageBox.confirm('确定清空所有已商品和填写信息吗?', '提示', { ElMessageBox.confirm('确定清空所有已商品吗?', '提示', { type: 'warning' })
type: 'warning' .then(() => {
}).then(() => { cartItems.value = []
cartItems.value = [] form.consumer_name = ''
form.consumer_name = '' form.remark = ''
form.remark = '' signatureFile.value = null
signatureFile.value = null signaturePreviewUrl.value = ''
signaturePreviewUrl.value = '' barcodeInput.value = ''
barcodeInput.value = '' })
})
} }
// --- 提交逻辑 (批量提交) --- // --- 提交逻辑 ---
const submitForm = async () => { const submitForm = async () => {
if (!formRef.value) return if (!formRef.value) return
if (cartItems.value.length === 0) { if (cartItems.value.length === 0) return ElMessage.warning('请先添加商品')
ElMessage.warning('购物车为空,请先扫码')
return
}
await formRef.value.validate(async (valid: boolean) => { await formRef.value.validate(async (valid: boolean) => {
if (!valid) return if (!valid) return
@ -351,11 +380,10 @@ const submitForm = async () => {
try { try {
loading.value = true loading.value = true
// 1. 上传签名 // 上传签名
const uploadRes = await uploadFile(signatureFile.value) const uploadRes = await uploadFile(signatureFile.value)
const signatureUrl = uploadRes.data.url const signatureUrl = uploadRes.data.url
// 2. 构造 items 数据
const itemsPayload = cartItems.value.map(item => ({ const itemsPayload = cartItems.value.map(item => ({
stock_id: item.id, stock_id: item.id,
source_table: item.source_table, source_table: item.source_table,
@ -365,7 +393,6 @@ const submitForm = async () => {
price: item.price price: item.price
})) }))
// 3. 提交业务单据
await submitOutbound({ await submitOutbound({
items: itemsPayload, items: itemsPayload,
outbound_type: form.outbound_type, outbound_type: form.outbound_type,
@ -375,160 +402,73 @@ const submitForm = async () => {
signature_path: signatureUrl signature_path: signatureUrl
}) })
ElMessage.success('批量出库成功') ElMessage.success('出库成功')
// 清空 // 重置
cartItems.value = [] cartItems.value = []
form.consumer_name = '' form.consumer_name = ''
form.remark = '' form.remark = ''
signatureFile.value = null signatureFile.value = null
signaturePreviewUrl.value = '' signaturePreviewUrl.value = ''
// 刷新操作员列表
loadHistoryOperators() loadHistoryOperators()
} catch (error) { } catch (error) {
console.error(error) console.error(error)
ElMessage.error('提交失败')
} finally { } finally {
loading.value = false loading.value = false
} }
}) })
} }
// --- 摄像头控制 --- // --- 签名逻辑 (Canvas) ---
const toggleCamera = async () => { const openSignatureDialog = () => { showSignatureDialog.value = true }
if (showCamera.value) {
await stopCamera()
} else {
if (isHttpAndNotLocal.value) {
ElMessage.error('浏览器安全限制:摄像头仅支持 HTTPS 或 localhost。请检查地址栏或配置 Chrome Flags。')
}
showCamera.value = true
nextTick(() => {
startCamera()
})
}
}
const startCamera = () => {
html5QrCode.value = new Html5Qrcode("reader", {
formatsToSupport: [ Html5QrcodeSupportedFormats.CODE_128 ],
verbose: false
})
html5QrCode.value.start(
{ facingMode: "environment" },
{
fps: 10,
qrbox: { width: 250, height: 150 },
aspectRatio: 1.0
},
(decodedText) => {
barcodeInput.value = decodedText
handleScan()
},
(errorMessage) => { }
).catch(err => {
let msg = '无法启动摄像头'
if (err.toString().includes('Permission')) {
msg = '摄像头权限被拒绝,请检查浏览器设置'
} else if (err.toString().includes('Secure Context')) {
msg = '摄像头需要 HTTPS 环境'
}
ElMessage.error(`${msg}: ${err}`)
showCamera.value = false
})
}
const stopCamera = async () => {
if (html5QrCode.value) {
try {
if (html5QrCode.value.isScanning) {
await html5QrCode.value.stop()
}
html5QrCode.value.clear()
showCamera.value = false
} catch (err) {
showCamera.value = false
}
}
}
// --- 签名核心逻辑 ---
const openSignatureDialog = () => {
showSignatureDialog.value = true
}
const initCanvas = async () => { const initCanvas = async () => {
// 必须等待 DOM 更新完成,确保 dialog 里的 ref 已经挂载
await nextTick() await nextTick()
const canvas = nativeCanvasRef.value const canvas = nativeCanvasRef.value
const container = canvasContainerRef.value const container = canvasContainerRef.value
if (canvas && container) { if (canvas && container) {
// 设置物理像素等于显示像素,避免模糊
canvas.width = container.clientWidth canvas.width = container.clientWidth
canvas.height = container.clientHeight canvas.height = container.clientHeight
ctx.value = canvas.getContext('2d') ctx.value = canvas.getContext('2d')
if (ctx.value) { if (ctx.value) {
ctx.value.lineWidth = 4 ctx.value.lineWidth = 4
ctx.value.lineCap = 'round' ctx.value.lineCap = 'round'
ctx.value.lineJoin = 'round' ctx.value.lineJoin = 'round'
ctx.value.strokeStyle = '#000000' ctx.value.strokeStyle = '#000000'
// 填充白色背景,防止生成透明图片
ctx.value.fillStyle = '#ffffff' ctx.value.fillStyle = '#ffffff'
ctx.value.fillRect(0, 0, canvas.width, canvas.height) ctx.value.fillRect(0, 0, canvas.width, canvas.height)
} }
} else {
console.error('Canvas 初始化失败:无法获取 DOM 元素')
} }
} }
const getPos = (e: MouseEvent | TouchEvent) => { const getPos = (e: MouseEvent | TouchEvent) => {
if (!nativeCanvasRef.value) return { x: 0, y: 0 } if (!nativeCanvasRef.value) return { x: 0, y: 0 }
const rect = nativeCanvasRef.value.getBoundingClientRect() const rect = nativeCanvasRef.value.getBoundingClientRect()
let clientX, clientY const clientX = e.type.startsWith('touch') ? (e as TouchEvent).touches[0].clientX : (e as MouseEvent).clientX
if (e.type.startsWith('touch')) { const clientY = e.type.startsWith('touch') ? (e as TouchEvent).touches[0].clientY : (e as MouseEvent).clientY
clientX = (e as TouchEvent).touches[0].clientX
clientY = (e as TouchEvent).touches[0].clientY
} else {
clientX = (e as MouseEvent).clientX
clientY = (e as MouseEvent).clientY
}
return { x: clientX - rect.left, y: clientY - rect.top } return { x: clientX - rect.left, y: clientY - rect.top }
} }
const startDrawing = (e: MouseEvent | TouchEvent) => { const startDrawing = (e: MouseEvent | TouchEvent) => {
// 阻止默认事件(如页面滚动)
e.preventDefault() e.preventDefault()
isDrawing.value = true isDrawing.value = true
const { x, y } = getPos(e) const { x, y } = getPos(e)
lastX.value = x lastX.value = x; lastY.value = y
lastY.value = y ctx.value?.beginPath()
if(ctx.value) { ctx.value?.moveTo(x, y)
ctx.value.beginPath()
ctx.value.moveTo(x, y)
ctx.value.lineTo(x, y)
ctx.value.stroke()
}
} }
const draw = (e: MouseEvent | TouchEvent) => { const draw = (e: MouseEvent | TouchEvent) => {
e.preventDefault() e.preventDefault()
if (!isDrawing.value || !ctx.value) return if (!isDrawing.value || !ctx.value) return
const { x, y } = getPos(e) const { x, y } = getPos(e)
ctx.value.beginPath()
ctx.value.moveTo(lastX.value, lastY.value)
ctx.value.lineTo(x, y) ctx.value.lineTo(x, y)
ctx.value.stroke() ctx.value.stroke()
lastX.value = x
lastY.value = y
} }
const stopDrawing = () => { const stopDrawing = () => { isDrawing.value = false }
isDrawing.value = false
if (ctx.value) ctx.value.beginPath()
}
const clearCanvas = () => { const clearCanvas = () => {
if (!ctx.value || !nativeCanvasRef.value) return if (!ctx.value || !nativeCanvasRef.value) return
@ -538,189 +478,86 @@ const clearCanvas = () => {
} }
const handleSignConfirm = () => { const handleSignConfirm = () => {
if (!nativeCanvasRef.value) return nativeCanvasRef.value?.toBlob((blob) => {
nativeCanvasRef.value.toBlob((blob) => {
if (blob) { if (blob) {
const file = new File([blob], `signature_${Date.now()}.png`, { type: 'image/png' }) const file = new File([blob], `sign_${Date.now()}.png`, { type: 'image/png' })
signatureFile.value = file signatureFile.value = file
signaturePreviewUrl.value = URL.createObjectURL(file) signaturePreviewUrl.value = URL.createObjectURL(file)
showSignatureDialog.value = false showSignatureDialog.value = false
} else {
ElMessage.error('生成签名失败')
} }
}, 'image/png') }, 'image/png')
} }
const handleSignCancel = () => { const handleSignCancel = () => { showSignatureDialog.value = false }
showSignatureDialog.value = false
}
onUnmounted(() => { onUnmounted(() => {
stopCamera() if (signaturePreviewUrl.value) URL.revokeObjectURL(signaturePreviewUrl.value)
if (signaturePreviewUrl.value) {
URL.revokeObjectURL(signaturePreviewUrl.value)
}
}) })
</script> </script>
<style scoped> <style scoped>
.scan-area { .app-container.mobile-optimized {
text-align: center; padding: 10px; max-width: 600px; margin: 0 auto;
padding: 20px;
} }
.camera-box {
width: 100%;
max-width: 400px;
height: 300px;
margin: 0 auto 20px;
background: #000;
overflow: hidden;
}
.http-warning {
color: #e6a23c;
background: #fdf6ec;
padding: 10px;
margin-bottom: 10px;
border-radius: 4px;
font-size: 12px;
}
.confirm-area {
max-width: 800px;
margin: 0 auto;
}
.mt-20 {
margin-top: 20px;
}
.form-actions {
margin-top: 30px;
display: flex;
justify-content: space-between;
}
.signature-display-area {
border: 1px dashed #dcdfe6;
border-radius: 4px;
padding: 10px;
text-align: center;
background: #fafafa;
min-height: 80px;
display: flex;
align-items: center;
justify-content: center;
}
.signed-image-box img {
max-height: 100px;
max-width: 100%;
display: block;
margin-bottom: 5px;
border: 1px solid #eee;
}
/* 新增:头部右侧信息 */
.header-right {
display: flex;
align-items: center;
}
.summary-text {
margin-right: 15px;
font-size: 14px;
color: #606266;
}
.summary-text .num { color: #409EFF; font-weight: bold; margin: 0 4px; }
.summary-text .price { color: #F56C6C; font-weight: bold; margin: 0 4px; font-size: 16px; }
/* 响应式签名弹窗 */ /* 头部 */
:deep(.fullscreen-signature-dialog .el-dialog__body) { .card-header { display: flex; justify-content: space-between; align-items: center; }
padding: 0; .title-box { font-size: 16px; font-weight: bold; display: flex; align-items: center; gap: 8px; }
height: 100%; .header-price { font-size: 18px; color: #F56C6C; font-weight: bold; }
overflow: hidden;
display: flex; /* 扫码区 */
.scan-section { margin-bottom: 20px; }
.camera-wrapper {
height: 25vh; background: #000; border-radius: 12px; overflow: hidden; position: relative; margin-bottom: 10px;
} }
.signature-wrapper { .scan-overlay {
display: flex; position: absolute; bottom: 10px; right: 10px; z-index: 10;
width: 100%;
height: 100%;
background-color: #fff;
} }
.signature-canvas-container { .camera-placeholder {
flex: 1; height: 120px; background: #f5f7fa; border: 1px dashed #dcdfe6; border-radius: 8px;
position: relative; display: flex; flex-direction: column; justify-content: center; align-items: center;
background-color: #fff; color: #909399; margin-bottom: 10px; cursor: pointer;
height: 100%;
width: 100%;
overflow: hidden;
} }
.native-canvas { .camera-placeholder .text { margin-top: 5px; font-size: 13px; }
display: block;
width: 100%; /* 表单与购物车 */
height: 100%; .cart-section { margin-bottom: 20px; }
cursor: crosshair; .form-section { background: #fff; }
touch-action: none; .signature-box {
border: 1px dashed #dcdfe6; border-radius: 6px; height: 100px;
background: #fcfcfc; display: flex; justify-content: center; align-items: center; cursor: pointer;
}
.unsigned-placeholder { display: flex; flex-direction: column; align-items: center; color: #909399; font-size: 13px; }
.signed-img img { max-height: 90px; }
.re-sign-tip { display: block; text-align: center; font-size: 12px; color: #409EFF; margin-top: 2px; }
.bottom-actions { display: flex; justify-content: space-between; margin-top: 30px; }
.bottom-actions .el-button { width: 48%; }
/* 全屏签名弹窗 */
:deep(.fullscreen-signature-dialog .el-dialog__body) { padding: 0; height: 100%; display: flex; }
.signature-wrapper { display: flex; width: 100%; height: 100%; }
.signature-canvas-container { flex: 1; position: relative; background: #fff; overflow: hidden; }
.native-canvas { display: block; width: 100%; height: 100%; touch-action: none; }
.canvas-tip {
position: absolute; bottom: 20px; left: 50%; transform: translateX(-50%);
color: #ccc; font-size: 20px; pointer-events: none; opacity: 0.5; writing-mode: vertical-lr;
} }
.signature-sidebar { .signature-sidebar {
width: 150px; width: 120px; background: #333; color: #fff;
background: #333; display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 20px 10px;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
padding: 20px 10px;
gap: 30px;
color: #fff;
z-index: 10;
box-shadow: -2px 0 5px rgba(0,0,0,0.1);
}
.sidebar-title {
writing-mode: vertical-rl;
letter-spacing: 4px;
font-size: 18px;
font-weight: bold;
opacity: 0.8;
}
.sidebar-actions {
display: flex;
flex-direction: column;
gap: 20px;
width: 100%;
}
.sidebar-actions .el-button {
width: 100%;
margin-left: 0;
height: 50px;
}
.confirm-btn {
margin-top: 20px;
font-weight: bold;
} }
.sidebar-title { writing-mode: vertical-rl; font-size: 18px; letter-spacing: 5px; margin-bottom: 30px; font-weight: bold; }
.sidebar-actions { display: flex; flex-direction: column; gap: 20px; width: 100%; }
.sidebar-actions .el-button { width: 100%; margin: 0; height: 50px; }
@media screen and (max-width: 768px) { @media screen and (max-width: 768px) {
.signature-wrapper { .signature-wrapper { flex-direction: column; }
flex-direction: column; .signature-canvas-container { flex: 1; }
} .canvas-tip { writing-mode: horizontal-tb; bottom: 50%; }
.signature-canvas-container { .signature-sidebar { width: 100%; height: auto; flex-direction: row; padding: 10px; justify-content: space-between; }
flex: 1; .sidebar-title { display: none; }
height: auto; .sidebar-actions { flex-direction: row; width: 100%; gap: 10px; }
} .sidebar-actions .el-button { flex: 1; height: 40px; }
.signature-sidebar {
width: 100%;
height: auto;
flex-direction: row;
padding: 15px;
gap: 10px;
order: 2;
}
.sidebar-title {
display: none;
}
.sidebar-actions {
flex-direction: row;
gap: 10px;
width: 100%;
}
.sidebar-actions .el-button {
flex: 1;
height: 44px;
font-size: 14px;
}
.confirm-btn {
margin-top: 0;
}
} }
</style> </style>

View File

@ -1,15 +1,49 @@
<template> <template>
<div class="app-container mobile-optimized"> <div class="app-container mobile-optimized">
<el-card class="main-card" shadow="never">
<el-card v-if="!isSessionActive" class="main-card idle-card" shadow="never">
<div class="idle-content">
<el-icon :size="60" color="#409EFF"><VideoPlay /></el-icon>
<h2>库存盘点系统</h2>
<p class="subtitle">请确保已连接扫描枪或摄像头</p>
<div class="idle-actions">
<el-button type="primary" size="large" class="w-100" @click="startNewSession" :loading="btnLoading">
开始新盘点
</el-button>
<el-button
v-if="serverDraftCount > 0"
type="warning"
plain
size="large"
class="w-100"
@click="resumeSession"
:loading="btnLoading"
>
继续上次盘点
<div class="btn-subtext">(云端已存: {{ serverDraftCount }} )</div>
</el-button>
</div>
<div class="safe-tip">
<el-icon><Cloudy /></el-icon>
<span>数据实时同步至服务器防止意外丢失</span>
</div>
</div>
</el-card>
<el-card v-else class="main-card active-card" shadow="never" v-loading="loading">
<template #header> <template #header>
<div class="header-row"> <div class="header-row">
<div class="title"> <div class="title-box">
<span>📷 库存盘点</span> <span class="title-text">📷 盘点作业中</span>
<el-tag v-if="!showList" type="success" size="small" effect="dark">扫描中</el-tag> <el-tag v-if="syncStatus === 'success'" type="success" size="small" effect="dark" round>已同步</el-tag>
<el-tag v-else type="info" size="small">暂停</el-tag> <el-tag v-else-if="syncStatus === 'syncing'" type="warning" size="small" effect="dark" round>同步中...</el-tag>
<el-tag v-else type="danger" size="small" effect="dark" round>同步失败</el-tag>
</div> </div>
<el-button type="primary" plain @click="openInventoryList" icon="List"> <el-button type="info" text bg size="small" @click="pauseSession" :icon="VideoPause">
查看清单/手动查找 暂停/退出
</el-button> </el-button>
</div> </div>
</template> </template>
@ -17,43 +51,47 @@
<div class="scanner-container"> <div class="scanner-container">
<div v-if="!showList" class="camera-active-box"> <div v-if="!showList" class="camera-active-box">
<QrScanner @decode="onScanSuccess" /> <QrScanner @decode="onScanSuccess" />
<div class="scan-overlay-tip">将条码对准取景框</div> <div class="scan-overlay-tip">将条码对准取景框</div>
</div> </div>
<div v-else class="camera-paused-box" @click="showList = false"> <div v-else class="camera-paused-box" @click="showList = false">
<el-icon :size="60" color="#909399"><VideoPause /></el-icon> <el-icon :size="50" color="#909399"><List /></el-icon>
<p>正在查看清单<br>摄像头已暂停</p> <p>正在查看清单列表<br>摄像头已暂停</p>
<el-button type="primary" link>点击返回扫描</el-button> <el-button type="primary" link>点击返回继续扫描</el-button>
</div> </div>
</div> </div>
<div class="stats-dashboard"> <div class="stats-dashboard" @click="openInventoryList">
<div class="stat-card"> <div class="stat-card">
<div class="stat-val">{{ stats.total }}</div> <div class="stat-val">{{ stats.total }}</div>
<div class="stat-label">应盘总数</div> <div class="stat-label">总数</div>
</div> </div>
<div class="stat-card success"> <div class="stat-card success">
<div class="stat-val">{{ stats.scanned }}</div> <div class="stat-val">{{ stats.scanned }}</div>
<div class="stat-label">(相符)</div> <div class="stat-label"></div>
</div> </div>
<div class="stat-card error"> <div class="stat-card error">
<div class="stat-val">{{ stats.missing }}</div> <div class="stat-val">{{ stats.missing }}</div>
<div class="stat-label">差异(未扫)</div> <div class="stat-label">差异</div>
</div>
<div class="stat-arrow">
<el-icon><ArrowRight /></el-icon>
</div> </div>
</div> </div>
<div class="main-actions"> <div class="main-actions">
<el-button <el-row :gutter="10">
type="danger" <el-col :span="12">
size="large" <el-button type="primary" plain size="large" class="w-100 action-btn" @click="openInventoryList" :icon="Search">
class="finish-btn" 查看清单
@click="handleFinish" </el-button>
:loading="printing" </el-col>
:disabled="stats.total === 0" <el-col :span="12">
icon="Printer" <el-button type="danger" size="large" class="w-100 action-btn" @click="openFinishDialog" :icon="Checked">
> 结束盘点
结束盘点并打印差异报告 </el-button>
</el-button> </el-col>
<p class="printer-tip">目标打印机: 192.168.9.205</p> </el-row>
<p class="printer-tip">打印机 IP: 192.168.9.205</p>
</div> </div>
</el-card> </el-card>
@ -61,8 +99,7 @@
v-model="showList" v-model="showList"
title="📦 在库物品清单" title="📦 在库物品清单"
direction="btt" direction="btt"
size="90%" size="85%"
:with-header="true"
destroy-on-close destroy-on-close
class="inventory-drawer" class="inventory-drawer"
> >
@ -70,48 +107,102 @@
<div class="search-bar"> <div class="search-bar">
<el-input <el-input
v-model="searchKeyword" v-model="searchKeyword"
placeholder="搜索名称 / 规格 / 条码" placeholder="搜索名称 / 规格 / 条码..."
prefix-icon="Search" prefix-icon="Search"
clearable clearable
size="large"
/> />
<el-select <el-select v-model="filterType" placeholder="状态" style="width: 110px; margin-left: 8px;">
v-model="filterType"
placeholder="类型"
style="width: 100px; margin-left: 8px;"
size="large"
>
<el-option label="全部" value="all" /> <el-option label="全部" value="all" />
<el-option label="采购" value="material" /> <el-option label="已盘" value="scanned" />
<el-option label="半成品" value="semi" /> <el-option label="差异" value="missing" />
<el-option label="成品" value="product" />
</el-select> </el-select>
</div> </div>
<el-table <el-table
:data="filteredList" :data="filteredList"
height="100%" height="100%"
style="width: 100%; flex: 1;"
stripe stripe
border border
row-key="uniqueKey" row-key="uniqueKey"
style="width: 100%"
> >
<el-table-column prop="name" label="名称" min-width="120" show-overflow-tooltip /> <el-table-column prop="name" label="物品名称" min-width="130" show-overflow-tooltip>
<el-table-column prop="standard" label="规格" min-width="100" show-overflow-tooltip />
<el-table-column prop="uuid" label="条码后6位" width="100">
<template #default="scope"> <template #default="scope">
{{ scope.row.uuid ? '...' + scope.row.uuid.slice(-6) : '-' }} <div>{{ scope.row.name }}</div>
<div style="font-size: 12px; color: #999;">{{ scope.row.standard }}</div>
</template> </template>
</el-table-column> </el-table-column>
<el-table-column label="状态" width="80" align="center" fixed="right">
<el-table-column prop="uuid" label="条码尾号" width="90" align="center">
<template #default="scope"> <template #default="scope">
<el-tag v-if="scope.row.scanned" type="success" effect="dark">已盘</el-tag> {{ scope.row.uuid ? scope.row.uuid.slice(-6) : '-' }}
<el-tag v-else type="danger" effect="plain">未扫</el-tag> </template>
</el-table-column>
<el-table-column label="库存" width="70" align="center">
<template #default="scope">
<span style="font-weight: bold;">{{ parseFloat(scope.row.qty_stock) }}</span>
</template>
</el-table-column>
<el-table-column label="状态" width="70" align="center" fixed="right">
<template #default="scope">
<el-tag v-if="scope.row.scanned" type="success" size="small" effect="dark">OK</el-tag>
<el-tag v-else type="danger" size="small" effect="plain">未扫</el-tag>
</template> </template>
</el-table-column> </el-table-column>
</el-table> </el-table>
</div> </div>
</el-drawer> </el-drawer>
<el-dialog
v-model="showFinishDialog"
title="📊 盘点结算"
width="90%"
align-center
:close-on-click-modal="false"
class="preview-dialog"
>
<div class="report-summary">
<div class="summary-row">
<span>盘点时间:</span>
<span>{{ new Date().toLocaleTimeString() }}</span>
</div>
<div class="summary-stats">
<div class="s-item">
<div class="num">{{ stats.total }}</div>
<div class="txt">总数</div>
</div>
<div class="s-item success">
<div class="num">{{ stats.scanned }}</div>
<div class="txt">实盘</div>
</div>
<div class="s-item error">
<div class="num">{{ stats.missing }}</div>
<div class="txt">丢失</div>
</div>
</div>
</div>
<div class="missing-list-header">差异物品 (丢失清单)</div>
<el-table :data="missingList" height="250" border size="small" style="margin-bottom: 10px;">
<el-table-column prop="name" label="名称" show-overflow-tooltip />
<el-table-column prop="qty_stock" label="账存" width="60" align="center" />
</el-table>
<template #footer>
<div class="dialog-footer">
<el-button @click="showFinishDialog = false">返回</el-button>
<div class="footer-right">
<el-button type="success" @click="generatePDF" :icon="Download" circle title="下载PDF" />
<el-button type="primary" @click="confirmPrint" :loading="printing" :icon="Printer">
打印报告
</el-button>
</div>
</div>
</template>
</el-dialog>
</div> </div>
</template> </template>
@ -119,10 +210,17 @@
import { ref, computed, onMounted } from 'vue' import { ref, computed, onMounted } from 'vue'
import { getAllStock, printStocktakeReport } from '@/api/inbound/stock' import { getAllStock, printStocktakeReport } from '@/api/inbound/stock'
import QrScanner from '@/components/QrScanner/index.vue' import QrScanner from '@/components/QrScanner/index.vue'
import { ElMessage, ElNotification, ElMessageBox } from 'element-plus' import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, List, Printer, VideoPause } from '@element-plus/icons-vue' import { Search, VideoPlay, VideoPause, List, Printer, Checked, Download, ArrowRight, Cloudy } from '@element-plus/icons-vue'
import jsPDF from 'jspdf'
import 'jspdf-autotable'
import request from '@/utils/request'
import { useUserStore } from '@/stores/user' // 引入UserStore获取真实用户
// --- 类型定义 --- const userStore = useUserStore()
const currentUser = userStore.username || 'admin' // 优先使用登录名
// --- 数据接口 ---
interface StockItem { interface StockItem {
id: number id: number
name: string name: string
@ -130,71 +228,192 @@ interface StockItem {
batch_no: string batch_no: string
uuid: string uuid: string
bar_code: string bar_code: string
qty_stock: number
scanned: boolean scanned: boolean
category_type: 'material' | 'semi' | 'product'
category_label: string
uniqueKey: string uniqueKey: string
[key: string]: any [key: string]: any
} }
// --- 状态管理 --- // --- 状态变量 ---
const loading = ref(false)
const btnLoading = ref(false)
const printing = ref(false) const printing = ref(false)
const showList = ref(false) // 控制抽屉显示 const isSessionActive = ref(false) // 会话是否进行中
const serverDraftCount = ref(0) // 服务器上的草稿数量
const showList = ref(false) // 是否显示抽屉清单
const showFinishDialog = ref(false) // 是否显示结算弹窗
const syncStatus = ref<'success' | 'syncing' | 'failed'>('success')
const allData = ref<StockItem[]>([])
const scannedSet = ref<Set<string>>(new Set())
const filterType = ref('all') const filterType = ref('all')
const searchKeyword = ref('') const searchKeyword = ref('')
const allData = ref<StockItem[]>([])
// --- API 封装 ---
const api = {
getDrafts: () => request({ url: '/v1/inbound/stock/draft/list', method: 'get', params: { user_id: currentUser } }),
addDraft: (data: any) => request({ url: '/v1/inbound/stock/draft/add', method: 'post', data: { ...data, user_id: currentUser } }),
clearDraft: () => request({ url: '/v1/inbound/stock/draft/clear', method: 'post', data: { user_id: currentUser } })
}
// --- 初始化 --- // --- 初始化 ---
const init = async () => { onMounted(async () => {
await checkServerDraft()
})
const checkServerDraft = async () => {
try {
const res: any = await api.getDrafts()
if (res && res.length > 0) {
serverDraftCount.value = res.length
} else {
serverDraftCount.value = 0
}
} catch (e) {
console.error('检查草稿失败', e)
}
}
// --- 核心业务逻辑 ---
// 1. 开始新会话 (清空服务器草稿)
const startNewSession = async () => {
try {
if (serverDraftCount.value > 0) {
await ElMessageBox.confirm('服务器存在未完成的盘点记录,开始新盘点将清除它们,确定吗?', '新盘点', { type: 'warning' })
}
btnLoading.value = true
await api.clearDraft() // 清空后端
scannedSet.value.clear()
await loadData() // 拉取库存
isSessionActive.value = true
} catch (e) {
// cancel
} finally {
btnLoading.value = false
}
}
// 2. 恢复旧会话 (从服务器拉取草稿)
const resumeSession = async () => {
btnLoading.value = true
try {
// 先拉草稿
const drafts: any = await api.getDrafts()
const draftUUIDs = new Set(drafts.map((d: any) => d.uuid))
scannedSet.value = draftUUIDs
await loadData() // 再拉库存,并匹配状态
isSessionActive.value = true
} catch (e) {
ElMessage.error('恢复进度失败')
} finally {
btnLoading.value = false
}
}
// 3. 暂停 (无需做任何事,因为数据是实时同步的)
const pauseSession = () => {
isSessionActive.value = false
checkServerDraft() // 更新一下待机界面的数量显示
ElMessage.success('已退出,进度已安全保存在云端')
}
// 4. 加载库存数据
const loadData = async () => {
loading.value = true
try { try {
const res = await getAllStock() const res = await getAllStock()
const list: StockItem[] = [] const list: StockItem[] = []
const processItem = (item: any, type: 'material' | 'semi' | 'product', label: string) => { const processItem = (item: any, type: string) => {
// 逻辑:只要 qty_stock > 0 就算在库
const stock = parseFloat(item.stock_quantity || item.qty_stock || 0)
if (stock <= 0) return
const name = item.material_name || item.product_name || item.name || '未知物品' const name = item.material_name || item.product_name || item.name || '未知物品'
return { const uuid = item.uuid || item.sku || ''
list.push({
...item, ...item,
name: name, name: name,
standard: item.standard || '', standard: item.standard || '',
batch_no: item.batch_no || item.batch_number || '', batch_no: item.batch_no || item.batch_number || '',
uuid: item.uuid || item.sku || '', uuid: uuid,
bar_code: item.bar_code || item.barcode || '', bar_code: item.bar_code || item.barcode || '',
scanned: false, qty_stock: stock,
category_type: type, scanned: scannedSet.value.has(uuid), // 匹配草稿状态
category_label: label,
uniqueKey: `${type}_${item.id}` uniqueKey: `${type}_${item.id}`
} })
} }
if (res.materials) res.materials.forEach((i: any) => list.push(processItem(i, 'material', '采购件'))) if (res.materials) res.materials.forEach((i: any) => processItem(i, 'material'))
if (res.semis) res.semis.forEach((i: any) => list.push(processItem(i, 'semi', '半成品'))) if (res.semis) res.semis.forEach((i: any) => processItem(i, 'semi'))
if (res.products) res.products.forEach((i: any) => list.push(processItem(i, 'product', '成品'))) if (res.products) res.products.forEach((i: any) => processItem(i, 'product'))
allData.value = list allData.value = list
ElMessage.success(`加载成功,共 ${list.length} 件物品`)
} catch (e) { } catch (e) {
ElMessage.error('库存加载失败,请重试') ElMessage.error('库存数据加载失败')
} finally {
loading.value = false
} }
} }
// --- 打开清单 (同时会自动触发 v-if 销毁摄像头) --- // 5. 扫码成功处理 (实时同步到服务器)
const openInventoryList = () => { const onScanSuccess = async (code: string) => {
showList.value = true if (!code) return
const trimCode = code.trim()
const item = allData.value.find(i => i.uuid === trimCode || i.bar_code === trimCode)
if (item) {
if (item.scanned) {
ElMessage.warning('重复扫描')
return
}
// 前端先响应,不阻塞 UI
item.scanned = true
scannedSet.value.add(item.uuid)
if (navigator.vibrate) navigator.vibrate(100);
ElMessage.success(`已确认:${item.name}`)
// 后台静默同步
syncStatus.value = 'syncing'
try {
await api.addDraft({
id: item.id,
uuid: item.uuid,
name: item.name,
standard: item.standard,
batch_no: item.batch_no,
qty_stock: item.qty_stock
})
syncStatus.value = 'success'
} catch (e) {
console.error('同步失败', e)
syncStatus.value = 'failed'
}
} else {
ElMessage.error(`未知条码: ${trimCode}`)
if (navigator.vibrate) navigator.vibrate([200, 50, 200]);
}
} }
// --- 过滤逻辑 --- // --- 计算属性 ---
const filteredList = computed(() => { const filteredList = computed(() => {
let result = allData.value let result = allData.value
if (filterType.value !== 'all') { if (filterType.value === 'scanned') result = result.filter(i => i.scanned)
result = result.filter(item => item.category_type === filterType.value) if (filterType.value === 'missing') result = result.filter(i => !i.scanned)
}
if (searchKeyword.value) { if (searchKeyword.value) {
const kw = searchKeyword.value.toLowerCase().trim() const kw = searchKeyword.value.toLowerCase()
result = result.filter(item => result = result.filter(i =>
(item.name && item.name.toLowerCase().includes(kw)) || i.name.toLowerCase().includes(kw) ||
(item.standard && item.standard.toLowerCase().includes(kw)) || i.uuid.includes(kw) ||
(item.uuid && item.uuid.toLowerCase().includes(kw)) || (i.standard && i.standard.toLowerCase().includes(kw)) // 增加对规格的搜索
(item.bar_code && item.bar_code.toLowerCase().includes(kw))
) )
} }
return result return result
@ -206,91 +425,99 @@ const stats = computed(() => {
return { total, scanned, missing: total - scanned } return { total, scanned, missing: total - scanned }
}) })
// --- 扫码逻辑 --- const missingList = computed(() => {
const onScanSuccess = (code: string) => { return allData.value.filter(i => !i.scanned)
if (!code) return })
const trimCode = code.trim()
const item = allData.value.find(i => i.uuid === trimCode || i.bar_code === trimCode) // --- 界面交互 ---
const openInventoryList = () => { showList.value = true }
if (item) { const openFinishDialog = () => {
if (item.scanned) { if (stats.value.total === 0) return
ElMessage.warning(`${item.name} 已扫过`) showFinishDialog.value = true
return
}
item.scanned = true
// 震动反馈 (如果设备支持)
if (navigator.vibrate) navigator.vibrate(200);
ElNotification({
title: '✅ 匹配成功',
message: `${item.name}\n${item.standard}`,
type: 'success',
duration: 2000,
position: 'top-left' // 移动端通常顶部提示更明显
})
} else {
ElMessage.error(`未找到: ${trimCode}`)
if (navigator.vibrate) navigator.vibrate([100, 50, 100]);
}
} }
// --- 结束打印 --- // 生成 PDF (包含中文支持提示)
const handleFinish = async () => { const generatePDF = () => {
if (stats.value.total === 0) return const doc = new jsPDF()
// 提示:默认 jspdf 不支持中文,需要 addFont。
// 这里使用英文表头以确保基础可用性,实际生产需自行引入中文字体文件
doc.setFontSize(18)
doc.text("Inventory Stocktake Report", 14, 22)
doc.setFontSize(11)
doc.text(`Time: ${new Date().toLocaleString()}`, 14, 30)
doc.text(`Total: ${stats.value.total} | Scanned: ${stats.value.scanned} | Missing: ${stats.value.missing}`, 14, 38)
const tableData = missingList.value.map(item => [
item.uuid,
item.name,
item.standard,
item.qty_stock.toString()
])
;(doc as any).autoTable({
head: [['UUID', 'Name', 'Spec', 'Stock']],
body: tableData,
startY: 45,
theme: 'grid'
})
doc.save(`inventory_report_${Date.now()}.pdf`)
}
// 打印并清除服务器草稿
const confirmPrint = async () => {
try { try {
await ElMessageBox.confirm(
`应盘: ${stats.value.total} | 差异: ${stats.value.missing}\n确认结束并打印`,
'结束盘点',
{ confirmButtonText: '打印报告', cancelButtonText: '取消', type: 'warning', center: true }
)
const missingItems = allData.value.filter(i => !i.scanned)
const payload = { const payload = {
total: stats.value.total, total: stats.value.total,
scanned: stats.value.scanned, scanned: stats.value.scanned,
missing: stats.value.missing, missing: stats.value.missing,
missing_items: missingItems missing_items: missingList.value
} }
printing.value = true printing.value = true
await printStocktakeReport(payload) await printStocktakeReport(payload)
ElMessage.success('打印指令已发送') ElMessage.success('已发送至打印机')
// 任务完成,清空服务器草稿
await api.clearDraft()
scannedSet.value.clear()
isSessionActive.value = false
showFinishDialog.value = false
checkServerDraft() // 刷新计数
} catch (e) { } catch (e) {
if (e !== 'cancel') ElMessage.error('打印失败') ElMessage.error('打印失败')
} finally { } finally {
printing.value = false printing.value = false
} }
} }
onMounted(() => {
init()
})
</script> </script>
<style scoped> <style scoped>
/* 移动端容器适配 */ /* 移动端容器适配 */
.app-container.mobile-optimized { .app-container.mobile-optimized {
padding: 10px; padding: 10px;
max-width: 600px; /* 在平板/PC上限制宽度,保持手机观感 */ max-width: 600px; /* 限制最大宽度,保持手机观感 */
margin: 0 auto; margin: 0 auto;
} }
/* 头部样式 */ /* 待机卡片 */
.header-row { .idle-card {
min-height: 400px;
display: flex; display: flex;
justify-content: space-between; justify-content: center;
align-items: center; align-items: center;
text-align: center;
} }
.header-row .title { .idle-content { width: 100%; padding: 20px; }
display: flex; .subtitle { color: #909399; margin-bottom: 30px; }
flex-direction: column; .idle-actions { display: flex; flex-direction: column; gap: 15px; }
gap: 4px; .btn-subtext { font-size: 12px; opacity: 0.8; margin-top: 2px; }
font-weight: bold; .safe-tip { margin-top: 30px; font-size: 12px; color: #67c23a; display: flex; align-items: center; justify-content: center; gap: 5px; }
font-size: 16px;
} /* 头部 */
.header-row { display: flex; justify-content: space-between; align-items: center; }
.title-box { display: flex; align-items: center; gap: 8px; font-weight: bold; font-size: 16px; }
/* 扫描区域 */ /* 扫描区域 */
.scanner-container { .scanner-container {
@ -300,92 +527,55 @@ onMounted(() => {
overflow: hidden; overflow: hidden;
margin-bottom: 15px; margin-bottom: 15px;
position: relative; position: relative;
box-shadow: 0 4px 10px rgba(0,0,0,0.2); box-shadow: 0 4px 12px rgba(0,0,0,0.15);
} }
.camera-active-box { width: 100%; height: 100%; }
.camera-active-box {
width: 100%;
height: 100%;
}
.scan-overlay-tip { .scan-overlay-tip {
position: absolute; position: absolute; bottom: 15px; left: 0; width: 100%;
bottom: 10px; text-align: center; color: rgba(255,255,255,0.9); font-size: 13px; pointer-events: none;
left: 0; text-shadow: 0 1px 3px rgba(0,0,0,0.8);
width: 100%;
text-align: center;
color: rgba(255, 255, 255, 0.8);
font-size: 12px;
background: linear-gradient(to top, rgba(0,0,0,0.8), transparent);
padding: 10px 0;
pointer-events: none;
} }
.camera-paused-box { .camera-paused-box {
width: 100%; width: 100%; height: 100%; display: flex; flex-direction: column;
height: 100%; justify-content: center; align-items: center; background: #f2f3f5; color: #909399; cursor: pointer;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
background: #f0f2f5;
color: #909399;
cursor: pointer;
text-align: center;
} }
/* 统计仪表盘 */ /* 统计仪表盘 */
.stats-dashboard { .stats-dashboard {
display: flex; display: flex; align-items: center;
gap: 10px; background: #f8f9fa; border: 1px solid #ebeef5;
margin-bottom: 20px; border-radius: 8px; padding: 10px; margin-bottom: 20px;
} cursor: pointer; transition: all 0.2s; position: relative;
.stat-card {
flex: 1;
background: #f8f9fa;
border-radius: 8px;
padding: 15px 5px;
text-align: center;
border: 1px solid #ebeef5;
}
.stat-card .stat-val {
font-size: 24px;
font-weight: 800;
line-height: 1.2;
}
.stat-card .stat-label {
font-size: 12px;
color: #909399;
margin-top: 4px;
} }
.stats-dashboard:active { background: #f0f2f5; }
.stat-card { flex: 1; text-align: center; }
.stat-val { font-size: 20px; font-weight: 800; line-height: 1.2; }
.stat-label { font-size: 11px; color: #909399; }
.stat-card.success .stat-val { color: #67c23a; } .stat-card.success .stat-val { color: #67c23a; }
.stat-card.error .stat-val { color: #f56c6c; } .stat-card.error .stat-val { color: #f56c6c; }
.stat-arrow { width: 20px; color: #c0c4cc; }
/* 底部按钮 */ /* 底部操作 */
.main-actions { .w-100 { width: 100%; }
margin-top: 10px; .action-btn { font-weight: bold; height: 48px; }
} .printer-tip { text-align: center; color: #c0c4cc; font-size: 12px; margin-top: 15px; }
.finish-btn {
height: 50px;
font-size: 16px;
border-radius: 25px; /* 圆角按钮更好点 */
}
.printer-tip {
text-align: center;
font-size: 12px;
color: #909399;
margin-top: 12px;
}
/* 抽屉内容布局 */ /* 抽屉样式 */
.drawer-content { .drawer-content { height: 100%; display: flex; flex-direction: column; padding: 10px; }
height: 100%; .search-bar { display: flex; margin-bottom: 10px; }
display: flex;
flex-direction: column; /* 结算弹窗 */
padding: 10px; .report-summary {
} background: #f5f7fa; padding: 15px; border-radius: 6px; margin-bottom: 15px;
.search-bar {
display: flex;
margin-bottom: 10px;
} }
.summary-row { display: flex; justify-content: space-between; margin-bottom: 15px; color: #606266; font-size: 13px; }
.summary-stats { display: flex; justify-content: space-between; text-align: center; }
.s-item .num { font-size: 18px; font-weight: bold; }
.s-item .txt { font-size: 12px; color: #909399; }
.s-item.success .num { color: #67c23a; }
.s-item.error .num { color: #f56c6c; }
.missing-list-header { font-weight: bold; margin-bottom: 8px; font-size: 13px; border-left: 3px solid #f56c6c; padding-left: 8px; }
.dialog-footer { display: flex; justify-content: space-between; align-items: center; margin-top: 10px; }
.footer-right { display: flex; gap: 10px; }
</style> </style>