feat(scrap): 报废作业页重构为「按单扫码执行」,对齐出库版式

create.vue 由「直接报废」页(492 行)重写为按单执行页:
  · 顶部选择已批准申请单(scope=executable, status=1);
  · 载入 items_json 为待执行清单,逐项显示批准数量与已扫数量;
  · 扫码头按 (source_table, stock_id) 匹配批准明细,
    不在单内或超批准量时红色 toast + 震动阻断,禁止入车;
  · 支持 ?requestId= 深链直达;提交实扫 payload 到 execute 接口。

审批页的「执行报废」由弹窗盲执行改为跳转本页(router.push + query.requestId),
移除 executeVisible/confirmExecute 等已失效代码;路由标题改为「按单报废执行」。
executeScrapByRequest 增加 items 参数。
This commit is contained in:
yueli
2026-09-10 10:14:43 +08:00
parent 7719943779
commit af2d1c10c6
4 changed files with 529 additions and 336 deletions

View File

@ -94,10 +94,18 @@ export function approveScrapRequest(id: number, data: { action: 'approve' | 'rej
}) })
} }
// 9. 按单报废执行(扣减库存) // 9. 按单报废执行(提交实扫明细,扣减库存)
export function executeScrapByRequest(id: number) { // items 必须是该申请单批准明细的子集,且累计数量不得超过批准数量
export function executeScrapByRequest(id: number, items: Array<{
source_table: string
stock_id: number
quantity: number
sku?: string
name?: string
}>) {
return request({ return request({
url: `/v1/scrap/request/${id}/execute`, url: `/v1/scrap/request/${id}/execute`,
method: 'post' method: 'post',
data: { items }
}) })
} }

View File

@ -261,7 +261,7 @@ const routes: Array<RouteRecordRaw> = [
path: 'create', path: 'create',
name: 'ScrapCreate', name: 'ScrapCreate',
component: () => import('@/views/operation/scrap/create.vue'), component: () => import('@/views/operation/scrap/create.vue'),
meta: { title: '新建报废' } meta: { title: '按单报废执行' }
}, },
{ {
path: 'apply', path: 'apply',

View File

@ -159,45 +159,18 @@
</template> </template>
</el-dialog> </el-dialog>
<!-- 按单报废执行 Dialog(严格按选单内容扣减) -->
<el-dialog v-model="executeVisible" title="按单报废(确认扣减库存)" width="760px" destroy-on-close>
<el-alert
type="warning" :closable="false" show-icon
title="确认后将严格按下列“选单明细”扣减对应库存行的可用数量并写入报废流水,不可撤销。"
style="margin-bottom:12px;"
/>
<el-table :data="execItems" border size="small" max-height="340">
<el-table-column type="index" label="序号" width="60" align="center" />
<el-table-column label="来源" width="90" align="center">
<template #default="{ row: item }">
<el-tag size="small">{{ sourceLabel(item.source_table) }}</el-tag>
</template>
</el-table-column>
<el-table-column prop="name" label="名称" min-width="140" show-overflow-tooltip />
<el-table-column prop="spec_model" label="规格型号" min-width="120" show-overflow-tooltip />
<el-table-column prop="location" label="库位" width="110" />
<el-table-column prop="batch_number" label="批次/序列号" width="130" />
<el-table-column label="报废数量" width="100" align="center">
<template #default="{ row: item }">
<span style="color:#F56C6C;font-weight:bold;">{{ item.scrap_qty }}</span>
</template>
</el-table-column>
</el-table>
<template #footer>
<el-button @click="executeVisible = false">取消</el-button>
<el-button type="warning" :loading="executing" @click="confirmExecute">确认执行报废</el-button>
</template>
</el-dialog>
</div> </div>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { ref, computed, onMounted } from 'vue' import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { Refresh, Warning } from '@element-plus/icons-vue' import { Refresh, Warning } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus' import { ElMessage, ElMessageBox } from 'element-plus'
import { getScrapApprovals, approveScrapRequest, executeScrapByRequest } from '@/api/scrap' import { getScrapApprovals, approveScrapRequest } from '@/api/scrap'
import { useUserStore } from '@/stores/user' import { useUserStore } from '@/stores/user'
const router = useRouter()
const userStore = useUserStore() const userStore = useUserStore()
// --- 状态 --- // --- 状态 ---
@ -216,11 +189,6 @@ const currentRejectRow = ref<any>(null)
const rejectReason = ref('') const rejectReason = ref('')
const rejectLoading = ref(false) const rejectLoading = ref(false)
// 执行 Dialog
const executeVisible = ref(false)
const executeRow = ref<any>(null)
const execItems = ref<any[]>([])
const executing = ref(false)
const userNameCache = ref<Record<number, string>>({}) const userNameCache = ref<Record<number, string>>({})
@ -313,24 +281,9 @@ const confirmReject = async () => {
} finally { rejectLoading.value = false } } finally { rejectLoading.value = false }
} }
// --- 按单报废执行(严格按选单明细) --- // --- 按单报废执行:跳转到「按单报废执行」扫码页,由实扫明细驱动扣减 ---
const openExecute = (row: any) => { const openExecute = (row: any) => {
executeRow.value = row router.push({ path: '/scrap/create', query: { requestId: row.id } })
execItems.value = row.items || []
executeVisible.value = true
}
const confirmExecute = async () => {
if (!executeRow.value) return
executing.value = true
try {
await executeScrapByRequest(executeRow.value.id)
ElMessage.success('已执行报废并扣减库存')
executeVisible.value = false
await fetchData()
} catch (err: any) {
// 拦截器已弹后端业务错误;无响应才算网络异常
if (!err?.response) ElMessage.error('网络异常,请重试')
} finally { executing.value = false }
} }
onMounted(() => { fetchData() }) onMounted(() => { fetchData() })

View File

@ -4,62 +4,163 @@
<template #header> <template #header>
<div class="card-header"> <div class="card-header">
<div class="title-box"> <div class="title-box">
<span>报废作业</span> <span>按单报废执行</span>
<el-tag v-if="cartItems.length > 0" type="danger" size="small" effect="dark"> <el-tag v-if="cartItems.length > 0" type="danger" size="small" effect="dark">
已选 {{ cartItems.length }} 项 已扫 {{ cartItems.length }} 项
</el-tag> </el-tag>
</div> </div>
</div> </div>
</template> </template>
<div class="scan-section"> <div class="mode-switch-bar">
<div v-if="hasPermission" class="camera-placeholder" @click="showCamera = true"> <el-tag type="danger" size="large" style="font-size: 14px;">按单执行</el-tag>
<el-icon :size="40" color="#409EFF"><CameraFilled /></el-icon> <span class="mode-hint">请先选择已审批通过的报废申请单,再扫码报废</span>
<span class="text">点击开启全屏扫码</span> </div>
<!-- Step 1:选择已批准的报废申请单 -->
<div class="approval-request-select">
<el-select
v-model="selectedRequestId"
placeholder="请选择已审批通过的报废申请单"
filterable
clearable
style="width: 100%"
:loading="requestsLoading"
@change="handleRequestChange"
>
<el-option
v-for="req in approvalRequests"
:key="req.id"
:value="req.id"
:label="req.request_no"
>
<span>{{ req.request_no }}</span>
<el-divider direction="vertical" />
<span>{{ req.applicant_name || '未知申请人' }}</span>
<el-divider direction="vertical" />
<span style="color: #909399; font-size: 13px">{{ req.remark || '无备注' }}</span>
</el-option>
</el-select>
<p class="select-tip">仅显示已通过(status=1)的报废申请单</p>
</div>
<!-- Step 2:待执行清单 -->
<div v-if="selectedRequest" class="planned-items-section">
<div class="planned-header">
<span class="planned-title">待执行报废清单</span>
<el-tag type="danger" size="small">{{ plannedItems.length }} 种</el-tag>
</div> </div>
<div v-else class="camera-placeholder" style="background-color: #f5f5f5; cursor: not-allowed;"> <el-table :data="plannedItems" border size="small" style="width: 100%;">
<el-icon :size="40" color="#909399"><CameraFilled /></el-icon> <el-table-column type="index" label="序号" width="60" align="center" />
<span class="text">无扫码权限</span> <el-table-column label="来源" width="80" align="center">
<template #default="{ row }">
<el-tag size="small" type="info">{{ sourceLabel(row.source_table) }}</el-tag>
</template>
</el-table-column>
<el-table-column prop="name" label="名称" min-width="120" show-overflow-tooltip />
<el-table-column prop="spec_model" label="规格" min-width="100" show-overflow-tooltip />
<el-table-column prop="sku" label="SKU" width="110" show-overflow-tooltip />
<el-table-column prop="location" label="库位" width="100" show-overflow-tooltip />
<el-table-column label="批准数量" width="90" align="center">
<template #default="{ row }">
<span style="color: #E6A23C; font-weight: bold;">{{ row.scrap_qty ?? '-' }}</span>
</template>
</el-table-column>
<el-table-column label="已扫" width="80" align="center">
<template #default="{ row }">
<span :style="{ color: scannedQtyOf(row) >= Number(row.scrap_qty) ? '#67C23A' : '#909399', fontWeight: 'bold' }">
{{ scannedQtyOf(row) }}
</span>
</template>
</el-table-column>
</el-table>
</div>
<div class="scan-section">
<!-- 扫码进度条 -->
<div v-if="selectedRequest && scanTotalQty > 0" class="scan-progress">
<div class="progress-info">
<span>扫码进度</span>
<el-tag type="success" size="small">{{ scanScannedTypes }}/{{ scanTotalTypes }} 种</el-tag>
<el-tag type="primary" size="small">{{ scanScannedQty }}/{{ scanTotalQty }} 件</el-tag>
<el-button
v-if="unscannedCount > 0"
type="warning" plain size="small" style="margin-left: auto;"
@click="showUnscannedDialog = true"
>
未扫清单 ({{ unscannedCount }})
</el-button>
</div>
<el-progress
:percentage="scanTotalQty > 0 ? Math.min(100, Math.round(scanScannedQty / scanTotalQty * 100)) : 0"
:stroke-width="8"
:color="scanScannedQty >= scanTotalQty ? '#67C23A' : '#F56C6C'"
/>
</div> </div>
<div class="input-box"> <template v-if="!selectedRequestId">
<el-input <div class="camera-placeholder" style="background-color: #f5f5f5; cursor: not-allowed;">
v-model="barcodeInput" <el-icon :size="40" color="#909399"><CameraFilled /></el-icon>
placeholder="扫描或输入条码回车" <span class="text">请先选择报废申请单</span>
@keyup.enter="handleManualInput" </div>
clearable <div class="input-box">
ref="barcodeRef" <el-input v-model="barcodeInput" placeholder="请先选择报废申请单" disabled size="large">
size="large" <template #prefix><el-icon><Scissor /></el-icon></template>
:disabled="!hasPermission" <template #append><el-button disabled>添加</el-button></template>
> </el-input>
<template #prefix> </div>
<el-icon><Scissor /></el-icon> </template>
</template> <template v-else>
<template #append> <div v-if="hasPermission" class="camera-placeholder" @click="showCamera = true">
<el-button @click="handleManualInput" :disabled="!hasPermission">添加</el-button> <el-icon :size="40" color="#409EFF"><CameraFilled /></el-icon>
</template> <span class="text">点击开启全屏扫码</span>
</el-input> </div>
</div> <div v-else class="camera-placeholder" style="background-color: #f5f5f5; cursor: not-allowed;">
<el-icon :size="40" color="#909399"><CameraFilled /></el-icon>
<span class="text">无扫码权限</span>
</div>
<div class="input-box">
<el-input
v-model="barcodeInput"
placeholder="扫描或输入条码回车"
@keyup.enter="handleManualInput"
clearable
ref="barcodeRef"
size="large"
:disabled="!hasPermission"
>
<template #prefix>
<el-icon><Scissor /></el-icon>
</template>
<template #append>
<el-button @click="handleManualInput" :disabled="!hasPermission">添加</el-button>
</template>
</el-input>
</div>
</template>
</div> </div>
<div class="cart-section"> <div class="cart-section">
<div v-if="cartItems.length > 0"> <div v-if="cartItems.length > 0">
<el-table :data="cartItems" border stripe style="width: 100%"> <el-table :data="cartItems" border stripe style="width: 100%">
<el-table-column prop="name" label="物品名称" min-width="120" show-overflow-tooltip /> <el-table-column prop="name" label="物品名称" min-width="120" show-overflow-tooltip />
<el-table-column prop="spec_model" label="规格" min-width="100" show-overflow-tooltip />
<el-table-column prop="sku" label="SKU" width="120" show-overflow-tooltip /> <el-table-column prop="sku" label="SKU" width="120" show-overflow-tooltip />
<el-table-column label="可用库存" width="90" align="center"> <el-table-column label="库存" width="70" align="center">
<template #default="{row}"> <template #default="{row}">
<el-tag type="info">{{ parseFloat(row.available_quantity) }}</el-tag> <el-tag :type="parseFloat(row.available_quantity) > 0 ? 'success' : 'danger'" size="small">
{{ parseFloat(row.available_quantity) }}
</el-tag>
</template> </template>
</el-table-column> </el-table-column>
<el-table-column label="报废数" width="130" align="center"> <el-table-column label="报废数" width="130" align="center">
<template #default="{row}"> <template #default="{row}">
<el-input-number <el-input-number
v-model="row.quantity" v-model="row.scrap_quantity"
:min="1" :min="1"
:max="parseFloat(row.available_quantity)" :max="maxScrapFor(row)"
size="small" size="small"
style="width: 100px" style="width: 100px"
:disabled="!hasPermission" :disabled="!hasPermission"
@ -67,14 +168,6 @@
</template> </template>
</el-table-column> </el-table-column>
<el-table-column label="损失金额" width="100" align="center">
<template #default="{row}">
<span style="color: #F56C6C; font-weight: bold;">
¥{{ ((row.price || 0) * row.quantity).toFixed(2) }}
</span>
</template>
</el-table-column>
<el-table-column v-if="hasPermission" label="操作" width="60" align="center" fixed="right"> <el-table-column v-if="hasPermission" label="操作" width="60" align="center" fixed="right">
<template #default="{$index}"> <template #default="{$index}">
<el-button type="danger" icon="Delete" circle size="small" @click="removeFromCart($index)" /> <el-button type="danger" icon="Delete" circle size="small" @click="removeFromCart($index)" />
@ -86,29 +179,17 @@
</div> </div>
<div v-if="cartItems.length > 0" class="form-section"> <div v-if="cartItems.length > 0" class="form-section">
<el-divider content-position="left">报废登记信息</el-divider> <el-divider content-position="left">报废执行信息</el-divider>
<el-form :model="form" ref="formRef" label-position="top"> <el-form :model="form" label-position="top">
<el-form-item label="报废原因" prop="reason" required> <el-form-item label="报废原因(来自申请单)" prop="reason">
<el-input <el-input v-model="form.reason" type="textarea" :rows="2" disabled />
v-model="form.reason"
type="textarea"
:rows="3"
placeholder="请详细填写报废原因,如:设备老化、损坏严重等"
size="large"
maxlength="500"
show-word-limit
/>
</el-form-item>
<el-form-item label="备注说明" prop="remark">
<el-input v-model="form.remark" type="textarea" :rows="2" placeholder="补充说明..." />
</el-form-item> </el-form-item>
<div class="bottom-actions"> <div class="bottom-actions">
<el-button v-if="hasPermission" @click="clearAll" icon="Refresh">清空</el-button> <el-button v-if="hasPermission" @click="clearAll" icon="Refresh">重扫</el-button>
<el-button v-if="hasPermission" type="danger" size="large" :loading="loading" @click="submitForm" icon="Select"> <el-button v-if="hasPermission" type="danger" size="large" :loading="loading" @click="submitForm" icon="Select">
确认报废 确认执行报废
</el-button> </el-button>
</div> </div>
</el-form> </el-form>
@ -127,26 +208,60 @@
</div> </div>
<div class="scanner-footer"> <div class="scanner-footer">
<p>请将条码/二维码放入镜头范围</p> <p>请对准条形码,识别成功后自动添加</p>
<p v-if="cartItems.length > 0" class="current-count">已添加: {{ cartItems.length }} 项</p> <p v-if="cartItems.length > 0" class="current-count">当前已添加: {{ scanScannedQty }} 件</p>
</div> </div>
</div> </div>
<!-- 未扫清单弹窗 -->
<el-dialog v-model="showUnscannedDialog" title="未扫清单" width="600px" destroy-on-close>
<el-alert
v-if="unscannedList.length > 0"
:title="`以下 ${unscannedList.length} 种物料还未扫满,请补扫(未扫满也可提交,将按实扫数量报废):`"
type="warning" :closable="false" show-icon style="margin-bottom: 12px;"
/>
<el-table :data="unscannedList" border size="small" max-height="400">
<el-table-column type="index" label="#" width="40" align="center" />
<el-table-column prop="name" label="物料名称" min-width="140" show-overflow-tooltip />
<el-table-column prop="sku" label="SKU" min-width="110" show-overflow-tooltip />
<el-table-column label="批准" width="70" align="center">
<template #default="{ row }">{{ row.planQty }}</template>
</el-table-column>
<el-table-column label="已扫" width="70" align="center">
<template #default="{ row }">
<span style="color: #67C23A;">{{ row.scannedQty }}</span>
</template>
</el-table-column>
<el-table-column label="待扫" width="70" align="center">
<template #default="{ row }">
<span style="color: #F56C6C; font-weight: bold;">{{ row.remaining }}</span>
</template>
</el-table-column>
</el-table>
<template #footer>
<el-button @click="showUnscannedDialog = false">关闭</el-button>
<el-button type="primary" @click="showUnscannedDialog = false; showCamera = true">去扫码</el-button>
</template>
</el-dialog>
</div> </div>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { ref, reactive, nextTick } from 'vue' import { ref, reactive, nextTick, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus' import { ElMessage, ElMessageBox } from 'element-plus'
import { Scissor, CameraFilled, Close, Refresh, Select, Delete } from '@element-plus/icons-vue' import { Scissor, CameraFilled } from '@element-plus/icons-vue'
import QrScanner from '@/components/QrScanner/index.vue' import QrScanner from '@/components/QrScanner/index.vue'
import { scanBarcode, createScrap } from '@/api/scrap' import { scanBarcode, getScrapApprovals, executeScrapByRequest } from '@/api/scrap'
import { useUserStore } from '@/stores/user' import { useUserStore } from '@/stores/user'
import { useRouter } from 'vue-router' import { useRouter, useRoute } from 'vue-router'
const router = useRouter() const router = useRouter()
const route = useRoute()
const userStore = useUserStore() const userStore = useUserStore()
const hasPermission = userStore.hasPermission('scrap_create:operation') const hasPermission = computed(() =>
userStore.role === 'SUPER_ADMIN' || userStore.hasPermission('scrap_execute')
)
// --- 状态定义 --- // --- 状态定义 ---
const barcodeInput = ref('') const barcodeInput = ref('')
@ -154,14 +269,144 @@ const cartItems = ref<any[]>([])
const loading = ref(false) const loading = ref(false)
const showCamera = ref(false) const showCamera = ref(false)
const barcodeRef = ref() const barcodeRef = ref()
const formRef = ref()
// 已批准的报废申请单
const approvalRequests = ref<any[]>([])
const selectedRequest = ref<any>(null)
const requestsLoading = ref(false)
const showUnscannedDialog = ref(false)
const form = reactive({ const form = reactive({
reason: '', reason: ''
remark: ''
}) })
// --- 核心扫码逻辑 --- // --- 计算属性 ---
const selectedRequestId = computed({
get: () => selectedRequest.value?.id ?? null,
set: (val) => {
if (!val) {
selectedRequest.value = null
} else {
selectedRequest.value = approvalRequests.value.find(r => r.id === val) ?? null
}
}
})
const plannedItems = computed<any[]>(() => selectedRequest.value?.items ?? [])
// 扫码进度
const scanTotalQty = computed(() =>
plannedItems.value.reduce((sum: number, it: any) => sum + (Number(it.scrap_qty) || 0), 0)
)
const scanScannedQty = computed(() =>
cartItems.value.reduce((sum: number, it: any) => sum + (Number(it.scrap_quantity) || 0), 0)
)
const scanScannedTypes = computed(() => cartItems.value.length)
const scanTotalTypes = computed(() => plannedItems.value.length)
// --- 按 (source_table, stock_id) 匹配计划项 ---
const matchPlan = (sourceTable: string, stockId: any) =>
plannedItems.value.find(
(p: any) => String(p.source_table) === String(sourceTable) && String(p.stock_id) === String(stockId)
)
// 某计划项已扫数量
const scannedQtyOf = (plan: any) =>
cartItems.value
.filter(ci => String(ci.source_table) === String(plan.source_table)
&& String(ci.stock_id) === String(plan.stock_id))
.reduce((sum, ci) => sum + (Number(ci.scrap_quantity) || 0), 0)
// 购物车某行还能再报废多少(批准量 - 其余行已占用量)
const maxScrapFor = (row: any) => {
const plan = matchPlan(row.source_table, row.stock_id)
const approved = Number(plan?.scrap_qty) || 0
const others = cartItems.value
.filter(ci => ci !== row
&& String(ci.source_table) === String(row.source_table)
&& String(ci.stock_id) === String(row.stock_id))
.reduce((sum, ci) => sum + (Number(ci.scrap_quantity) || 0), 0)
const avail = parseFloat(row.available_quantity) || 0
return Math.max(0, Math.min(approved - others, avail))
}
// 未扫清单
const unscannedList = computed(() =>
plannedItems.value.map((plan: any) => {
const planQty = Number(plan.scrap_qty) || 0
const scannedQty = scannedQtyOf(plan)
return {
name: plan.name || '',
sku: plan.sku || '',
planQty,
scannedQty,
remaining: Math.max(0, planQty - scannedQty)
}
}).filter((item: any) => item.remaining > 0)
)
const unscannedCount = computed(() => unscannedList.value.length)
const sourceLabel = (st: string) =>
({ stock_buy: '采购件', stock_semi: '半成品', stock_product: '成品' } as any)[st] || st || '-'
// --- 加载已批准的报废申请单 ---
const loadApprovalRequests = async () => {
requestsLoading.value = true
try {
const res: any = await getScrapApprovals({ scope: 'executable', status: 1, page: 1, limit: 100 })
approvalRequests.value = res.data?.items || []
// 支持从审批页跳转时带 requestId 直接选中
const presetId = Number(route.query.requestId)
if (presetId) {
const hit = approvalRequests.value.find(r => r.id === presetId)
if (hit) handleRequestChange(presetId)
else ElMessage.warning('指定的报废申请单不可执行(可能已被执行或状态已变更)')
}
} catch (e) {
console.error('加载报废申请单失败', e)
ElMessage.error('加载报废申请单失败')
} finally {
requestsLoading.value = false
}
}
const handleRequestChange = (val: number | null) => {
if (!val) {
selectedRequest.value = null
form.reason = ''
} else {
selectedRequest.value = approvalRequests.value.find(r => r.id === val) ?? null
form.reason = selectedRequest.value?.remark || ''
}
// 切换申请单时清空购物车,防止已扫物品与新单据混淆
cartItems.value = []
barcodeInput.value = ''
}
/**
* 校验扫码物品是否属于本申请单的批准明细,且累计不超批准量。
* 返回 null 表示通过,否则返回错误文案。
*/
const validateAgainstPlan = (item: any, addQty: number): string | null => {
const plan = matchPlan(item.source_table, item.id)
if (!plan) {
return `该物料【${item.name || item.sku}】不在申请单的批准明细中,禁止报废`
}
const approved = Number(plan.scrap_qty) || 0
const alreadyScanned = scannedQtyOf(plan)
if (alreadyScanned + addQty > approved) {
return `【${plan.name || plan.sku}】超出批准数量(批准: ${approved},已扫: ${alreadyScanned},本次: ${addQty})`
}
return null
}
// --- 扫码逻辑 ---
const onScanSuccess = (code: string) => { const onScanSuccess = (code: string) => {
if (!code) return if (!code) return
const trimCode = code.trim() const trimCode = code.trim()
@ -184,48 +429,95 @@ const onScanSuccess = (code: string) => {
} }
const handleManualInput = async () => { const handleManualInput = async () => {
if (!hasPermission.value) {
ElMessage.warning('无操作权限')
return
}
const code = barcodeInput.value.trim() const code = barcodeInput.value.trim()
if (!code) return if (!code) return
if (!selectedRequest.value) {
ElMessage.warning('请先选择要执行的报废申请单')
return
}
try { try {
loading.value = true loading.value = true
// 查重 // 1. 购物车已有该库存行 → 累加(按 source_table + id 去重,与申请单明细同口径)
const existIndex = cartItems.value.findIndex(item => item.barcode === code || item.sku === code) const existIndex = cartItems.value.findIndex(
item => String(item.source_table) === String(item.source_table) &&
(item.barcode === code || item.sku === code || String(item.id) === String(code))
)
if (existIndex > -1) { if (existIndex > -1) {
const item = cartItems.value[existIndex] const item = cartItems.value[existIndex]
const maxQty = parseFloat(item.available_quantity)
if (item.quantity < maxQty) { // ★ 越权/超量拦截:红色错误提示并阻断扫码
item.quantity++ const err = validateAgainstPlan(item, 1)
ElMessage.success(`数量+1 (当前: ${item.quantity})`) if (err) {
if (navigator.vibrate) navigator.vibrate(50) ElMessage.error(err)
} else { if (navigator.vibrate) navigator.vibrate([200, 100, 200])
ElMessage.warning(`库存不足 (余: ${maxQty})`) barcodeInput.value = ''
return
} }
const maxQty = maxScrapFor(item)
if (maxQty <= 0) {
ElMessage.error(`【${item.name}】已达批准数量上限,无法继续报废`)
if (navigator.vibrate) navigator.vibrate([200, 100, 200])
barcodeInput.value = ''
return
}
try {
await ElMessageBox.confirm(
`【${item.name} × ${item.spec_model || '-'}】已在清单中(当前已扫 ${item.scrap_quantity} 个)。\n\n确认再 +1 吗?`,
'重复扫码确认',
{ confirmButtonText: '确认 +1', cancelButtonText: '取消', type: 'warning' }
)
} catch (e) {
barcodeInput.value = ''
return
}
item.scrap_quantity++
ElMessage.success(`数量+1 (当前: ${item.scrap_quantity})`)
if (navigator.vibrate) navigator.vibrate(50)
barcodeInput.value = '' barcodeInput.value = ''
return return
} }
// 查库 // 2. 查库
const res = await scanBarcode(code) const res: any = await scanBarcode(code)
if (res.code === 200 && res.data) { if (res.code === 200 && res.data) {
const item = res.data const item = res.data
const availQty = parseFloat(item.available_quantity || 0)
if (availQty <= 0) { // ★ 校验是否在批准明细内 / 是否超批准量
ElMessage.warning(`库存不足 (余: ${availQty})`) const err = validateAgainstPlan(item, 1)
} else { if (err) {
cartItems.value.push({ ElMessage.error(err)
...item, if (navigator.vibrate) navigator.vibrate([200, 100, 200])
quantity: 1, barcodeInput.value = ''
price: item.price || 0 return
})
ElMessage.success(`添加成功: ${item.name}`)
if (navigator.vibrate) navigator.vibrate(100)
} }
const availQty = parseFloat(item.available_quantity || 0)
if (availQty <= 0) {
ElMessage.error(`库存不足 (余: ${availQty})`)
if (navigator.vibrate) navigator.vibrate([200, 100, 200])
barcodeInput.value = ''
return
}
cartItems.value.push({
...item,
scrap_quantity: 1
})
ElMessage.success(`添加成功: ${item.name}`)
if (navigator.vibrate) navigator.vibrate(100)
barcodeInput.value = '' barcodeInput.value = ''
} else { } else {
ElMessage.error(res.msg || '未找到该物料') ElMessage.error(res.msg || '未找到该物料')
if (navigator.vibrate) navigator.vibrate([200, 100, 200])
} }
} catch (error: any) { } catch (error: any) {
if (error.response && error.response.status === 404) { if (error.response && error.response.status === 404) {
@ -233,6 +525,7 @@ const handleManualInput = async () => {
} else { } else {
ElMessage.error('查询出错') ElMessage.error('查询出错')
} }
if (navigator.vibrate) navigator.vibrate([200, 100, 200])
} finally { } finally {
loading.value = false loading.value = false
if (!showCamera.value) { if (!showCamera.value) {
@ -242,251 +535,190 @@ const handleManualInput = async () => {
} }
const removeFromCart = (index: number) => { const removeFromCart = (index: number) => {
if (!hasPermission.value) {
ElMessage.warning('无操作权限')
return
}
cartItems.value.splice(index, 1) cartItems.value.splice(index, 1)
} }
const clearAll = () => { const clearAll = () => {
ElMessageBox.confirm('确定清空所有已选物品吗?', '提示', { type: 'warning' }) if (!hasPermission.value) {
ElMessage.warning('无操作权限')
return
}
ElMessageBox.confirm('确定清空所有已扫物品吗?(保留申请单选择)', '提示', { type: 'warning' })
.then(() => { .then(() => {
cartItems.value = [] cartItems.value = []
form.reason = ''
form.remark = ''
barcodeInput.value = '' barcodeInput.value = ''
}) })
.catch(() => {})
} }
// --- 提交逻辑 --- // --- 提交执行 ---
const submitForm = async () => { const submitForm = async () => {
if (!formRef.value) return if (!hasPermission.value) {
if (cartItems.value.length === 0) return ElMessage.warning('请先添加物品') ElMessage.warning('无操作权限')
// 验证报废原因
if (!form.reason.trim()) {
ElMessage.error('请填写报废原因')
return return
} }
if (!selectedRequest.value) return ElMessage.warning('请先选择要执行的报废申请单')
if (cartItems.value.length === 0) return ElMessage.warning('请先扫码添加报废物料')
// 检查报废数量 // 逐项复核批准量
const invalidItem = cartItems.value.find(item => !item.quantity || item.quantity <= 0) for (const item of cartItems.value) {
if (invalidItem) { const err = validateAgainstPlan(item, 0)
ElMessage.warning('请填写有效的报废数量') if (err) return ElMessage.error(err)
return if (!item.scrap_quantity || item.scrap_quantity <= 0) {
return ElMessage.warning('请填写有效的报废数量')
}
if (item.scrap_quantity > (parseFloat(item.available_quantity) || 0)) {
return ElMessage.error(`【${item.name}】报废数量超过当前可用库存`)
}
} }
// 检查报废数量是否超过可用库存 try {
const overstockItem = cartItems.value.find(item => item.quantity > parseFloat(item.available_quantity)) await ElMessageBox.confirm(
if (overstockItem) { `确认按实扫数量执行报废吗?\n申请单:${selectedRequest.value.request_no}\n共 ${cartItems.value.length} 项 / ${scanScannedQty.value} 件\n\n执行后不可撤销。`,
ElMessage.warning(`物料 ${overstockItem.sku} 报废数量超过可用库存`) '执行确认',
return { confirmButtonText: '确认执行', cancelButtonText: '取消', type: 'warning' }
} )
} catch { return }
try { try {
loading.value = true loading.value = true
const data = { const items = cartItems.value.map(item => ({
reason: form.reason, source_table: item.source_table,
remark: form.remark, stock_id: item.id,
items: cartItems.value.map(item => ({ quantity: item.scrap_quantity,
id: item.id, sku: item.sku ? String(item.sku) : '',
sku: item.sku, name: item.name ? String(item.name) : ''
source_table: item.source_table, }))
quantity: item.quantity
}))
}
const res = await createScrap(data) await executeScrapByRequest(selectedRequest.value.id, items)
if (res.code === 200) {
ElMessage.success('报废提交成功') ElMessage.success('已执行报废并扣减库存')
router.push('/scrap/index') router.push('/scrap/index')
} else { } catch (err: any) {
ElMessage.error(res.msg || '提交失败') // 拦截器已弹后端业务错误;无响应才算网络异常
} if (!err?.response) ElMessage.error('网络异常,请重试')
} catch (error: any) {
console.error(error)
ElMessage.error(error.response?.data?.msg || '提交失败')
} finally { } finally {
loading.value = false loading.value = false
} }
} }
onMounted(() => {
loadApprovalRequests()
})
</script> </script>
<style scoped> <style scoped>
.app-container { .app-container.mobile-optimized {
padding: 10px; padding: 10px; max-width: 700px; margin: 0 auto;
} }
.box-card { .card-header { display: flex; justify-content: space-between; align-items: center; }
max-width: 1200px; .title-box { font-size: 16px; font-weight: bold; display: flex; align-items: center; gap: 8px; }
margin: 0 auto;
}
.card-header { /* 模式条 */
.mode-switch-bar {
display: flex; display: flex;
justify-content: space-between;
align-items: center; align-items: center;
gap: 16px;
margin-bottom: 16px;
padding: 12px 16px;
background: #fef0f0;
border-radius: 8px;
border: 1px solid #fde2e2;
} }
.mode-hint { color: #909399; font-size: 13px; }
.title-box { /* 申请单选择 */
.approval-request-select { margin-bottom: 16px; }
.select-tip { margin: 6px 0 0 0; color: #909399; font-size: 12px; }
/* 待执行清单 */
.planned-items-section {
margin-bottom: 16px;
padding: 12px;
background: #fef0f0;
border: 1px solid #fde2e2;
border-radius: 8px;
}
.planned-header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 10px;
}
.planned-title { font-weight: bold; font-size: 14px; color: #F56C6C; }
/* 扫码区 */
.scan-section { margin-bottom: 20px; }
.scan-progress {
background: #f5f7fa;
border: 1px solid #ebeef5;
border-radius: 6px;
padding: 10px 14px;
margin-bottom: 12px;
}
.progress-info {
display: flex; display: flex;
align-items: center; align-items: center;
gap: 10px; gap: 10px;
font-size: 18px; margin-bottom: 6px;
font-weight: bold; font-size: 13px;
font-weight: 600;
} }
.scan-section {
margin-bottom: 20px;
}
.camera-placeholder { .camera-placeholder {
display: flex; height: 120px; background: #f5f7fa; border: 1px dashed #dcdfe6; border-radius: 8px;
flex-direction: column; display: flex; flex-direction: column; justify-content: center; align-items: center;
align-items: center; color: #909399; margin-bottom: 10px; cursor: pointer;
justify-content: center;
height: 180px;
background: linear-gradient(135deg, #ecf5ff 0%, #d9ecff 100%);
border: 2px dashed #409EFF;
border-radius: 8px;
cursor: pointer;
transition: all 0.3s; transition: all 0.3s;
} }
.camera-placeholder:active { background: #e6e8eb; }
.camera-placeholder .text { margin-top: 5px; font-size: 13px; }
.camera-placeholder:hover { .input-box :deep(.el-input__wrapper) { box-shadow: 0 0 0 1px #dcdfe6 inset; }
background: linear-gradient(135deg, #d9ecff 0%, #b3d8ff 100%);
transform: scale(1.01);
}
.camera-placeholder .text { /* 全屏扫码 */
margin-top: 10px;
color: #409EFF;
font-size: 14px;
}
.input-box {
margin-top: 15px;
}
.input-box :deep(.el-input__wrapper) {
box-shadow: 0 0 0 1px #dcdfe6 inset;
}
.input-box :deep(.el-input__wrapper:hover) {
box-shadow: 0 0 0 1px #c0c4cc inset;
}
.input-box :deep(.el-input__wrapper.is-focus) {
box-shadow: 0 0 0 1px #409EFF inset;
}
.cart-section {
margin-bottom: 20px;
}
.form-section {
margin-top: 20px;
padding-top: 20px;
border-top: 1px solid #eee;
}
.form-section :deep(.el-divider__text) {
font-weight: bold;
color: #F56C6C;
}
.bottom-actions {
display: flex;
justify-content: flex-end;
gap: 15px;
margin-top: 20px;
padding-top: 20px;
border-top: 1px solid #eee;
}
.bottom-actions .el-button--large {
padding: 12px 30px;
font-size: 16px;
}
/* 全屏扫码样式 */
.fullscreen-scanner-overlay { .fullscreen-scanner-overlay {
position: fixed; position: fixed;
top: 0; top: 0; left: 0; width: 100vw; height: 100vh;
left: 0; background: #000; z-index: 9999;
right: 0; display: flex; flex-direction: column;
bottom: 0;
background: #000;
z-index: 2000;
display: flex;
flex-direction: column;
} }
.scanner-header { .scanner-header {
display: flex; height: 60px; display: flex; align-items: center; justify-content: space-between;
align-items: center; padding: 0 15px; background: rgba(0,0,0,0.6); color: #fff;
justify-content: space-between; position: absolute; top: 0; width: 100%; z-index: 10;
padding: 15px;
background: rgba(0, 0, 0, 0.8);
color: #fff;
} }
.scanner-title { font-size: 16px; font-weight: bold; }
.scanner-title { .close-btn { background: rgba(255,255,255,0.2); border: none; color: #fff; }
font-size: 18px;
font-weight: bold;
}
.close-btn {
background: rgba(255, 255, 255, 0.2);
border: none;
color: #fff;
}
.scanner-placeholder {
width: 40px;
}
.scanner-body { .scanner-body {
flex: 1; flex: 1; width: 100%; position: relative;
display: flex; display: flex; align-items: center; justify-content: center;
align-items: center; }
justify-content: center; :deep(.qr-scanner-container) {
width: 100% !important; height: 100% !important; border-radius: 0 !important;
} }
.scanner-footer { .scanner-footer {
padding: 20px; position: absolute; bottom: 0; width: 100%;
text-align: center; padding: 20px; background: rgba(0,0,0,0.6); color: #fff;
background: rgba(0, 0, 0, 0.8); text-align: center; z-index: 10;
color: #fff;
} }
.current-count { color: #F56C6C; font-weight: bold; margin-top: 5px; font-size: 16px; }
.scanner-footer p { /* 表单与购物车 */
margin: 5px 0; .cart-section { margin-bottom: 20px; }
} .form-section { background: #fff; }
.form-section :deep(.el-divider__text) { font-weight: bold; color: #F56C6C; }
.current-count { .bottom-actions { display: flex; justify-content: space-between; margin-top: 20px; }
font-size: 16px; .bottom-actions .el-button { width: 48%; }
font-weight: bold;
color: #F56C6C;
}
@media (max-width: 768px) { @media screen and (max-width: 768px) {
.app-container { .title-box { font-size: 14px; }
padding: 5px; .camera-placeholder { height: 100px; }
}
.title-box {
font-size: 16px;
}
.camera-placeholder {
height: 120px;
}
.bottom-actions {
flex-direction: column;
}
.bottom-actions .el-button {
width: 100%;
}
} }
</style> </style>