diff --git a/src/api/stock/stock.ts b/src/api/stock/stock.ts index 7e0fc3e8..bcee774a 100644 --- a/src/api/stock/stock.ts +++ b/src/api/stock/stock.ts @@ -398,3 +398,69 @@ export function stockStockWarehouse(data: { pagination?: any; where?: any }) { isSystemApi: true } as any) } + +export function exportStockWarehouse(data: { where?: Record; group_by_batch?: boolean; sort?: Record }) { + return request({ + url: '/system', + method: 'post', + params: { + method: 'stock.warehouse.export', + v, + timestamp: new Date().getTime() + }, + data: data || {}, + isSystemApi: true + } as any) +} + +export function getExportTaskProgress(data: { task_id?: string; taskId?: string }) { + return request({ + url: '/system', + method: 'post', + params: { + method: 'stock.warehouse.exportTaskProgress', + v, + timestamp: new Date().getTime() + }, + data, + isSystemApi: true + } as any) +} + +export type StockWarehouseImportItem = { + stock_id?: string | number + sku?: string + item_code?: string + cargo_code?: string + sku_property?: string + stock_unit?: string + brand_name?: string + gross_weight?: string | number + tag_price?: string | number + retail_price?: string | number + [key: string]: any +} + +export type StockWarehouseImportPayload = + | StockWarehouseImportItem[] + | { + items?: StockWarehouseImportItem[] + rows?: StockWarehouseImportItem[] + list?: StockWarehouseImportItem[] + data?: StockWarehouseImportItem[] + [key: string]: any + } + +export function importStockWarehouse(data: StockWarehouseImportPayload) { + return request({ + url: '/system', + method: 'post', + params: { + method: 'stock.warehouse.import', + v, + timestamp: new Date().getTime() + }, + data, + isSystemApi: true + } as any) +} diff --git a/src/api/storage_receiving/receiving.ts b/src/api/storage_receiving/receiving.ts index 046acfb6..e3082068 100644 --- a/src/api/storage_receiving/receiving.ts +++ b/src/api/storage_receiving/receiving.ts @@ -294,6 +294,32 @@ export function detailChange(data: any): Promise { }) } +export function addDetail(data: any): Promise { + return request({ + url: '/system', + method: 'post', + params: { + method: 'storage.receiving.addDetail', + v, + timestamp: new Date().getTime() + }, + data + }) +} + +export function deleteDetail(data: any): Promise { + return request({ + url: '/system', + method: 'post', + params: { + method: 'storage.receiving.deleteDetail', + v, + timestamp: new Date().getTime() + }, + data + }) +} + export function save(data: any): Promise { return request({ url: '/system', diff --git a/src/views/stock/stock/index.vue b/src/views/stock/stock/index.vue index d100bee5..a86b71a2 100644 --- a/src/views/stock/stock/index.vue +++ b/src/views/stock/stock/index.vue @@ -77,11 +77,22 @@ :icon="Download" @click="handleExport" title="导出" - :loading="loading" + :loading="exportLoading" > 导出 + + 导入 + + + + +
+
+ 任务ID:{{ exportTaskProgress.taskId || '—' }} +
+ +
+ 状态:{{ exportStatusText }} + 进度:{{ exportProgressPercent }}% + 更新时间:{{ formatDateTime(exportTaskProgress.updateTime) }} +
+
+ {{ exportTaskProgress.error || exportTaskProgress.message }} +
+
+
+ + +
+
+ + 选择文件 + {{ selectedImportFileName || '未选择文件' }} +
+
+ 汇总:共 {{ importSummary.total }} 条,新增 {{ importSummary.addCount }} 条,修改 {{ importSummary.updateCount }} 条 +
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+ + +
diff --git a/src/views/storage/receiving/component/Product.vue b/src/views/storage/receiving/component/Product.vue index bdca9468..0357add5 100644 --- a/src/views/storage/receiving/component/Product.vue +++ b/src/views/storage/receiving/component/Product.vue @@ -2,25 +2,15 @@
+ 新增商品 + 批量导入商品 刷新 全部 已匹配 未匹配 - 添加商品 - 批量操作 - - - - - +
@@ -88,14 +78,36 @@ @@ -123,69 +135,8 @@
- - - - - + @@ -216,6 +167,236 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+ + + + 已按收货单货主过滤:{{ boundStoreName || ('ID ' + boundStoreId) }} + 当前收货单未绑定货主,查询不过滤货主 +
+ +
+ +
+
+ +
+ + +
+
+ + + +
+ +
+ +
+
+ +
+ + +
+ + 选择Excel + 下载模板 + 清除数据 + 只重试失败 + 导入 + 已选文件:{{ batchImportFileName || '未选择' }} +
+ +
+ + + + + +
+ +
+ 已生成基础新增数组:{{ batchImportAddItems.length }} 条 +
+ + +
+
@@ -280,7 +461,10 @@ import UpperTable from '@/components/UpperTable/index.vue' import AddProduct from '@/views/stock/stock/component/add.vue' import * as receivingApi from '@/api/storage_receiving/receiving' import * as stockApi from '@/api/stock/stock' +import * as indexApi from '@/api/index/index' +import * as warehouseApi from '@/api/warehouse/warehouse' import { buildStockQuery } from '@/utils/stockQueryBuilder' +import * as XLSX from 'xlsx' import basic from '../window/basic.vue' import log from '../window/log.vue' @@ -296,9 +480,7 @@ const props = defineProps<{ const tableData = ref([]) const multipleSelection = ref([]) -const saveLoading = ref(false) const matchFilter = ref('all') -const validityUnit = ref<'year' | 'month' | 'day'>('day') const filteredTableData = computed(() => { if (matchFilter.value === 'matched') { @@ -309,6 +491,52 @@ const filteredTableData = computed(() => { return tableData.value }) +const isMatchedRow = (row: any) => { + const status = String(row?.match_status || '').toLowerCase() + return !!row?.system_product_id || row?.is_matched === true || row?.is_matched === 1 || status === 'matched' || status === '已匹配' +} + +const isReadOnlyStatus = (status: any) => { + const normalized = String(status || '').toLowerCase() + return normalized === 'completed' || normalized === 'cancelled' || normalized === 'canceled' || normalized === '已完成' || normalized === '已作废' +} + +const isRowReadOnly = (row?: any) => { + if (isReadOnlyStatus(props.row?.status || props.row?.receiving_status)) return true + return isReadOnlyStatus(row?.status || row?.receiving_status || row?.receiving?.status) +} + +const getDetailIdFromRow = (row?: any) => { + const id = Number(row?.detail_id ?? row?.id) + if (!Number.isFinite(id) || id <= 0) return undefined + return id +} + +const isRowNotStored = (row?: any) => { + const storageStatus = String(row?.storage_status ?? '').toLowerCase().trim() + if (!storageStatus) { + const storedQuantity = Number(row?.stored_quantity ?? row?.inbound_quantity ?? 0) + return !Number.isFinite(storedQuantity) || storedQuantity <= 0 + } + + if (storageStatus === 'none' || storageStatus === '未入库') return true + if (storageStatus === 'all' || storageStatus === '全部入库' || storageStatus === 'partial' || storageStatus === '部分入库') { + return false + } + + const storedQuantity = Number(row?.stored_quantity ?? row?.inbound_quantity ?? 0) + return !Number.isFinite(storedQuantity) || storedQuantity <= 0 +} + +const canDeleteDetailRow = (row?: any) => { + if (!row || isRowReadOnly(row)) return false + return isRowNotStored(row) +} + +const showReadOnlyTip = () => { + ElMessage.warning('该收货单状态下商品明细为只读,不可操作') +} + const DAY_MS = 24 * 60 * 60 * 1000 const getDate = (value?: string) => { @@ -323,6 +551,15 @@ const isExpired = (expiryDate?: string) => { return expiry.getTime() < Date.now() } +const formatValidity = (productionDate?: string, expiryDate?: string) => { + const start = getDate(productionDate) + const end = getDate(expiryDate) + if (!start || !end) return '--' + const diff = Math.floor((end.getTime() - start.getTime()) / DAY_MS) + if (!Number.isFinite(diff)) return '--' + return `${diff}天` +} + const calcDiffYears = (start: Date, end: Date) => { let years = end.getFullYear() - start.getFullYear() const monthDiff = end.getMonth() - start.getMonth() @@ -341,21 +578,6 @@ const calcDiffMonths = (start: Date, end: Date) => { return months } -const formatValidity = (productionDate?: string, expiryDate?: string) => { - const start = getDate(productionDate) - const end = getDate(expiryDate) - if (!start || !end) return '--' - const diffMs = end.getTime() - start.getTime() - if (diffMs < 0) return `0${validityUnit.value === 'day' ? '天' : validityUnit.value === 'month' ? '月' : '年'}` - - if (validityUnit.value === 'year') { - return `${calcDiffYears(start, end)}年` - } - if (validityUnit.value === 'month') { - return `${calcDiffMonths(start, end)}月` - } - return `${Math.floor(diffMs / DAY_MS)}天` -} // 分页相关 const pagination = reactive({ @@ -395,6 +617,60 @@ const loadProductData = () => { emit('refresh-product') } +const isDeletingRow = (row?: any) => { + const detailId = getDetailIdFromRow(row) + if (!detailId) return false + return deletingDetailId.value === detailId +} + +const confirmDeleteDetail = async (row: any) => { + if (isRowReadOnly(row)) { + showReadOnlyTip() + return + } + + if (!isRowNotStored(row)) { + ElMessage.warning('仅未入库明细支持删除') + return + } + + const detailId = getDetailIdFromRow(row) + if (!detailId) { + ElMessage.warning('缺少有效的收货明细ID') + return + } + + try { + await ElMessageBox.confirm( + '确认删除该收货明细吗?删除后将回算统计数据。', + '删除确认', + { + type: 'warning', + confirmButtonText: '确认删除', + cancelButtonText: '取消' + } + ) + } catch { + return + } + + deletingDetailId.value = detailId + try { + const res: any = await receivingApi.deleteDetail({ detail_id: detailId }) + if (res && (res.code === 200 || res.flag === 'success')) { + ElMessage.success(res?.message || '删除成功') + loadProductData() + } else { + ElMessage.error(res?.message || '删除失败') + } + } catch (error) { + console.error('删除收货明细失败', error) + ElMessage.error('删除收货明细失败') + } finally { + deletingDetailId.value = null + } +} + async function fetchReceivingDetail() { try { const params = { @@ -470,21 +746,6 @@ const position = ref({ x: 350, y: 250 }) const isDragging = ref(false) const dragOffset = ref({ x: 0, y: 0 }) -// 快速关联弹窗控制 -const quickLinkVisible = ref(false) -const isQuickFullscreen = ref(false) -const quickPosition = ref({ x: 250, y: 150 }) -const isQuickDragging = ref(false) -const quickDragOffset = ref({ x: 0, y: 0 }) -const quickSearchQuery = ref('') -const quickLinkStore = ref(null) -// 快速关联搜索结果状态 -const quickSearchResults = ref([]) -const quickSearchLoading = ref(false) -const quickResultPagination = reactive({ page: 1, pageSize: 10, total: 0 }) -const selectedSystemProduct = ref(null) -const multipleQuickSelection = ref([]) - // 添加商品抽屉 const addDrawerVisible = ref(false) const addDrawerStore = ref(null) @@ -497,6 +758,1211 @@ const dateForm = reactive({ expiry_date: '' }) +const editDialogVisible = ref(false) +const editSaving = ref(false) +const editingDetailRow = ref(null) +const editDialogMode = ref<'edit' | 'add'>('edit') +const editForm = reactive({ + actual_quantity: '', + batch_number: '', + production_date: '', + expiry_date: '', + shelf_life_days: '', + inbound_min_days: '', + box_quantity: '', + boxes_per_pallet: '', + pallet_quantity: '', + space_id: '', + remark: '', + system_product_id: '', + barcode: '', + product_name: '', + box_width: '', + box_height: '', + box_length: '', + box_remainder: '', + box_weight: '', + weight: '', + space_display_name: '', + is_shelf_life_mgmt: '', + is_batch_mgmt: '' +}) + +const systemProductPickerVisible = ref(false) +const systemProductLoading = ref(false) +const systemProductKeyword = ref('') +const systemProductResults = ref([]) +const systemProductSelection = ref([]) +const systemProductPagination = reactive({ page: 1, pageSize: 10, total: 0 }) + +const spacePickerVisible = ref(false) +const spaceLoading = ref(false) +const spaceKeyword = ref('') +const spaceResults = ref([]) +const spaceSelection = ref([]) +const spacePagination = reactive({ page: 1, pageSize: 10, total: 0 }) + +const batchImportDialogVisible = ref(false) +const batchImportLoading = ref(false) +const batchImportInputRef = ref(null) +const batchImportSourceFile = ref(null) +const batchImportFileName = ref('') +const batchImportPreviewRows = ref([]) +const batchImportAddItems = ref([]) +const batchImportEditingRow = ref(null) +const batchImportPickerMode = ref<'space' | 'sku' | ''>('') +const batchRetryFailedLoading = ref(false) +const deletingDetailId = ref(null) + +const spaceDisplayName = computed(() => { + return String(editForm.space_display_name || '').trim() || (String(editForm.space_id || '').trim() ? `ID ${editForm.space_id}` : '') +}) + +const hasSkuSelected = computed(() => { + return String(editForm.system_product_id ?? '').trim() !== '' +}) + +const editDialogTitle = computed(() => (editDialogMode.value === 'add' ? '新增商品明细' : '编辑收货明细')) + +const toBoolFlag = (val: any) => { + if (val === null || val === undefined || val === '') return false + if (typeof val === 'boolean') return val + if (typeof val === 'number') return val === 1 + const normalized = String(val).trim().toLowerCase() + return normalized === '1' || normalized === 'y' || normalized === 'yes' || normalized === 'true' || normalized === '是' +} + +const isShelfLifeManaged = computed(() => toBoolFlag(editForm.is_shelf_life_mgmt)) +const isBatchManaged = computed(() => toBoolFlag(editForm.is_batch_mgmt)) + +const boundStoreId = computed(() => { + const candidates = [ + editingDetailRow.value?.store_id, + editingDetailRow.value?.store?.id, + editingDetailRow.value?.receiving?.store_id, + editingDetailRow.value?.receiving?.store?.id, + props.row?.store_id, + props.row?.store?.id + ] + for (const c of candidates) { + const n = Number(c) + if (Number.isFinite(n) && n > 0) return n + } + return undefined +}) + +const boundStoreName = computed(() => { + return ( + editingDetailRow.value?.store?.store_remask || + editingDetailRow.value?.store?.store_name || + editingDetailRow.value?.receiving?.store?.store_remask || + editingDetailRow.value?.receiving?.store?.store_name || + props.row?.store?.store_remask || + props.row?.store?.store_name || + props.row?.store_name || + '' + ) +}) + +const resetEditForm = () => { + Object.keys(editForm).forEach((k) => { + editForm[k] = '' + }) +} + +const getSpaceDisplayName = (space: any) => { + const customName = String(space?.custom_name ?? space?.customName ?? '').trim() + if (customName) return customName + return String(space?.space_name ?? space?.name ?? space?.space_code ?? '').trim() +} + +const resolveSpaceDisplayNameById = async (spaceId: any) => { + const rawId = String(spaceId ?? '').trim() + if (!rawId) return '' + + const parsedId = Number(rawId) + if (!Number.isFinite(parsedId) || parsedId <= 0) return '' + + try { + const info: any = await warehouseApi.getSpaceInfo(parsedId) + const direct = info?.data || info + return getSpaceDisplayName(direct) + } catch (error) { + console.error('按ID获取库位名称失败', error) + return '' + } +} + +const parseNonNegativeInteger = (val: any): number | undefined => { + if (val === null || val === undefined) return undefined + const text = String(val).trim() + if (!text) return undefined + const num = Number(text) + if (!Number.isFinite(num)) return undefined + return Math.max(0, Math.floor(num)) +} + +const setEditFieldInteger = (field: string, value: number | undefined) => { + editForm[field] = value === undefined ? '' : String(value) +} + +const parseDaysInteger = (val: any) => { + const text = String(val ?? '').trim() + if (!text) return undefined + const num = Number(text) + if (!Number.isFinite(num)) return undefined + return Math.max(0, Math.floor(num)) +} + +const toDateStart = (dateStr?: string) => { + const d = getDate(dateStr) + if (!d) return null + const next = new Date(d) + next.setHours(0, 0, 0, 0) + return next +} + +const formatDateYMD = (date: Date) => { + const year = date.getFullYear() + const month = String(date.getMonth() + 1).padStart(2, '0') + const day = String(date.getDate()).padStart(2, '0') + return `${year}-${month}-${day}` +} + +const shiftDateByDays = (dateStr: string, days: number) => { + const base = toDateStart(dateStr) + if (!base || !Number.isFinite(days)) return '' + const next = new Date(base) + next.setDate(next.getDate() + Math.floor(days)) + return formatDateYMD(next) +} + +const getTodayStart = () => { + const today = new Date() + today.setHours(0, 0, 0, 0) + return today +} + +const getExpiryRemainingDays = (expiryDate?: string) => { + const expiry = toDateStart(expiryDate) + if (!expiry) return undefined + const today = getTodayStart() + return Math.floor((expiry.getTime() - today.getTime()) / DAY_MS) +} + +const validateInboundMinDaysConstraint = (showMessage = true) => { + if (!hasSkuSelected.value || !isShelfLifeManaged.value) return true + const inboundMinDays = parseDaysInteger(editForm.inbound_min_days) + if (inboundMinDays === undefined || inboundMinDays <= 0) return true + + const expiryDate = String(editForm.expiry_date ?? '').trim() + if (!expiryDate) return true + + const remainingDays = getExpiryRemainingDays(expiryDate) + if (remainingDays === undefined) return true + if (remainingDays >= inboundMinDays) return true + + if (showMessage) { + ElMessage.error(`保质期低于${inboundMinDays}天,商品已设置禁止入库`) + } + return false +} + +const onEditProductionDateChange = () => { + if (!hasSkuSelected.value || !isShelfLifeManaged.value) { + validateInboundMinDaysConstraint(true) + return + } + + const shelfLifeDays = parseDaysInteger(editForm.shelf_life_days) + const productionDate = String(editForm.production_date ?? '').trim() + const expiryDate = String(editForm.expiry_date ?? '').trim() + if (shelfLifeDays !== undefined && shelfLifeDays > 0 && productionDate && !expiryDate) { + editForm.expiry_date = shiftDateByDays(productionDate, shelfLifeDays) + } + validateInboundMinDaysConstraint(true) +} + +const onEditExpiryDateChange = () => { + if (!hasSkuSelected.value || !isShelfLifeManaged.value) { + validateInboundMinDaysConstraint(true) + return + } + + const shelfLifeDays = parseDaysInteger(editForm.shelf_life_days) + const productionDate = String(editForm.production_date ?? '').trim() + const expiryDate = String(editForm.expiry_date ?? '').trim() + if (shelfLifeDays !== undefined && shelfLifeDays > 0 && expiryDate && !productionDate) { + editForm.production_date = shiftDateByDays(expiryDate, -shelfLifeDays) + } + validateInboundMinDaysConstraint(true) +} + +const handleQuantityLinkage = (source: 'actual_quantity' | 'box_quantity' | 'boxes_per_pallet' | 'box_remainder') => { + const total = parseNonNegativeInteger(editForm.actual_quantity) + const boxCount = parseNonNegativeInteger(editForm.box_quantity) + const boxSpec = parseNonNegativeInteger(editForm.boxes_per_pallet) + const remainderRaw = parseNonNegativeInteger(editForm.box_remainder) + + if (!boxSpec || boxSpec <= 0) { + return + } + + if (source === 'actual_quantity' || (source === 'boxes_per_pallet' && total !== undefined)) { + const safeTotal = total ?? 0 + const nextBoxCount = Math.floor(safeTotal / boxSpec) + const nextRemainder = safeTotal % boxSpec + setEditFieldInteger('box_quantity', nextBoxCount) + setEditFieldInteger('box_remainder', nextRemainder) + setEditFieldInteger('actual_quantity', safeTotal) + return + } + + let safeBoxCount = boxCount ?? 0 + let safeRemainder = remainderRaw ?? 0 + + if (safeRemainder >= boxSpec) { + safeBoxCount += Math.floor(safeRemainder / boxSpec) + safeRemainder = safeRemainder % boxSpec + } + + const nextTotal = safeBoxCount * boxSpec + safeRemainder + setEditFieldInteger('box_quantity', safeBoxCount) + setEditFieldInteger('box_remainder', safeRemainder) + setEditFieldInteger('actual_quantity', nextTotal) +} + +const openEditDialog = (row: any) => { + if (isRowReadOnly(row)) { + showReadOnlyTip() + return + } + editDialogMode.value = 'edit' + editingDetailRow.value = row + editForm.actual_quantity = row?.actual_quantity ?? row?.quantity ?? '' + editForm.batch_number = row?.batch_number ?? '' + editForm.production_date = row?.production_date ?? '' + editForm.expiry_date = row?.expiry_date ?? '' + editForm.box_quantity = row?.box_quantity ?? '' + editForm.boxes_per_pallet = row?.boxes_per_pallet ?? '' + editForm.pallet_quantity = row?.pallet_quantity ?? '' + editForm.space_id = row?.space_id ?? '' + editForm.space_display_name = + String(row?.space_custom_name ?? '').trim() || + String(row?.space_name ?? '').trim() || + String(row?.space_code ?? '').trim() || + (row?.space_id ? `ID ${row.space_id}` : '') + editForm.remark = row?.remark ?? '' + editForm.system_product_id = row?.system_product_id ?? '' + editForm.barcode = row?.barcode ?? row?.barcodes ?? '' + editForm.product_name = row?.product_name ?? row?.item_name ?? '' + editForm.box_width = row?.box_width ?? '' + editForm.box_height = row?.box_height ?? '' + editForm.box_length = row?.box_length ?? '' + editForm.box_remainder = row?.box_remainder ?? '' + editForm.box_weight = row?.box_weight ?? '' + editForm.weight = row?.weight ?? '' + editForm.is_shelf_life_mgmt = + row?.is_shelf_life_mgmt ?? + row?.is_shelf_life_manage ?? + row?.is_validity_mgmt ?? + row?.system_product?.is_shelf_life_mgmt ?? + row?.system_product?.is_shelf_life_manage ?? + '' + editForm.shelf_life_days = + row?.shelf_life_days ?? + row?.system_product?.shelf_life_days ?? + '' + editForm.is_batch_mgmt = + row?.is_batch_mgmt ?? + row?.is_batch_manage ?? + row?.system_product?.is_batch_mgmt ?? + row?.system_product?.is_batch_manage ?? + '' + editForm.inbound_min_days = + row?.inbound_min_days ?? + row?.system_product?.inbound_min_days ?? + '' + + const shouldResolveSpaceName = + !!String(editForm.space_id ?? '').trim() && + !String(row?.space_custom_name ?? '').trim() && + !String(row?.space_name ?? '').trim() && + !String(row?.space_code ?? '').trim() + + if (shouldResolveSpaceName) { + void resolveSpaceDisplayNameById(editForm.space_id).then((name) => { + if (!name) return + if (editingDetailRow.value?.id !== row?.id) return + editForm.space_display_name = name + }) + } + + if (String(editForm.production_date ?? '').trim() && !String(editForm.expiry_date ?? '').trim()) { + onEditProductionDateChange() + } else if (String(editForm.expiry_date ?? '').trim() && !String(editForm.production_date ?? '').trim()) { + onEditExpiryDateChange() + } else { + validateInboundMinDaysConstraint(false) + } + + handleQuantityLinkage('actual_quantity') + editDialogVisible.value = true +} + +const openAddItemDialog = () => { + if (isReadOnlyStatus(props.row?.status || props.row?.receiving_status)) { + showReadOnlyTip() + return + } + + editDialogMode.value = 'add' + editingDetailRow.value = null + resetEditForm() + editDialogVisible.value = true +} + +const openBatchImportDialog = () => { + batchImportDialogVisible.value = true +} + +const openBatchRowSpacePicker = async (row: any) => { + batchImportEditingRow.value = row + batchImportPickerMode.value = 'space' + await openSpacePicker() +} + +const openBatchRowSkuPicker = async (row: any) => { + batchImportEditingRow.value = row + batchImportPickerMode.value = 'sku' + await openSystemProductPicker() +} + +const triggerBatchImportSelect = () => { + batchImportInputRef.value?.click() +} + +const onBatchImportFileChange = (evt: Event) => { + const input = evt.target as HTMLInputElement + const file = input?.files?.[0] + if (!file) return + const lowerName = String(file.name || '').toLowerCase() + if (!lowerName.endsWith('.xlsx')) { + ElMessage.warning('仅支持 .xlsx 文件') + input.value = '' + return + } + batchImportSourceFile.value = file + batchImportFileName.value = file.name + void generateBatchImportList() + input.value = '' +} + +const downloadBatchImportTemplate = () => { + const headers = [ + 'SKU', + '条码', + '商品名称', + '实际收货数量', + '箱规', + '托盘数', + '批次号', + '生产日期', + '到期日期', + '库位条码或名称', + '毛重/重量', + '箱长', + '箱宽', + '箱高', + '实测箱重', + '备注' + ] + const sample = ['', '', '', 0, 1, '', '', '', '', '', '', '', '', '', '', ''] + const ws = XLSX.utils.aoa_to_sheet([headers, sample]) + const wb = XLSX.utils.book_new() + XLSX.utils.book_append_sheet(wb, ws, '批量导入商品') + XLSX.writeFile(wb, `收货商品导入模板_${Date.now()}.xlsx`) +} + +const pickImportValue = (row: Record, keys: string[]) => { + for (const key of keys) { + if (Object.prototype.hasOwnProperty.call(row, key)) { + const v = row[key] + if (v !== null && v !== undefined && String(v).trim() !== '') { + return v + } + } + } + return '' +} + +const toImportNumber = (val: any) => { + const text = String(val ?? '').trim() + if (!text) return undefined + const num = Number(text) + return Number.isFinite(num) ? num : undefined +} + +const toImportString = (val: any) => { + if (Array.isArray(val)) { + const parts = val + .map((item) => String(item ?? '').trim()) + .filter((item) => !!item) + return parts.length ? parts.join(',') : undefined + } + if (val && typeof val === 'object') { + const candidates = [val.barcode, val.code, val.value] + for (const candidate of candidates) { + const text = String(candidate ?? '').trim() + if (text) return text + } + return undefined + } + const text = String(val ?? '').trim() + return text || undefined +} + +const normalizeBarcodeString = (barcodes: any, fallback?: any) => { + const barcodeFromList = toImportString(barcodes) + if (barcodeFromList) return barcodeFromList + return toImportString(fallback) || '' +} + +const normalizeQuantityByTotalAndSpec = (itemPayload: any) => { + const total = Number(itemPayload?.actual_quantity) + const boxSpec = Number(itemPayload?.boxes_per_pallet) + if (!Number.isFinite(total) || !Number.isFinite(boxSpec) || boxSpec <= 0) return + const safeTotal = Math.max(0, Math.floor(total)) + const safeSpec = Math.max(1, Math.floor(boxSpec)) + itemPayload.actual_quantity = safeTotal + itemPayload.boxes_per_pallet = safeSpec + itemPayload.box_quantity = Math.floor(safeTotal / safeSpec) + itemPayload.box_remainder = safeTotal % safeSpec +} + +const querySystemProductById = async (skuId: number) => { + if (!Number.isFinite(skuId) || skuId <= 0) return null + try { + const where = buildStockQuery({ id: skuId }) + const res: any = await stockApi.stockWarehouse({ page: 1, pageSize: 1 }, where) + const list = res?.data?.list || [] + return list[0] || null + } catch (error) { + console.error('按SKU查询商品失败', error) + return null + } +} + +const generateBatchImportList = async () => { + if (!batchImportSourceFile.value) { + ElMessage.warning('请先选择Excel文件') + return + } + + batchImportLoading.value = true + try { + const buffer = await batchImportSourceFile.value.arrayBuffer() + const wb = XLSX.read(buffer, { type: 'array' }) + const firstName = wb.SheetNames[0] + if (!firstName) { + ElMessage.warning('Excel中没有可读取的工作表') + return + } + + const ws = wb.Sheets[firstName] + if (!ws) { + ElMessage.warning('工作表读取失败') + return + } + const rawRows = XLSX.utils.sheet_to_json>(ws, { defval: '' }) + + const previewRows: any[] = [] + const addItems: any[] = [] + + for (let index = 0; index < rawRows.length; index += 1) { + const row = (rawRows[index] || {}) as Record + const itemPayload: any = {} + + const systemProductId = toImportNumber(pickImportValue(row, ['SKU', '系统商品ID', 'system_product_id'])) + const barcode = toImportString(pickImportValue(row, ['条码', 'barcode', 'barcodes'])) + const productName = toImportString(pickImportValue(row, ['商品名称', 'product_name', 'item_name'])) + const actualQuantity = toImportNumber(pickImportValue(row, ['实际收货数量', 'actual_quantity'])) + const boxQuantity = toImportNumber(pickImportValue(row, ['箱数', 'box_quantity'])) + const boxSpec = toImportNumber(pickImportValue(row, ['箱规', 'boxes_per_pallet'])) + const boxRemainder = toImportNumber(pickImportValue(row, ['剩余不满一箱', 'box_remainder'])) + const palletQuantity = toImportNumber(pickImportValue(row, ['托盘数', 'pallet_quantity'])) + const batchNumber = toImportString(pickImportValue(row, ['批次号', 'batch_number'])) + const productionDate = toImportString(pickImportValue(row, ['生产日期', 'production_date'])) + const expiryDate = toImportString(pickImportValue(row, ['到期日期', 'expiry_date'])) + const spaceKeyword = toImportString(pickImportValue(row, ['库位条码或名称', '库位名称', '库位条码', '库位ID', 'space_id', 'space_code', 'space_name'])) + const weight = toImportNumber(pickImportValue(row, ['毛重/重量', 'weight'])) + const boxLength = toImportNumber(pickImportValue(row, ['箱长', 'box_length'])) + const boxWidth = toImportNumber(pickImportValue(row, ['箱宽', 'box_width'])) + const boxHeight = toImportNumber(pickImportValue(row, ['箱高', 'box_height'])) + const boxWeight = toImportNumber(pickImportValue(row, ['实测箱重', 'box_weight'])) + const remark = toImportString(pickImportValue(row, ['备注', 'remark'])) + + if (systemProductId !== undefined) itemPayload.system_product_id = systemProductId + if (barcode !== undefined) itemPayload.barcode = barcode + if (productName !== undefined) itemPayload.product_name = productName + if (actualQuantity !== undefined) itemPayload.actual_quantity = actualQuantity + if (boxSpec !== undefined) itemPayload.boxes_per_pallet = boxSpec + if (palletQuantity !== undefined) itemPayload.pallet_quantity = palletQuantity + if (batchNumber !== undefined) itemPayload.batch_number = batchNumber + if (productionDate !== undefined) itemPayload.production_date = productionDate + if (expiryDate !== undefined) itemPayload.expiry_date = expiryDate + if (weight !== undefined) itemPayload.weight = weight + if (boxLength !== undefined) itemPayload.box_length = boxLength + if (boxWidth !== undefined) itemPayload.box_width = boxWidth + if (boxHeight !== undefined) itemPayload.box_height = boxHeight + if (boxWeight !== undefined) itemPayload.box_weight = boxWeight + if (remark !== undefined) itemPayload.remark = remark + + normalizeQuantityByTotalAndSpec(itemPayload) + + if (systemProductId !== undefined) { + const product = await querySystemProductById(systemProductId) + if (product) { + itemPayload.product_name = product.item_name || product.product_name || itemPayload.product_name + itemPayload.barcode = normalizeBarcodeString(product.barcodes, product.barcode) || itemPayload.barcode + } + } + + let resolvedSpaceKeyword = spaceKeyword ?? '' + if (spaceKeyword) { + const resolvedSpace = await resolveSpaceByKeyword(spaceKeyword) + if (resolvedSpace.id) { + itemPayload.space_id = resolvedSpace.id + } + if (resolvedSpace.displayName) { + resolvedSpaceKeyword = resolvedSpace.displayName + } + } + + if (Object.keys(itemPayload).length === 0) return + + previewRows.push({ + row_no: index + 2, + system_product_id: itemPayload.system_product_id ?? '', + barcode: itemPayload.barcode ?? '', + product_name: itemPayload.product_name ?? '', + actual_quantity: itemPayload.actual_quantity ?? '', + box_quantity: itemPayload.box_quantity ?? '', + boxes_per_pallet: itemPayload.boxes_per_pallet ?? '', + box_remainder: itemPayload.box_remainder ?? '', + space_keyword: resolvedSpaceKeyword, + import_status: '待导入', + import_message: '', + remark: itemPayload.remark ?? '', + item_payload: itemPayload + }) + } + + batchImportPreviewRows.value = previewRows + addItems.push(...previewRows.map((r) => ({ item: { ...(r.item_payload || {}) } }))) + batchImportAddItems.value = addItems + ElMessage.success(`已生成 ${addItems.length} 条基础新增数据`) + } catch (error) { + console.error('解析导入文件失败', error) + ElMessage.error('解析导入文件失败') + } finally { + batchImportLoading.value = false + } +} + +const clearBatchImportData = () => { + batchImportPreviewRows.value = [] + batchImportAddItems.value = [] + batchImportSourceFile.value = null + batchImportFileName.value = '' +} + +const resolveSpaceByKeyword = async (keyword: string): Promise<{ id?: number; displayName?: string }> => { + const text = String(keyword || '').trim() + if (!text) return {} + + const numericId = Number(text) + if (Number.isFinite(numericId) && numericId > 0) { + try { + const info: any = await warehouseApi.getSpaceInfo(numericId) + const direct = info?.data || info + const resolvedId = Number(direct?.id ?? numericId) + return { + id: Number.isFinite(resolvedId) && resolvedId > 0 ? resolvedId : numericId, + displayName: getSpaceDisplayName(direct) + } + } catch (error) { + console.error('按ID获取库位信息失败', error) + } + } + + const res: any = await indexApi.searchSpace({ keyword: text, page: 1, pageSize: 20 }) + const data = res && (res.data || res.list || res) + const list = Array.isArray(data?.list) ? data.list : Array.isArray(data) ? data : [] + if (!list.length) return {} + + const exact = list.find((item: any) => { + const code = String(item?.space_code ?? '').trim() + const customName = String(item?.custom_name ?? item?.customName ?? '').trim() + const name = String(item?.space_name ?? item?.name ?? '').trim() + return code === text || customName === text || name === text + }) || list[0] + + const id = Number(exact?.id) + return { + id: Number.isFinite(id) && id > 0 ? id : undefined, + displayName: getSpaceDisplayName(exact) + } +} + +const submitBatchImportCreate = async () => { + const receivingId = Number(props.id ?? props.row?.id) + if (!Number.isFinite(receivingId) || receivingId <= 0) { + ElMessage.warning('缺少有效的收货单ID,无法导入') + return + } + if (!batchImportPreviewRows.value.length) { + ElMessage.warning('请先选择Excel并生成列表') + return + } + + batchImportLoading.value = true + let successCount = 0 + try { + for (const row of batchImportPreviewRows.value) { + const ok = await importSingleBatchRow(row, receivingId) + if (ok) successCount += 1 + } + + ElMessage.success(`导入完成:成功 ${successCount} 条,共 ${batchImportPreviewRows.value.length} 条`) + if (successCount > 0) { + loadProductData() + } + } finally { + batchImportLoading.value = false + batchImportAddItems.value = batchImportPreviewRows.value.map((r) => ({ + receiving_id: receivingId, + item: { ...(r.item_payload || {}) } + })) + } +} + +const importSingleBatchRow = async (row: any, receivingId: number): Promise => { + const item = { ...(row.item_payload || {}) } + const keyword = String(row.space_keyword || '').trim() + + try { + normalizeQuantityByTotalAndSpec(item) + + const skuId = Number(item.system_product_id) + if (Number.isFinite(skuId) && skuId > 0) { + const product = await querySystemProductById(skuId) + if (product) { + item.product_name = product.item_name || product.product_name || item.product_name + item.barcode = normalizeBarcodeString(product.barcodes, product.barcode) || item.barcode + } + } + + if (!item.space_id) { + if (keyword) { + const resolvedSpace = await resolveSpaceByKeyword(keyword) + if (!resolvedSpace.id) { + row.import_status = '失败' + row.import_message = `库位未匹配: ${keyword}` + return false + } + item.space_id = resolvedSpace.id + if (resolvedSpace.displayName) { + row.space_keyword = resolvedSpace.displayName + } + } else { + item.space_id = 1 + } + } + + row.item_payload = item + + const payload = { receiving_id: receivingId, item } + const res: any = await receivingApi.addDetail(payload) + if (res && (res.code === 200 || res.flag === 'success')) { + row.import_status = '成功' + row.import_message = res?.message || '创建成功' + return true + } + + row.import_status = '失败' + row.import_message = res?.message || '创建失败' + return false + } catch (error: any) { + row.import_status = '失败' + row.import_message = error?.message || '创建失败' + return false + } +} + +const retryFailedBatchRows = async () => { + const receivingId = Number(props.id ?? props.row?.id) + if (!Number.isFinite(receivingId) || receivingId <= 0) { + ElMessage.warning('缺少有效的收货单ID,无法重试') + return + } + const failedRows = batchImportPreviewRows.value.filter((r) => r.import_status === '失败') + if (!failedRows.length) { + ElMessage.warning('当前没有失败行可重试') + return + } + + batchRetryFailedLoading.value = true + let successCount = 0 + try { + for (const row of failedRows) { + const ok = await importSingleBatchRow(row, receivingId) + if (ok) successCount += 1 + } + ElMessage.success(`重试完成:成功 ${successCount} 条,共 ${failedRows.length} 条`) + if (successCount > 0) { + loadProductData() + } + } finally { + batchRetryFailedLoading.value = false + } +} + +const retryBatchImportRow = async (row: any) => { + const receivingId = Number(props.id ?? props.row?.id) + if (!Number.isFinite(receivingId) || receivingId <= 0) { + ElMessage.warning('缺少有效的收货单ID,无法重试') + return + } + const ok = await importSingleBatchRow(row, receivingId) + if (ok) { + ElMessage.success(`第 ${row.row_no} 行重试成功`) + loadProductData() + } +} + +const openSystemProductPicker = async () => { + systemProductPickerVisible.value = true + systemProductSelection.value = [] + await querySystemProducts(1) +} + +const openSpacePicker = async () => { + spacePickerVisible.value = true + spaceSelection.value = [] + await querySpaces(1) +} + +const handleSpaceSelectionChange = (val: any[]) => { + spaceSelection.value = val +} + +const handleSpaceRowClick = (row: any) => { + spaceSelection.value = [row] +} + +const onSpacePageSizeChange = (size: number) => { + spacePagination.pageSize = size + querySpaces(1) +} + +const querySpaces = async (page = 1) => { + spaceLoading.value = true + try { + const keyword = String(spaceKeyword.value || '').trim() + const res: any = await indexApi.searchSpace({ keyword, page, pageSize: spacePagination.pageSize }) + const data = res && (res.data || res.list || res) + const list = Array.isArray(data?.list) ? data.list : Array.isArray(data) ? data : [] + + spaceResults.value = list.map((item: any) => ({ + ...item, + display_name: getSpaceDisplayName(item), + space_name: item.space_name || item.name || item.space_code || '' + })) + spacePagination.total = data?.pagination?.total || data?.total || spaceResults.value.length + spacePagination.page = page + } catch (error) { + console.error('查询库位失败', error) + ElMessage.error('查询库位失败') + spaceResults.value = [] + spacePagination.total = 0 + } finally { + spaceLoading.value = false + } +} + +const applySelectedSpace = () => { + if (spaceSelection.value.length !== 1) { + ElMessage.warning('请选择一个库位') + return + } + + const picked = spaceSelection.value[0] + + if (batchImportPickerMode.value === 'space' && batchImportEditingRow.value) { + const row = batchImportEditingRow.value + const display = getSpaceDisplayName(picked) || picked?.space_code || '' + row.space_keyword = display + row.import_status = '待导入' + row.import_message = '' + row.item_payload = { + ...(row.item_payload || {}), + space_id: Number(picked?.id) || 1 + } + batchImportPickerMode.value = '' + batchImportEditingRow.value = null + spacePickerVisible.value = false + return + } + + editForm.space_id = picked?.id ?? '' + editForm.space_display_name = getSpaceDisplayName(picked) + spacePickerVisible.value = false +} + +const handleSystemProductSelectionChange = (val: any[]) => { + systemProductSelection.value = val +} + +const handleSystemProductRowClick = (row: any) => { + systemProductSelection.value = [row] +} + +const onSystemProductPageSizeChange = (size: number) => { + systemProductPagination.pageSize = size + querySystemProducts(1) +} + +const querySystemProducts = async (page = 1) => { + systemProductLoading.value = true + try { + const paginationParam = { page, pageSize: systemProductPagination.pageSize } + const params: any = {} + + if (boundStoreId.value) { + params.store_id = boundStoreId.value + } + + const keyword = String(systemProductKeyword.value || '').trim() + if (keyword) { + if (/^\d{6,}$/.test(keyword)) { + params.barcodes = { operator: 'like', value: keyword } + } else { + params.item_name = { operator: 'like', value: keyword } + } + } + + const where = buildStockQuery(params) + const res: any = await stockApi.stockWarehouse(paginationParam, where) + + if (res && res.data) { + systemProductResults.value = res.data.list || [] + systemProductPagination.total = res.data.pagination?.total || res.data.total || systemProductResults.value.length + systemProductPagination.page = page + } else { + systemProductResults.value = [] + systemProductPagination.total = 0 + systemProductPagination.page = page + } + } catch (error) { + console.error('查询系统商品失败', error) + ElMessage.error('查询系统商品失败') + systemProductResults.value = [] + systemProductPagination.total = 0 + } finally { + systemProductLoading.value = false + } +} + +const applySelectedSystemProduct = () => { + if (systemProductSelection.value.length !== 1) { + ElMessage.warning('请选择一条系统商品记录') + return + } + + const picked = systemProductSelection.value[0] || {} + + if (batchImportPickerMode.value === 'sku' && batchImportEditingRow.value) { + const row = batchImportEditingRow.value + row.system_product_id = picked.id ?? row.system_product_id + row.barcode = normalizeBarcodeString(picked.barcodes, picked.barcode) || row.barcode + row.product_name = picked.item_name || picked.product_name || row.product_name + row.import_status = '待导入' + row.import_message = '' + row.item_payload = { + ...(row.item_payload || {}), + system_product_id: picked.id ?? row.item_payload?.system_product_id, + barcode: normalizeBarcodeString(picked.barcodes, picked.barcode) || row.item_payload?.barcode, + product_name: picked.item_name || picked.product_name || row.item_payload?.product_name, + weight: picked.weight ?? picked.gross_weight ?? row.item_payload?.weight, + box_length: picked.box_length ?? picked.length ?? row.item_payload?.box_length, + box_width: picked.box_width ?? picked.width ?? row.item_payload?.box_width, + box_height: picked.box_height ?? picked.height ?? row.item_payload?.box_height, + box_weight: picked.box_weight ?? picked.gross_weight ?? row.item_payload?.box_weight, + boxes_per_pallet: picked.boxes_per_pallet ?? row.item_payload?.boxes_per_pallet + } + batchImportPickerMode.value = '' + batchImportEditingRow.value = null + systemProductPickerVisible.value = false + return + } + + editForm.system_product_id = picked.id ?? editForm.system_product_id + editForm.barcode = normalizeBarcodeString(picked.barcodes, picked.barcode) || editForm.barcode + editForm.product_name = picked.item_name || picked.product_name || editForm.product_name + editForm.weight = picked.weight ?? picked.gross_weight ?? editForm.weight + editForm.box_length = picked.box_length ?? picked.length ?? editForm.box_length + editForm.box_width = picked.box_width ?? picked.width ?? editForm.box_width + editForm.box_height = picked.box_height ?? picked.height ?? editForm.box_height + editForm.box_weight = picked.box_weight ?? picked.gross_weight ?? editForm.box_weight + editForm.boxes_per_pallet = picked.boxes_per_pallet ?? editForm.boxes_per_pallet + editForm.is_shelf_life_mgmt = + picked.is_shelf_life_mgmt ?? + picked.is_shelf_life_manage ?? + picked.is_validity_mgmt ?? + editForm.is_shelf_life_mgmt + editForm.shelf_life_days = + picked.shelf_life_days ?? + editForm.shelf_life_days + editForm.is_batch_mgmt = + picked.is_batch_mgmt ?? + picked.is_batch_manage ?? + editForm.is_batch_mgmt + editForm.inbound_min_days = + picked.inbound_min_days ?? + editForm.inbound_min_days + handleQuantityLinkage('boxes_per_pallet') + + if (String(editForm.production_date ?? '').trim() && !String(editForm.expiry_date ?? '').trim()) { + onEditProductionDateChange() + } else if (String(editForm.expiry_date ?? '').trim() && !String(editForm.production_date ?? '').trim()) { + onEditExpiryDateChange() + } else { + validateInboundMinDaysConstraint(false) + } + + systemProductPickerVisible.value = false + ElMessage.success('已使用系统商品属性回填表单') +} + +const parseNumberIfValid = (val: any) => { + if (val === null || val === undefined) return undefined + const text = String(val).trim() + if (!text) return undefined + const num = Number(text) + return Number.isFinite(num) ? num : undefined +} + +const stringIfNonEmpty = (val: any) => { + if (val === null || val === undefined) return undefined + const text = String(val).trim() + return text ? text : undefined +} + +const validateRequiredQuantityFields = () => { + const requiredFields: Array<{ key: keyof typeof editForm; label: string }> = [ + { key: 'actual_quantity', label: '实际收货数量' }, + { key: 'box_quantity', label: '箱数' }, + { key: 'boxes_per_pallet', label: '箱规' }, + { key: 'box_remainder', label: '剩余不满一箱' } + ] + + for (const field of requiredFields) { + const text = String(editForm[field.key] ?? '').trim() + if (!text) { + ElMessage.warning(`请填写${field.label}`) + return false + } + } + + const total = parseNumberIfValid(editForm.actual_quantity) + const boxCount = parseNumberIfValid(editForm.box_quantity) + const boxSpec = parseNumberIfValid(editForm.boxes_per_pallet) + const remainder = parseNumberIfValid(editForm.box_remainder) + + if ( + total === undefined || + boxCount === undefined || + boxSpec === undefined || + remainder === undefined + ) { + ElMessage.warning('数量字段必须为有效数字') + return false + } + + if (boxSpec <= 0) { + ElMessage.warning('箱规必须大于 0') + return false + } + + if (remainder >= boxSpec) { + ElMessage.warning('剩余不满一箱数量必须小于箱规') + return false + } + + const expectedTotal = boxCount * boxSpec + remainder + if (expectedTotal !== total) { + ElMessage.warning('数量关系不正确,请确保:实际收货数量 = 箱数 × 箱规 + 剩余不满一箱') + return false + } + + return true +} + +const validateSkuDependentFields = () => { + if (hasSkuSelected.value) { + return true + } + + const barcode = String(editForm.barcode ?? '').trim() + const productName = String(editForm.product_name ?? '').trim() + + if (!barcode) { + ElMessage.warning('未选择 SKU 时,条码为必填') + return false + } + + if (!productName) { + ElMessage.warning('未选择 SKU 时,商品名称为必填') + return false + } + + return true +} + +const validateManagementDependentFields = () => { + if (!hasSkuSelected.value) { + return true + } + + if (isBatchManaged.value) { + const batchNumber = String(editForm.batch_number ?? '').trim() + if (!batchNumber) { + ElMessage.warning('该商品开启批次管理,批次号为必填') + return false + } + } + + if (isShelfLifeManaged.value) { + const productionDate = String(editForm.production_date ?? '').trim() + const expiryDate = String(editForm.expiry_date ?? '').trim() + if (!productionDate) { + ElMessage.warning('该商品开启效期管理,生产日期为必填') + return false + } + if (!expiryDate) { + ElMessage.warning('该商品开启效期管理,到期日期为必填') + return false + } + } + + return true +} + +const submitEditDetail = async () => { + if (!validateSkuDependentFields()) { + return + } + + if (!validateManagementDependentFields()) { + return + } + + if (!validateInboundMinDaysConstraint(true)) { + return + } + + if (!validateRequiredQuantityFields()) { + return + } + + const receivingId = Number( + editingDetailRow.value?.receiving_id ?? props.id ?? props.row?.id + ) + if (!Number.isFinite(receivingId) || receivingId <= 0) { + ElMessage.warning('缺少有效的收货单ID') + return + } + + const detailId = Number(editingDetailRow.value?.id) + if (editDialogMode.value === 'edit' && (!Number.isFinite(detailId) || detailId <= 0)) { + ElMessage.warning('缺少有效的收货明细ID') + return + } + + if (editForm.expiry_date) { + const expiryTime = new Date(editForm.expiry_date).getTime() + if (Number.isFinite(expiryTime)) { + const today = new Date() + today.setHours(0, 0, 0, 0) + if (expiryTime < today.getTime()) { + ElMessage.warning('到期日期不能早于当前日期') + return + } + } + } + + const itemPayload: any = {} + + const numberFields = [ + 'actual_quantity', + 'box_quantity', + 'boxes_per_pallet', + 'pallet_quantity', + 'space_id', + 'system_product_id', + 'box_width', + 'box_height', + 'box_length', + 'box_remainder', + 'box_weight', + 'weight' + ] + numberFields.forEach((field) => { + const parsed = parseNumberIfValid(editForm[field]) + if (parsed !== undefined) itemPayload[field] = parsed + }) + + const stringFields = ['batch_number', 'production_date', 'expiry_date', 'remark', 'barcode', 'product_name'] + stringFields.forEach((field) => { + const parsed = stringIfNonEmpty(editForm[field]) + if (parsed !== undefined) itemPayload[field] = parsed + }) + + const payload: any = + editDialogMode.value === 'add' + ? { + receiving_id: receivingId, + item: itemPayload + } + : { + id: detailId, + receiving_id: receivingId, + ...itemPayload + } + + editSaving.value = true + try { + const res: any = + editDialogMode.value === 'add' + ? await receivingApi.addDetail(payload) + : await receivingApi.detailChange(payload) + if (res && (res.code === 200 || res.flag === 'success')) { + ElMessage.success(res?.message || (editDialogMode.value === 'add' ? '新增明细成功' : '明细更新成功')) + editDialogVisible.value = false + resetEditForm() + loadProductData() + } else { + ElMessage.error(res?.message || (editDialogMode.value === 'add' ? '新增明细失败' : '明细更新失败')) + } + } catch (error) { + console.error(editDialogMode.value === 'add' ? '新增收货明细失败' : '更新收货明细失败', error) + ElMessage.error(editDialogMode.value === 'add' ? '新增收货明细失败' : '更新收货明细失败') + } finally { + editSaving.value = false + } +} + const windowStyle = computed(() => { if (isFullscreen.value) return {} return { @@ -505,17 +1971,16 @@ const windowStyle = computed(() => { } }) -const quickLinkStyle = computed(() => { - if (isQuickFullscreen.value) return {} - return { - top: `${quickPosition.value.y}px`, - left: `${quickPosition.value.x}px` +const openAddDrawer = (row?: any) => { + if (isRowReadOnly(row)) { + showReadOnlyTip() + return } -}) - -const openAddDrawer = () => { // row here is product row, but store info comes from parent receiving row (props.row) addDrawerStore.value = props.row?.store || { id: props.row?.store_id, name: props.row?.store_name } + if (row) { + multipleSelection.value = [row] + } addDrawerVisible.value = true // allow child to initialize with store after mount setTimeout(() => { @@ -558,7 +2023,19 @@ const openAddDrawer = () => { }, 100) } +const handleDateCellClick = (row: any) => { + if (isRowReadOnly(row)) { + showReadOnlyTip() + return + } + openDateDialog(row) +} + const openDateDialog = (row: any) => { + if (isRowReadOnly(row)) { + showReadOnlyTip() + return + } editingDateRow.value = row dateForm.production_date = row?.production_date || '' dateForm.expiry_date = row?.expiry_date || '' @@ -629,6 +2106,10 @@ const handleSelectionChange = (val: any[]) => { } const handleContextMenu = (row: any, column: any, event: MouseEvent) => { + if (isRowReadOnly(row)) { + event.preventDefault() + return + } event.preventDefault() currentRow.value = row menuTop.value = event.clientY @@ -655,133 +2136,10 @@ const handleProductDetail = () => { closeMenu() } -// 快速关联逻辑 -const handleQuickLink = (row: any) => { - currentRow.value = row - quickLinkVisible.value = true - // 将快速关联窗口居中显示 - isQuickFullscreen.value = false - const winW = 1250 - const winH = 700 - const qx = Math.max(0, Math.floor((window.innerWidth - winW) / 2)) - const qy = Math.max(0, Math.floor((window.innerHeight - winH) / 2)) - quickPosition.value = { x: qx, y: qy } - quickSearchQuery.value = row.product_name || row.item_name || '' - multipleQuickSelection.value = [] - selectedSystemProduct.value = null - // 优先使用商品行中可能包含的收货单货主(例如 row.receiving.store), - // 否则使用父组件传入的收货单(props.row)信息作为回退 - const storeFromDetail = row?.receiving?.store || row?.store || (row && (row.store_id || row.store_name) ? { id: row.store_id, name: row.store_name } : null) - const storeFromParent = props.row?.store || (props.row && (props.row.store_id || props.row.store_name) ? { id: props.row.store_id, name: props.row.store_name } : null) - quickLinkStore.value = storeFromDetail || storeFromParent || null - // 打开弹窗后立即搜索一次(如果有关键字或货主) - performQuickSearch(1) -} - -const handleQuickSelectionChange = (val: any[]) => { - multipleQuickSelection.value = val - if (val.length === 1) { - selectedSystemProduct.value = val[0] - } else { - selectedSystemProduct.value = null - } -} - -const handleQuickRowClick = (row: any) => { - // 点击行时切换选中状态,这里如果是单选逻辑,可以清空其他再选中当前 - // 或者直接赋值给 multipleQuickSelection 模拟单选 - multipleQuickSelection.value = [row] - selectedSystemProduct.value = row -} - -const onSystemProductChange = (row: any) => { - selectedSystemProduct.value = row -} - const tableRowClassName = (row: any) => { return 'clickable-row' } -const onQuickPageSizeChange = (size: number) => { - quickResultPagination.pageSize = size - performQuickSearch(1) -} - -const performQuickSearch = async (page = 1) => { - quickSearchLoading.value = true - try { - const paginationParam = { page, pageSize: quickResultPagination.pageSize } - // 构造符合后端期望的 where,对关键字智能判断使用条码或名称模糊匹配 - const params: any = {} - if (quickLinkStore.value && (quickLinkStore.value.id || quickLinkStore.value.store_id)) { - params.store_id = quickLinkStore.value.id || quickLinkStore.value.store_id - } - if (quickSearchQuery.value) { - const q = String(quickSearchQuery.value).trim() - // 如果看起来像条码(全数字且长度>=6),优先按条码搜索,否则按名称模糊搜索 - if (/^\d{6,}$/.test(q)) { - params.barcodes = { operator: 'like', value: q } - } else { - params.item_name = { operator: 'like', value: q } - } - } - const where = buildStockQuery(params) - const res: any = await stockApi.stockWarehouse(paginationParam, where) - if (res && res.data) { - quickSearchResults.value = res.data.list || [] - quickResultPagination.total = res.data.pagination?.total || res.data.total || quickSearchResults.value.length - quickResultPagination.page = page - } else { - quickSearchResults.value = [] - quickResultPagination.total = 0 - } - } catch (e) { - console.error('快速关联搜索失败', e) - ElMessage.error('搜索失败') - quickSearchResults.value = [] - quickResultPagination.total = 0 - } finally { - quickSearchLoading.value = false - } -} - -const confirmQuickLink = async () => { - if (!selectedSystemProduct.value) { - ElMessage.warning('请先选择一个系统商品') - return - } - - const detailId = currentRow.value?.id - const systemProductId = selectedSystemProduct.value?.id - - if (!detailId || !systemProductId) { - ElMessage.warning('缺少关联必要信息') - return - } - - saveLoading.value = true - try { - const res: any = await receivingApi.bindDetailProduct({ - detail_id: detailId, - system_product_id: systemProductId - }) - - if (res && (res.code === 200 || res.flag === 'success')) { - ElMessage.success(res.message || '关联成功') - quickLinkVisible.value = false - // 触发刷新列表 - loadProductData() - } else { - ElMessage.error(res?.message || '关联失败') - } - } catch (e) { - console.error('confirmQuickLink error:', e) - ElMessage.error('关联过程中出错') - } finally { - saveLoading.value = false - } -} - const toggleFullscreen = () => { isFullscreen.value = !isFullscreen.value } @@ -812,32 +2170,6 @@ const stopDrag = () => { window.removeEventListener('mouseup', stopDrag) } -// 快速关联弹窗拖拽 -const startQuickDrag = (e: MouseEvent) => { - if (isQuickFullscreen.value) return - isQuickDragging.value = true - quickDragOffset.value = { - x: e.clientX - quickPosition.value.x, - y: e.clientY - quickPosition.value.y - } - window.addEventListener('mousemove', onQuickDrag) - window.addEventListener('mouseup', stopQuickDrag) -} - -const onQuickDrag = (e: MouseEvent) => { - if (!isQuickDragging.value) return - quickPosition.value = { - x: Math.max(0, e.clientX - quickDragOffset.value.x), - y: Math.max(0, e.clientY - quickDragOffset.value.y) - } -} - -const stopQuickDrag = () => { - isQuickDragging.value = false - window.removeEventListener('mousemove', onQuickDrag) - window.removeEventListener('mouseup', stopQuickDrag) -} - const resetForm = () => { if (activeWindowTab.value === 'basic' && basicRef.value) { basicRef.value.reset?.() @@ -859,19 +2191,6 @@ const saveProductDetail = async () => { } } -const handleSave = async () => { - try { - saveLoading.value = true - // 模拟保存逻辑 - await new Promise(resolve => setTimeout(resolve, 500)) - ElMessage.success('保存成功') - } catch (error) { - ElMessage.error('保存失败') - } finally { - saveLoading.value = false - } -} - onMounted(() => { if (props.productData && props.productData.length > 0) { tableData.value = [...props.productData] @@ -907,6 +2226,62 @@ onUnmounted(() => { margin: 0 8px; } +.required-mark { + color: #f56c6c; + margin-left: 4px; +} + +.readonly-op { + color: #909399; +} + +.clickable-date-cell.is-readonly { + color: #909399; + cursor: not-allowed; +} + +.system-product-picker { + display: flex; + flex-direction: column; + gap: 10px; +} + +.picker-toolbar { + display: flex; + align-items: center; + gap: 12px; + flex-wrap: wrap; +} + +.batch-import-toolbar { + display: flex; + align-items: center; + gap: 10px; + flex-wrap: wrap; + margin-bottom: 10px; +} + +.batch-import-summary { + margin-top: 10px; + color: #606266; + font-size: 12px; +} + +.batch-cell-action { + display: flex; + align-items: center; + gap: 6px; +} + +.picker-hint { + color: #606266; + font-size: 12px; +} + +.picker-table-wrap { + height: 440px; +} + .product-window { position: fixed; z-index: 2000; @@ -929,21 +2304,6 @@ onUnmounted(() => { z-index: 3000; } -/* 遮罩层:阻止快速关联弹窗打开时对下层页面的交互 */ -.modal-backdrop { - position: fixed; - top: 0; - left: 0; - width: 100vw; - height: 100vh; - background: rgba(0,0,0,0.18); - z-index: 2400; -} - -/* 确保快速关联弹窗高于遮罩层 */ -.product-window.quick-link-window { - z-index: 2500; -} .window-header { padding: 8px 12px; @@ -1031,13 +2391,6 @@ onUnmounted(() => { gap: 12px; } -.quick-link-content { - padding: 20px; - flex: 1; - display: flex; - flex-direction: column; -} - .search-section { margin-bottom: 20px; } diff --git a/src/views/storage/receiving/index.vue b/src/views/storage/receiving/index.vue index 4c12c1d3..00fc7aef 100644 --- a/src/views/storage/receiving/index.vue +++ b/src/views/storage/receiving/index.vue @@ -9,7 +9,7 @@
刷新 - + 添加收货单 - {{ policyDialog.contractRow?.id }} - - - {{ policyDialog.contractRow?.current_subject_role === 'warehouse' ? '仓库方' : '货主方' }} - - {{ policyDialog.contractRow?.store_name }} - {{ policyDialog.contractRow?.warehouse_name }} + {{ policyDialog.contractRow?.print_quantity ?? '—' }} diff --git a/仓库商品导出_20260517 (3).xlsx b/仓库商品导出_20260517 (3).xlsx new file mode 100644 index 00000000..a856003f Binary files /dev/null and b/仓库商品导出_20260517 (3).xlsx differ