5703 lines
195 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use strict';
const crypto = require('node:crypto');
const fs = require('node:fs');
const fsp = require('node:fs/promises');
const os = require('node:os');
const path = require('node:path');
const ExcelJS = require('exceljs');
const Service = require('egg').Service;
const { parseWhereConditions } = require('../../../lib/query_condition_parser');
const DAY_MS = 24 * 60 * 60 * 1000;
const RECEIVING_EXPORT_PAGE_SIZE = 200;
const RECEIVING_ITEMS_FETCH_BATCH_SIZE = 100;
function getStartOfDayMs(value) {
const date = new Date(value);
if (Number.isNaN(date.getTime())) return null;
date.setHours(0, 0, 0, 0);
return date.getTime();
}
/**
* 判断到期日期是否早于当前日期。
* @param {string|Date|number} expiryDate 到期日期
* @param {Date} [currentDate=new Date()] 当前日期
* @return {boolean} 是否已过期
*/
function isExpiryDateBeforeToday(expiryDate, currentDate = new Date()) {
const expiryStartMs = getStartOfDayMs(expiryDate);
if (expiryStartMs === null) return false;
const currentStartMs = getStartOfDayMs(currentDate);
if (currentStartMs === null) return false;
return expiryStartMs < currentStartMs;
}
class ReceivingService extends Service {
/**
* 查询收货单列表。
* @param {Object} where 动态筛选条件
* @param {Object} [pageParams] 分页参数
* @param {number} [pageParams.page=1] 页码
* @param {number} [pageParams.pageSize=20] 每页条数
* @param {Object} [sortParams] 排序参数
* @param {Object} [options] 额外选项
* @param {boolean} [options.filterDepleted=false] 是否过滤掉无可再用量的收货单
* @param {number} [options.entry_order_id] 可选,按入库单商品交集过滤:只返回"至少有一条明细的 system_product_id 在入库单明细中"的收货单
* @param {string|string[]} [options.stock_query_where] 可选,按商品维度过滤:搜索条码/商品编码/商品ID,返回明细中含匹配商品的收货单(支持字符串或字符串数组,多个关键字取并集)
* @return {Promise<Object>} 列表、分页与汇总信息
*/
async getReceivingList(where, pageParams = {}, sortParams = {}, options = {}) {
const {
ctx,
app,
} = this;
const {
Sequelize,
} = app;
const {
Op,
} = Sequelize;
const {
page = 1,
pageSize = 20,
} = pageParams;
try {
const {
sortField = 'id',
sortOrder = 'DESC',
} = sortParams;
const { filterDepleted = false, entry_order_id: entryOrderId, stock_query_where: stockQueryWhere } = options;
const queryOptions = {
where: {
[Op.and]: [
{
warehouse_id: ctx.user.store_id,
},
],
},
order: [],
attributes: {
exclude: [ 'deleted_at' ],
},
};
const normalizedWhere = ctx.where && typeof ctx.where === 'object'
? ctx.where
: (where && typeof where === 'object' ? where : {});
let parsedResult = ctx.whereParsed;
if (!parsedResult || !Array.isArray(parsedResult.dynamicConditions)) {
const parsed = parseWhereConditions({
where: normalizedWhere,
app,
specialFieldMap: {
quickWhere: {
bucket: 'quick',
},
},
});
if (!parsed.ok) {
return {
code: 400,
data: {
list: [],
pagination: {
page: parseInt(page),
pageSize: parseInt(pageSize),
total: 0,
totalPages: 0,
hasPrevious: false,
hasNext: false,
},
summary: {
total_quantity: 0,
total_locked: 0,
total_available: 0,
total_items: 0,
},
},
message: `筛选条件解析失败: ${parsed.reason}`,
};
}
parsedResult = parsed.result;
}
const dynamicConditions = [ ...(parsedResult.dynamicConditions || []) ];
const quickWhereRaw = (parsedResult.rawConditionsByField && parsedResult.rawConditionsByField.quickWhere)
|| normalizedWhere.quickWhere;
if (quickWhereRaw && !this.isEmptyValue(quickWhereRaw.value)) {
const quickValue = String(quickWhereRaw.value).trim();
dynamicConditions.push({
[Op.or]: {
store_name: {
[Sequelize.Op.like]: `%${quickValue}%`,
},
receiving_number: {
[Sequelize.Op.like]: `%${quickValue}%`,
},
tracking_number: {
[Sequelize.Op.like]: `%${quickValue}%`,
},
creator_snapshot: {
[Sequelize.Op.like]: `%${quickValue}%`,
},
license_plate: {
[Sequelize.Op.like]: `%${quickValue}%`,
},
},
});
}
if (dynamicConditions.length > 0) {
queryOptions.where[Op.and].push({
[Op.and]: dynamicConditions,
});
}
const validSortFields = [
'id', 'receiving_number', 'status', 'create_at', 'update_at', 'store_id',
];
const actualSortField = validSortFields.includes(sortField) ? sortField : 'create_at';
const actualSortOrder = sortOrder.toUpperCase() === 'ASC' ? 'ASC' : 'DESC';
queryOptions.order.push([ actualSortField, actualSortOrder ]);
const offset = (page - 1) * pageSize;
const include = [
{
model: ctx.model.StoreWarehouse,
as: 'store',
attributes: [ 'store_remask' ],
where: {
warehouse_use_status: 1,
warehouse_id: ctx.user.store_id,
},
required: false,
},
{
model: ctx.model.AccountStoreEmployee,
as: 'creator',
attributes: [ 'real_name' ],
required: true,
},
];
// 可选过滤:排除无可再用量的收货单
let filteredReceivingIds = null;
if (filterDepleted) {
const candidateRows = await ctx.model.Receiving.findAll({
attributes: [ 'id' ],
where: queryOptions.where,
include,
distinct: true,
raw: true,
});
const candidateIds = candidateRows.map(r => r.id);
if (candidateIds.length > 0) {
// 1. 候选收货单明细的 actual_quantity 总和(按 receiving_id 分组)
const detailSums = await ctx.model.ReceivingDetail.findAll({
attributes: [
'receiving_id',
[ Sequelize.fn('SUM', Sequelize.col('actual_quantity')), 'total_actual' ],
],
where: { receiving_id: { [Op.in]: candidateIds } },
group: [ 'receiving_id' ],
raw: true,
});
const totalActualMap = {};
for (const row of detailSums) {
totalActualMap[row.receiving_id] = Number(row.total_actual) || 0;
}
// 2. 这些明细对应的 committed 绑定量(按 receiving_detail_id 分组)
const detailIds = detailSums.length > 0
? (await ctx.model.ReceivingDetail.findAll({
attributes: [ 'id' ],
where: { receiving_id: { [Op.in]: candidateIds } },
raw: true,
})).map(r => r.id)
: [];
const committedByDetailId = {};
if (detailIds.length > 0) {
const bindingRows = await ctx.model.InboundDirectLog.findAll({
attributes: [
'receiving_detail_id',
[ Sequelize.fn('SUM', Sequelize.col('quantity')), 'committed_sum' ],
],
where: {
receiving_detail_id: { [Op.in]: detailIds },
status: 'committed',
},
group: [ 'receiving_detail_id' ],
raw: true,
});
for (const row of bindingRows) {
committedByDetailId[row.receiving_detail_id] = Number(row.committed_sum) || 0;
}
}
// 3. 计算每个收货单的剩余可用量 = SUM(actual_quantity) - SUM(committed)
const idToDetailIdsMap = {};
if (detailIds.length > 0) {
const detailIdRows = await ctx.model.ReceivingDetail.findAll({
attributes: [ 'id', 'receiving_id' ],
where: { id: { [Op.in]: detailIds } },
raw: true,
});
for (const d of detailIdRows) {
if (!idToDetailIdsMap[d.receiving_id]) idToDetailIdsMap[d.receiving_id] = [];
idToDetailIdsMap[d.receiving_id].push(d.id);
}
}
const remainingByReceivingId = {};
for (const receivingId of candidateIds) {
const totalActual = totalActualMap[receivingId] || 0;
const detailIdList = idToDetailIdsMap[receivingId] || [];
const totalCommitted = detailIdList.reduce((sum, did) => sum + (committedByDetailId[did] || 0), 0);
remainingByReceivingId[receivingId] = totalActual - totalCommitted;
}
// 过滤:只保留剩余可用量 > 0 的收货单
filteredReceivingIds = candidateIds.filter(id => remainingByReceivingId[id] > 0);
} else {
filteredReceivingIds = [];
}
}
// 可选过滤:按入库单商品交集过滤(只返回 system_product_id 有交集的收货单)
let intersectionFilteredIds = null;
if (entryOrderId) {
// 1. 查该入库单的所有 entry_items → stock_id 集合
const entryItemRows = await ctx.model.EntryItems.findAll({
where: { order_id: entryOrderId },
attributes: [ 'stock_id' ],
raw: true,
});
const entrySpIdSet = new Set(entryItemRows.map(r => r.stock_id).filter(Boolean));
if (entrySpIdSet.size === 0) {
// 入库单无明细 → 不返回任何收货单
intersectionFilteredIds = [];
} else {
// 2. 查所有收货单明细,找出 system_product_id 在 entrySpIdSet 中的收货单 ID
const matchingDetailRows = await ctx.model.ReceivingDetail.findAll({
attributes: [ 'receiving_id' ],
where: {
system_product_id: { [Op.in]: [ ...entrySpIdSet ] },
},
group: [ 'receiving_id' ],
raw: true,
});
intersectionFilteredIds = matchingDetailRows.map(r => r.receiving_id);
}
}
// 可选过滤:按 stock_query_where(商品条码/编码/ID)过滤,支持字符串或字符串数组
let stockQueryFilteredIds = null;
const stockQueryKeywords = Array.isArray(stockQueryWhere)
? stockQueryWhere.map(v => String(v).trim()).filter(Boolean)
: (typeof stockQueryWhere === 'string' && stockQueryWhere.trim() !== '' ? [ stockQueryWhere.trim() ] : []);
if (stockQueryKeywords.length > 0) {
stockQueryFilteredIds = await this._resolveStockQueryReceivingIds(stockQueryKeywords);
}
// 合并 filterDepleted / entry_order_id / stock_query_where 的过滤结果(多组启用时取交集)
let combinedFilteredIds = null;
const idFilterSets = [ filteredReceivingIds, intersectionFilteredIds, stockQueryFilteredIds ]
.filter(arr => arr !== null)
.map(arr => new Set(arr));
if (idFilterSets.length > 0) {
const [ first, ...rest ] = idFilterSets;
combinedFilteredIds = [ ...first ].filter(id => rest.every(set => set.has(id)));
}
// 如果启用了过滤,用过滤后的 ID 做最终查询
const finalWhere = combinedFilteredIds !== null
? { id: { [Op.in]: combinedFilteredIds } }
: queryOptions.where;
const [ total, data ] = await Promise.all([
ctx.model.Receiving.count({
where: finalWhere,
include,
distinct: true,
}),
ctx.model.Receiving.findAll({
...queryOptions,
where: finalWhere,
include,
limit: parseInt(pageSize),
offset: parseInt(offset),
distinct: true,
raw: true,
}),
]);
const totalPages = Math.ceil(total / pageSize);
const hasPrevious = page > 1;
const hasNext = page < totalPages;
const stockIds = data.map(item => item.id);
let images = [];
if (stockIds.length > 0) {
images = await ctx.model.FileReference.findAll({
where: {
business_type: 'receiving',
business_id: {
[Op.in]: stockIds,
},
},
include: [
{
model: ctx.model.File,
as: 'file',
attributes: [ 'file_url' ],
required: true,
},
],
});
}
const processedData = data.map(item => {
// 注意:wms_receiving 表中没有 locked_quantity 字段,total_quantity 为商品总数量
const availableQuantity = Math.max(0, item.total_quantity || 0);
const lockRate = 0;
const itemImages = images
.filter(row => parseInt(row.business_id) === item.id)
.map(row => row.file.file_url);
return {
...item,
images: itemImages,
available_quantity: availableQuantity,
lock_rate: parseFloat(lockRate),
lock_rate_display: `${lockRate}%`,
create_at_display: item.created_at ? this.app.formatDate(item.created_at) : '',
update_at_display: item.updated_at ? this.app.formatDate(item.updated_at) : '',
};
});
const summary = {
total_quantity: data.reduce((sum, item) => sum + (item.total_quantity || 0), 0),
total_locked: 0,
total_available: data.reduce((sum, item) => sum + (item.total_quantity || 0), 0),
total_items: data.length,
};
return {
code: 200,
data: {
list: processedData,
pagination: {
page: parseInt(page),
pageSize: parseInt(pageSize),
total,
totalPages,
hasPrevious,
hasNext,
},
summary,
queryInfo: {
conditions: normalizedWhere,
sortField: actualSortField,
sortOrder: actualSortOrder,
hasBarcodeSearch: stockQueryKeywords.length > 0,
},
},
message: '查询成功',
};
} catch (error) {
ctx.logger.error('[StockService.getWarehouseStock] 查询失败:', error);
return {
code: 500,
data: {
list: [],
pagination: {
page: parseInt(page || 1),
pageSize: parseInt(pageSize || 20),
total: 0,
totalPages: 0,
hasPrevious: false,
hasNext: false,
},
summary: {
total_quantity: 0,
total_locked: 0,
total_available: 0,
total_items: 0,
},
},
message: `查询失败: ${error.message}`,
};
}
}
/**
* 按商品关键字解析收货单 ID 列表。
* 搜索范围:
* 1) wms_stock_warehouse.item_code(商品编码)模糊匹配
* 2) wms_stock_warehouse.id 精确匹配(关键字为纯数字时)
* 3) wms_stock_barcodes.barcode(条码)模糊匹配
* 再通过 wms_receiving_detail.system_product_id 关联回收货单。
* @param {string|string[]} keywords 搜索关键字(字符串或字符串数组,多个关键字取并集)
* @return {Promise<number[]|null>} 收货单 ID 数组;关键字为空返回 null
*/
async _resolveStockQueryReceivingIds(keywords) {
const { ctx, app } = this;
const { Sequelize } = app;
const { Op } = Sequelize;
const keywordList = (Array.isArray(keywords) ? keywords : [ keywords ])
.map(v => String(v).trim())
.filter(Boolean);
if (keywordList.length === 0) return null;
const stockIds = new Set();
// 1. 商品编码 / 商品ID 匹配(wms_stock_warehouse)
const stockWhere = {
[Op.or]: keywordList.map(k => ({ item_code: { [Op.like]: `%${k}%` } })),
};
keywordList.forEach(k => {
if (/^\d+$/.test(k)) {
stockWhere[Op.or].push({ id: Number(k) });
}
});
const stockRows = await ctx.model.StockWarehouse.findAll({
attributes: [ 'id' ],
where: stockWhere,
raw: true,
});
stockRows.forEach(row => stockIds.add(Number(row.id)));
// 2. 条码匹配(wms_stock_barcodes → stock_id)
const barcodeRows = await ctx.model.StockBarcode.findAll({
attributes: [ 'stock_id' ],
where: {
[Op.or]: keywordList.map(k => ({ barcode: { [Op.like]: `%${k}%` } })),
},
raw: true,
});
barcodeRows.forEach(row => stockIds.add(Number(row.stock_id)));
if (stockIds.size === 0) return [];
// 3. 通过明细表关联回收货单
const detailRows = await ctx.model.ReceivingDetail.findAll({
attributes: [ 'receiving_id' ],
where: {
system_product_id: { [Op.in]: [ ...stockIds ] },
},
group: [ 'receiving_id' ],
raw: true,
});
return [ ...new Set(detailRows.map(row => row.receiving_id)) ];
}
/**
* 货主侧收货单列表查询。
* 以 store_id 为维度查询收货单,支持分页、多条件筛选与排序。
* @param {Object} where 动态筛选条件
* @param {number} storeId 货主ID(必填)
* @param {Object} [pageParams] 分页参数
* @param {number} [pageParams.page=1] 页码
* @param {number} [pageParams.pageSize=20] 每页条数
* @param {Object} [sortParams] 排序参数
* @param {string} [sortParams.sortField='created_at'] 排序字段
* @param {string} [sortParams.sortOrder='DESC'] 排序方向
* @param {Object} [options] 额外选项
* @param {string|string[]} [options.stock_query_where] 可选,按商品维度过滤:搜索条码/商品编码/商品ID,返回明细中含匹配商品的收货单(支持字符串或字符串数组,多个关键字取并集)
* @return {Promise<Object>} 列表、分页与汇总信息
*/
async getStoreReceivingList(where, storeId, pageParams = {}, sortParams = {}, options = {}) {
const { ctx, app } = this;
const { Sequelize } = app;
const { Op } = Sequelize;
const { page = 1, pageSize = 20 } = pageParams;
const { sortField = 'created_at', sortOrder = 'DESC' } = sortParams;
const { stock_query_where: stockQueryWhere } = options;
try {
const queryOptions = {
where: {
[Op.and]: [
{ store_id: storeId },
],
},
order: [],
attributes: {
exclude: [ 'deleted_at' ],
},
};
const normalizedWhere = where && typeof where === 'object' ? where : {};
let parsedResult = ctx.whereParsed;
if (!parsedResult || !Array.isArray(parsedResult.dynamicConditions)) {
const parsed = parseWhereConditions({
where: normalizedWhere,
app,
specialFieldMap: {
quickWhere: {
bucket: 'quick',
},
},
});
if (!parsed.ok) {
return {
code: 400,
data: {
list: [],
pagination: { page: Number(page), pageSize: Number(pageSize), total: 0, totalPages: 0, hasPrevious: false, hasNext: false },
summary: { total_quantity: 0, total_locked: 0, total_available: 0, total_items: 0 },
},
message: `筛选条件解析失败: ${parsed.reason}`,
};
}
parsedResult = parsed.result;
}
const dynamicConditions = [ ...(parsedResult.dynamicConditions || []) ];
const quickWhereRaw = (parsedResult.rawConditionsByField && parsedResult.rawConditionsByField.quickWhere)
|| normalizedWhere.quickWhere;
if (quickWhereRaw && quickWhereRaw.value && String(quickWhereRaw.value).trim() !== '') {
const quickValue = String(quickWhereRaw.value).trim();
dynamicConditions.push({
[Op.or]: {
store_name: { [Sequelize.Op.like]: `%${quickValue}%` },
receiving_number: { [Sequelize.Op.like]: `%${quickValue}%` },
tracking_number: { [Sequelize.Op.like]: `%${quickValue}%` },
creator_snapshot: { [Sequelize.Op.like]: `%${quickValue}%` },
license_plate: { [Sequelize.Op.like]: `%${quickValue}%` },
},
});
}
if (dynamicConditions.length > 0) {
queryOptions.where[Op.and].push({ [Op.and]: dynamicConditions });
}
const validSortFields = [ 'id', 'receiving_number', 'status', 'created_at', 'updated_at', 'store_id', 'warehouse_id' ];
const actualSortField = validSortFields.includes(sortField) ? sortField : 'created_at';
const actualSortOrder = sortOrder.toUpperCase() === 'ASC' ? 'ASC' : 'DESC';
queryOptions.order.push([ actualSortField, actualSortOrder ]);
const offset = (page - 1) * pageSize;
// 可选过滤:按 stock_query_where(商品条码/编码/ID)过滤,支持字符串或字符串数组
let stockQueryFilteredIds = null;
const stockQueryKeywords = Array.isArray(stockQueryWhere)
? stockQueryWhere.map(v => String(v).trim()).filter(Boolean)
: (typeof stockQueryWhere === 'string' && stockQueryWhere.trim() !== '' ? [ stockQueryWhere.trim() ] : []);
if (stockQueryKeywords.length > 0) {
stockQueryFilteredIds = await this._resolveStockQueryReceivingIds(stockQueryKeywords);
}
const finalWhere = stockQueryFilteredIds !== null
? { id: { [Op.in]: stockQueryFilteredIds } }
: queryOptions.where;
const [ total, data ] = await Promise.all([
ctx.model.Receiving.count({
where: finalWhere,
distinct: true,
}),
ctx.model.Receiving.findAll({
...queryOptions,
where: finalWhere,
limit: Number(pageSize),
offset: Number(offset),
distinct: true,
raw: true,
}),
]);
const totalPages = Math.ceil(total / pageSize);
const hasPrevious = page > 1;
const hasNext = page < totalPages;
// 获取收货单图片
const stockIds = data.map(item => item.id);
let images = [];
if (stockIds.length > 0) {
images = await ctx.model.FileReference.findAll({
where: {
business_type: 'receiving',
business_id: { [Op.in]: stockIds },
},
include: [
{
model: ctx.model.File,
as: 'file',
attributes: [ 'file_url' ],
required: true,
},
],
});
}
const processedData = data.map(item => {
const availableQuantity = Math.max(0, item.total_quantity || 0);
const itemImages = images
.filter(row => Number(row.business_id) === item.id)
.map(row => row.file.file_url);
// 从 creator_snapshot 解析操作人姓名
let creatorName = '';
try {
if (item.creator_snapshot) {
const snapshot = JSON.parse(item.creator_snapshot);
creatorName = snapshot.name || '';
}
} catch (_) {
// ignore parse error
}
return {
...item,
images: itemImages,
available_quantity: availableQuantity,
lock_rate: 0,
lock_rate_display: '0%',
creator_name: creatorName,
create_at_display: item.created_at ? this.app.formatDate(item.created_at) : '',
update_at_display: item.updated_at ? this.app.formatDate(item.updated_at) : '',
};
});
const summary = {
total_quantity: data.reduce((sum, item) => sum + (item.total_quantity || 0), 0),
total_locked: 0,
total_available: data.reduce((sum, item) => sum + (item.total_quantity || 0), 0),
total_items: data.length,
};
return {
code: 200,
data: {
list: processedData,
pagination: {
page: Number(page),
pageSize: Number(pageSize),
total,
totalPages,
hasPrevious,
hasNext,
},
summary,
queryInfo: {
conditions: normalizedWhere,
sortField: actualSortField,
sortOrder: actualSortOrder,
hasBarcodeSearch: stockQueryKeywords.length > 0,
},
},
message: '查询成功',
};
} catch (error) {
ctx.logger.error('[ReceivingService.getStoreReceivingList] 查询失败:', error);
return {
code: 500,
data: {
list: [],
pagination: { page: Number(page || 1), pageSize: Number(pageSize || 20), total: 0, totalPages: 0, hasPrevious: false, hasNext: false },
summary: { total_quantity: 0, total_locked: 0, total_available: 0, total_items: 0 },
},
message: `查询失败: ${error.message}`,
};
}
}
/**
* 获取收货单详情(主单 + 明细分页 + 图片)。
* @param {Object} data 请求体
* @param {number} data.id 收货单ID
* @param {Object} data.pagination 分页参数
* @return {Promise<Object>} 详情数据,明细中的 space_id 会优先展示自定义库位名称,其次展示库位编码,并补充 space_id_raw 兼容原始ID
*/
async getReceivingDetail(data) {
const { id, pagination } = data;
const { page, pageSize } = pagination;
const { ctx, app } = this;
const { Op } = app.Sequelize;
// 获取用户仓库ID,增加错误处理
const warehouseId = ctx.user?.store_id;
if (!warehouseId) {
return { code: 0, message: '用户未绑定仓库', data: {} };
}
try {
// 1. 查询收货单主表
const receiving = await app.model.Receiving.findOne({ where: { id, warehouse_id: warehouseId } });
if (!receiving) {
return { code: 0, message: '无记录或无权访问', data: {} };
}
// 2. 查询收货单明细,按分页
const receivingItems = await app.model.ReceivingDetail.findAll({
where: { receiving_id: id },
include: [{
model: app.model.LocationSpace,
as: 'receiving_space',
attributes: [ 'id', 'custom_name', 'space_code' ],
required: false,
}],
offset: (page - 1) * pageSize,
limit: pageSize,
});
// 获取明细总数
const totalItems = await app.model.ReceivingDetail.count({ where: { receiving_id: id } });
// 组装分页信息
const detailPagination = {
total: totalItems,
currentPage: page,
pageSize,
totalPages: Math.ceil(totalItems / pageSize),
hasPrevious: page > 1,
hasNext: page < Math.ceil(totalItems / pageSize),
};
// 3. 获取明细ID数组
const receivingItemsIds = receivingItems.map(item => item.id);
// 4. 查询明细图片(如果明细数量大于0)
const itemImagesMap = {}; // 用于存储每个明细的图片
if (receivingItemsIds.length > 0) {
const receivingItemsImages = await ctx.model.FileReference.findAll({
where: {
business_type: 'receivingItem',
business_id: { [Op.in]: receivingItemsIds },
},
include: [{
model: ctx.model.File,
as: 'file',
attributes: [ 'file_url' ],
required: true,
}],
});
// 将图片按明细ID分组,并转换为前端可直接使用的链接
for (const image of receivingItemsImages) {
if (!itemImagesMap[image.business_id]) {
itemImagesMap[image.business_id] = [];
}
itemImagesMap[image.business_id].push({
id: image.file_id,
url: image.file.file_url,
});
}
}
// 5. 将图片合并到对应的明细中
const items = receivingItems.map(item => {
const detail = item.toJSON();
const { receiving_space: receivingSpace, ...detailBase } = detail;
const spaceName = receivingSpace?.custom_name || receivingSpace?.space_code || null;
return {
...detailBase,
space_id_raw: detailBase.space_id ?? null,
space_name: spaceName,
custom_space_name: receivingSpace?.custom_name ?? null,
space_id: spaceName,
box_remainder: detail.box_remainder ?? 0,
box_weight: detail.box_weight ?? 0,
images: itemImagesMap[item.id] || [],
};
});
// 6. 查询主表的图片
const receivingImages = await ctx.model.FileReference.findAll({
where: {
business_type: 'receiving',
business_id: id,
},
include: [{
model: ctx.model.File,
as: 'file',
attributes: [ 'file_url' ],
required: true,
}],
});
// 7. 组装返回数据
receiving.dataValues.details = items; // 包含图片链接的明细数据
receiving.dataValues.images = receivingImages.map(image => ({
id: image.file_id,
url: image.file.file_url,
})); // 包含主表图片链接
receiving.dataValues.pagination = detailPagination; // 包含分页信息
return { code: 200, message: '查询成功', data: { receiving } };
} catch (error) {
console.error('获取收货单详情失败:', error);
return { code: 500, message: '服务器错误', data: {} };
}
}
/**
* 批量作废收货单。
* @param {Object} data 请求体
* @param {number[]} data.ids 收货单ID数组
* @return {Promise<Object>} 作废处理结果
*/
async batchCancelReceiving(data) {
const { ids } = data;
const { ctx } = this;
const { Op } = ctx.model.Sequelize;
const warehouse_id = ctx.user.store_id;
try {
// 先查询这些单据是否都存在且状态允许作废
const receivings = await ctx.model.Receiving.findAll({ where: { id: { [Op.in]: ids }, warehouse_id } });
if (receivings.length !== ids.length) {
return { code: 0, message: '部分单据不存在或无权访问', data: {} };
}
const invalidStatus = receivings.find(r => r.status !== 'receiving');
if (invalidStatus) {
return { code: 0, message: '部分单据状态不允许作废', data: {} };
}
// 批量更新状态为cancelled
await ctx.model.Receiving.update({ status: 'cancelled' }, { where: { id: { [Op.in]: ids }, warehouse_id } });
// 批量记录操作日志
try {
const operationLogService = ctx.service && ctx.service.systems && ctx.service.systems.operationLog;
const payloads = ids.map(receivingId => ({
businessType: 'receiving',
businessId: receivingId,
operationCode: 'RECEIVING_BATCH_CANCEL',
operator: {
id: ctx.user?.employees_id || ctx.user?.id,
name: ctx.user?.employees_name || '',
},
extras: {
warehouseId: warehouse_id,
},
beforeChanges: null,
}));
if (operationLogService && typeof operationLogService.createOperationLogs === 'function') {
await operationLogService.createOperationLogs(payloads);
}
} catch (logErr) {
ctx.logger.warn('[receiving.batchCancelReceiving] 写入操作日志失败,不影响业务', logErr);
}
return { code: 200, message: '批量作废成功', data: {} };
} catch (error) {
console.error('批量作废收货单失败:', error);
return { code: 500, message: '服务器错误', data: {} };
}
}
/**
* 驳回收货单:将已完成收货单恢复为收货中,记录审核人信息与驳回理由。
* @param {Object} data 请求体
* @param {number[]} data.ids 收货单ID数组
* @param {string} [data.remark] 驳回理由(覆盖原备注)
* @return {Promise<Object>} 操作结果
*/
async rejectReceiving(data) {
const { ids, remark } = data;
const { ctx } = this;
const { Op } = ctx.model.Sequelize;
const warehouse_id = ctx.user.store_id;
if (!Array.isArray(ids) || ids.length === 0) {
return { code: 0, message: '收货单ID不能为空', data: {} };
}
const reviewerName = String(ctx.user?.employees_name || '').trim();
const reviewerEmployeeId = ctx.user?.employees_id || null;
try {
const receivings = await ctx.model.Receiving.findAll({
where: { id: { [Op.in]: ids }, warehouse_id },
});
if (receivings.length !== ids.length) {
return { code: 0, message: '部分单据不存在或无权访问', data: {} };
}
const nonCompleted = receivings.find(r => r.status !== 'completed');
if (nonCompleted) {
return { code: 0, message: '只有状态为收货完成的收货单才能驳回', data: {} };
}
const alreadyReviewed = receivings.find(r => Number(r.is_review) === 1);
if (alreadyReviewed) {
return { code: 0, message: '存在已审核的收货单,无法驳回', data: {} };
}
const alreadyStored = receivings.find(r => r.storage_status === 'partial' || r.storage_status === 'all');
if (alreadyStored) {
return { code: 0, message: '存在已入库的收货单,无法驳回', data: {} };
}
const updateData = {
status: 'receiving',
reviewer_name: reviewerName || null,
reviewer_employee_id: reviewerEmployeeId || null,
};
if (remark !== undefined && remark !== null) {
updateData.remark = String(remark).trim() || null;
}
await ctx.model.Receiving.update(updateData, {
where: { id: { [Op.in]: ids }, warehouse_id },
});
try {
const operationLogService = ctx.service && ctx.service.systems && ctx.service.systems.operationLog;
const payloads = ids.map(receivingId => ({
businessType: 'receiving',
businessId: receivingId,
operationCode: 'RECEIVING_REJECT',
operator: {
id: reviewerEmployeeId || ctx.user?.id,
name: reviewerName,
},
extras: {
warehouseId: warehouse_id,
remark: updateData.remark || '',
},
beforeChanges: null,
}));
if (operationLogService && typeof operationLogService.createOperationLogs === 'function') {
await operationLogService.createOperationLogs(payloads);
}
} catch (logErr) {
ctx.logger.warn('[receiving.rejectReceiving] 写入操作日志失败,不影响业务', logErr);
}
// 发送驳回通知
try {
const rawNoticeService = ctx.service && ctx.service.systems && ctx.service.systems.notice;
const noticeService = rawNoticeService && typeof rawNoticeService.send === 'function'
? rawNoticeService
: (rawNoticeService && rawNoticeService.index && typeof rawNoticeService.index.send === 'function'
? rawNoticeService.index
: null);
const receivingSummaries = receivings.map(item => {
let creator = null;
const rawSnapshot = item && item.creator_snapshot;
if (rawSnapshot && typeof rawSnapshot === 'string') {
try {
creator = JSON.parse(rawSnapshot);
} catch (error) {
creator = null;
}
} else if (rawSnapshot && typeof rawSnapshot === 'object') {
creator = rawSnapshot;
}
return {
id: Number(item && item.id),
receiving_number: String(item && item.receiving_number || ''),
creator: creator ? {
id: creator.id || creator.employees_id || null,
employees_id: creator.employees_id || creator.id || null,
name: String(creator.name || creator.real_name || '').trim() || null,
} : null,
};
});
if (noticeService) {
await Promise.all(receivingSummaries.map(item => noticeService.send({
warehouseId: warehouse_id,
messageType: 'text',
businessName: 'receiving',
event: 'receiving_rejected',
title: `收货单 ${item.receiving_number || item.id} 已被驳回`,
content: [
`驳回人:${reviewerName || '未知'}`,
`驳回理由:${updateData.remark || '无'}`,
`收货单ID:${item.id || ''}`,
`收货单号:${item.receiving_number || '无'}`,
`收货创建人:${item.creator && item.creator.name || '无'}`,
'请及时处理重新提交完成收货。',
].join('\n') + '。',
businessId: item.id || ids[0],
subject: {
id: warehouse_id,
type: 'warehouse',
name: String((ctx.user && (ctx.user.store_name || ctx.user.company_name)) || ''),
},
sender: {
id: reviewerEmployeeId || ctx.user?.id || null,
name: reviewerName,
},
metadata: {
id: item.id || null,
ids: [ item.id || null ].filter(Boolean),
receiving_id: item.id || null,
receiving_ids: [ item.id || null ].filter(Boolean),
receiving_number: item.receiving_number || '',
receiving_numbers: item.receiving_number ? [ item.receiving_number ] : [],
receiving_creator: item.creator || null,
receiving_creators: item.creator ? [ item.creator ] : [],
receiving: item,
receivings: [ item ],
warehouseId: warehouse_id,
remark: updateData.remark || '',
},
})));
}
} catch (notifyErr) {
ctx.logger.warn('[receiving.rejectReceiving] 发送驳回通知失败,不影响业务', notifyErr);
}
return { code: 200, message: '驳回成功', data: { count: ids.length } };
} catch (error) {
ctx.logger.error('[receiving.rejectReceiving] 驳回收货单失败', error);
return { code: 500, message: '服务器错误', data: {} };
}
}
/**
* 批量审核收货单:校验所有单据的状态后,用事务批量更新审核信息。
* 任意一张不符合条件则整批失败并回滚。
* @param {Object} data 请求体
* @param {number[]} data.ids 收货单ID数组
* @return {Promise<Object>} 操作结果
*/
async reviewReceiving(data) {
const { ids } = data;
const { ctx } = this;
const { Op } = ctx.model.Sequelize;
const warehouse_id = ctx.user.store_id;
if (!Array.isArray(ids) || ids.length === 0) {
return { code: 0, message: '收货单ID不能为空', data: {} };
}
const normalizedIds = Array.from(new Set(ids.map(Number).filter(n => Number.isFinite(n) && n > 0)));
if (normalizedIds.length === 0) {
return { code: 0, message: '收货单ID格式不正确', data: {} };
}
const reviewerName = String(ctx.user?.employees_name || '').trim() || null;
const reviewerEmployeeId = ctx.user?.employees_id || null;
const transaction = await ctx.model.transaction();
try {
// 加行锁查询,防止并发审核
const receivings = await ctx.model.Receiving.findAll({
where: { id: { [Op.in]: normalizedIds }, warehouse_id },
lock: transaction.LOCK.UPDATE,
transaction,
});
if (receivings.length !== normalizedIds.length) {
await transaction.rollback();
return { code: 0, message: '部分单据不存在或无权访问', data: {} };
}
// 逐条校验,收集所有不符合的收货单
const errors = [];
for (const r of receivings) {
if (r.status !== 'completed') {
errors.push(`收货单 ${r.receiving_number || r.id} 状态非收货完成`);
}
if (r.detail_status !== 'all_matched') {
errors.push(`收货单 ${r.receiving_number || r.id} 明细未全部匹配`);
}
if (r.storage_status !== 'none') {
errors.push(`收货单 ${r.receiving_number || r.id} 已存在入库记录`);
}
if (!r.store_id) {
errors.push(`收货单 ${r.receiving_number || r.id} 未绑定货主`);
}
if (Number(r.is_review) === 1) {
errors.push(`收货单 ${r.receiving_number || r.id} 已审核,无需重复操作`);
}
}
if (errors.length > 0) {
await transaction.rollback();
return { code: 0, message: errors.join(';'), data: {} };
}
// MySQL 二次状态核实:确保 WHERE 条件精准匹配,防止并发竞争
const updateResult = await ctx.model.Receiving.update(
{
is_review: 1,
reviewer_name: reviewerName,
reviewer_employee_id: reviewerEmployeeId,
},
{
where: {
id: { [Op.in]: normalizedIds },
warehouse_id,
[Op.or]: [
{ is_review: 0 },
{ is_review: null },
],
},
transaction,
}
);
const affectedRows = Array.isArray(updateResult)
? Number(updateResult[0] || 0)
: Number(updateResult || 0);
if (affectedRows !== normalizedIds.length) {
await transaction.rollback();
return { code: 0, message: '收货单审核状态已变化,请刷新后重试', data: {} };
}
// 写操作日志(失败不影响业务)
try {
const operationLogService = ctx.service && ctx.service.systems && ctx.service.systems.operationLog;
const payloads = normalizedIds.map(receivingId => ({
businessType: 'receiving',
businessId: receivingId,
operationCode: 'RECEIVING_REVIEW',
operator: {
id: reviewerEmployeeId || ctx.user?.id,
name: reviewerName || '',
},
extras: { warehouseId: warehouse_id },
beforeChanges: null,
transaction,
}));
if (operationLogService && typeof operationLogService.createOperationLogs === 'function') {
await operationLogService.createOperationLogs(payloads, { transaction });
}
} catch (logErr) {
ctx.logger.warn('[receiving.reviewReceiving] 写入操作日志失败,不影响业务', logErr);
}
await transaction.commit();
// 逐单发送审核完成通知(文字 + 文件,失败不影响业务)
const reviewer = {
employees_id: reviewerEmployeeId,
employees_name: reviewerName,
name: reviewerName,
id: reviewerEmployeeId,
};
for (const r of receivings) {
const receivingSnapshot = {
...(typeof r.toJSON === 'function' ? r.toJSON() : r),
is_review: 1,
reviewer_name: reviewerName,
reviewer_employee_id: reviewerEmployeeId,
updated_at: new Date(),
};
ctx.logger.info('[receiving.reviewReceiving] 开始处理单据通知', {
receiving_id: r.id,
receiving_number: r.receiving_number,
reviewer: reviewerName,
});
// 1. 发送文字通知
try {
const textResult = await this.sendReviewNotice({ receiving: receivingSnapshot, reviewer });
ctx.logger.info('[receiving.reviewReceiving] 文字通知结果', {
receiving_id: r.id,
receiving_number: r.receiving_number,
success: !!(textResult && textResult.success),
message: textResult && textResult.message,
matchedHookCount: Number(textResult && textResult.data && textResult.data.matchedHookCount || 0),
sentCount: Number(textResult && textResult.data && textResult.data.sentCount || 0),
failedCount: Number(textResult && textResult.data && textResult.data.failedCount || 0),
});
} catch (textErr) {
ctx.logger.error('[receiving.reviewReceiving] 文字通知发送失败', {
receiving_id: r.id,
error: textErr.message,
});
}
// 2. 加载明细与图片,生成 Excel 报表
let reviewReport = null;
try {
const details = await ctx.model.ReceivingDetail.findAll({
where: { receiving_id: r.id },
});
const detailIds = details.map(d => String(d.id));
const detailImageMap = new Map();
if (detailIds.length > 0) {
const detailImageRefs = await ctx.model.FileReference.findAll({
where: {
business_type: 'receivingItem',
business_id: { [Op.in]: detailIds },
},
include: [{ model: ctx.model.File, as: 'file', attributes: [ 'file_url' ], required: true }],
});
detailImageRefs.forEach(ref => {
const bid = String(ref.business_id);
if (!detailImageMap.has(bid)) detailImageMap.set(bid, []);
detailImageMap.get(bid).push(ref);
});
}
const receivingImages = await ctx.model.FileReference.findAll({
where: { business_type: 'receiving', business_id: r.id },
include: [{ model: ctx.model.File, as: 'file', attributes: [ 'file_url' ], required: true }],
});
const stats = {
total_details: details.length,
matched_details: details.filter(d => d.system_product_id).length,
unmatched_details: details.filter(d => !d.system_product_id).length,
total_quantity: details.reduce((sum, d) => sum + (d.actual_quantity || 0), 0),
};
const excelService = ctx.service && ctx.service.systems && ctx.service.systems.excel;
if (excelService && typeof excelService.generateAndUpload === 'function') {
const receivingNumber = String(r.receiving_number || r.id).replace(/[\\/:*?"<>|]/g, '_');
reviewReport = await excelService.generateAndUpload({
filename: `审核明细_${receivingNumber}.xlsx`,
dir: `exports/receiving/reviewed/${warehouse_id}`,
category: 'document',
saveRecord: true,
businessType: 'receivingReviewReport',
businessId: r.id,
expireDays: 90,
sheets: this.buildReviewReportSheets({
receiving: { ...receivingSnapshot, details },
reviewer,
stats,
detailImageMap,
receivingImages,
}),
});
}
ctx.logger.info('[receiving.reviewReceiving] Excel报表生成结果', {
receiving_id: r.id,
receiving_number: r.receiving_number,
success: !!reviewReport,
url: reviewReport && (reviewReport.url || reviewReport.cdnUrl || reviewReport.cosUrl || ''),
});
} catch (reportErr) {
ctx.logger.error('[receiving.reviewReceiving] Excel报表生成失败,跳过文件通知', {
receiving_id: r.id,
error: reportErr.message,
});
}
// 3. 发送文件通知(仅当 Excel 上传成功时)
if (reviewReport) {
try {
const fileResult = await this.sendReviewNotice({ receiving: receivingSnapshot, reviewer, reviewReport });
ctx.logger.info('[receiving.reviewReceiving] 文件通知结果', {
receiving_id: r.id,
receiving_number: r.receiving_number,
success: !!(fileResult && fileResult.success),
message: fileResult && fileResult.message,
matchedHookCount: Number(fileResult && fileResult.data && fileResult.data.matchedHookCount || 0),
sentCount: Number(fileResult && fileResult.data && fileResult.data.sentCount || 0),
failedCount: Number(fileResult && fileResult.data && fileResult.data.failedCount || 0),
reportUrl: reviewReport.url || reviewReport.cdnUrl || reviewReport.cosUrl || '',
});
} catch (fileErr) {
ctx.logger.error('[receiving.reviewReceiving] 文件通知发送失败', {
receiving_id: r.id,
error: fileErr.message,
});
}
}
ctx.logger.info('[receiving.reviewReceiving] 单据通知处理完成', {
receiving_id: r.id,
receiving_number: r.receiving_number,
hasReport: !!reviewReport,
});
}
return { code: 200, message: '审核成功', data: { count: normalizedIds.length } };
} catch (error) {
await transaction.rollback();
ctx.logger.error('[receiving.reviewReceiving] 审核收货单失败', error);
return { code: 500, message: `审核失败: ${error.message}`, data: {} };
}
}
/**
* 构建审核完成 Excel 报表 sheets,复用收货完成报表结构,但标注"审核人"而非"完成人"。
* @param {Object} options 构建参数
* @param {Object} options.receiving 收货单(需含 details 数组)
* @param {Object} [options.reviewer={}] 审核人信息
* @param {Object} [options.stats={}] 明细统计
* @param {Map} [options.detailImageMap] 明细图片 Map(key=detail.id字符串)
* @param {Array} [options.receivingImages] 收货单主图片数组
* @return {Array} sheets 数组
*/
buildReviewReportSheets({
receiving,
reviewer = {},
stats = {},
detailImageMap = new Map(),
receivingImages = [],
}) {
const details = Array.isArray(receiving && receiving.details)
? receiving.details.map(item => (typeof item.toJSON === 'function' ? item.toJSON() : item))
: [];
const mainImageUrls = (Array.isArray(receivingImages) ? receivingImages : [])
.map(item => (item && (item.url || item.file_url || (item.file && item.file.file_url))) || '')
.filter(Boolean);
const rows = [];
const embeddedImages = [];
const styledRows = [];
const summaryImageColumnIndex = 3;
const detailColumns = [
'序号', '商品名称', '条码',
'数量', '重量', '箱数', '托数',
'批次号', '生产日期', '到期日期', '备注', '图片链接', '图片',
];
const detailImageColumnIndex = detailColumns.length;
const maxDetailImageCount = Math.max(
1,
...details.map(detail => {
const imgs = Array.isArray(detailImageMap.get(String(detail.id)))
? detailImageMap.get(String(detail.id))
: [];
return imgs
.map(item => (item && (item.url || item.file_url || (item.file && item.file.file_url))) || '')
.filter(Boolean).length;
})
);
const buildLinkCell = urls => {
const normalized = (Array.isArray(urls) ? urls : [ urls ])
.map(item => String(item || '').trim())
.filter(Boolean);
if (normalized.length === 0) return '';
return { text: normalized.join('\n'), hyperlink: normalized[0], tooltip: normalized.join('\n') };
};
const pushRow = (cells = [], options = {}) => {
rows.push(cells);
const rowIndex = rows.length;
const maxCol = Math.max(Number(options.toCol || cells.length || 1), 1);
if (options.style || options.height) {
styledRows.push({
row: rowIndex,
fromCol: Math.max(Number(options.fromCol || 1), 1),
toCol: maxCol,
style: options.style || null,
height: options.height || null,
});
}
return rowIndex;
};
pushRow([]);
const reviewerName = reviewer.employees_name || reviewer.real_name || reviewer.name || '';
const reviewedAt = receiving.updated_at || new Date();
[
[ '收货单ID', receiving && receiving.id ],
[ '收货单号', receiving && receiving.receiving_number ],
[ '货主', receiving && receiving.store_name ],
[ '来货方式', this.formatDeliveryMethod(receiving && receiving.delivery_method) ],
...this.getCompletionContactFields(receiving),
[ '总明细数', stats.total_details || details.length ],
[ '已匹配明细数', stats.matched_details || 0 ],
[ '未匹配明细数', stats.unmatched_details || 0 ],
[ '总数量', stats.total_quantity || 0 ],
[ '总箱数', receiving && receiving.total_boxes ],
[ '总托盘数', receiving && receiving.total_pallets ],
[ '审核人', reviewerName ],
[ '审核时间', this.formatReportDate(reviewedAt) ],
[ '备注', receiving && receiving.remark ],
].forEach(([ field, value ]) => {
pushRow([ field, value ], {
toCol: 2,
style: { alignment: { vertical: 'top', wrapText: true } },
});
});
if (mainImageUrls.length === 0) {
pushRow([ '收货图片', '无' ], { toCol: 2, style: { alignment: { vertical: 'top', wrapText: true } } });
} else {
const summaryLinkCell = buildLinkCell(mainImageUrls);
const imagePlaceholders = Array(Math.max(mainImageUrls.length, 1)).fill('');
const firstImageRowIndex = pushRow([ '收货图片', summaryLinkCell, ...imagePlaceholders ], {
toCol: 2 + imagePlaceholders.length,
height: 88,
style: { alignment: { vertical: 'top', wrapText: true } },
});
mainImageUrls.forEach((imageUrl, index) => {
embeddedImages.push({ row: firstImageRowIndex, col: summaryImageColumnIndex + index, url: imageUrl, width: 96, height: 96, fallbackText: `收货图片${index + 1}` });
});
}
pushRow([]);
pushRow(detailColumns, {
toCol: detailColumns.length,
height: 22,
style: {
font: { bold: true, color: { argb: 'FF1F1F1F' } },
fill: { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FFD9EAF7' } },
alignment: { horizontal: 'center', vertical: 'middle', wrapText: true },
},
});
if (details.length === 0) {
pushRow([ '', '', '无明细' ], { toCol: detailColumns.length, style: { alignment: { vertical: 'top', wrapText: true } } });
} else {
details.forEach((detail, index) => {
const imgs = Array.isArray(detailImageMap.get(String(detail.id)))
? detailImageMap.get(String(detail.id))
: [];
const imgUrls = imgs
.map(item => (item && (item.url || item.file_url || (item.file && item.file.file_url))) || '')
.filter(Boolean);
const imageSlotCount = Math.max(imgUrls.length, 1);
const linkCell = buildLinkCell(imgUrls);
const rowCells = [
index + 1,
detail.product_name || '',
detail.barcode || '',
detail.actual_quantity || 0,
detail.weight || 0,
detail.box_quantity || 0,
detail.pallet_quantity || 0,
detail.batch_number || '',
this.formatReportDate(detail.production_date),
this.formatReportDate(detail.expiry_date),
detail.remark || '',
linkCell,
...Array(imageSlotCount).fill(''),
];
const targetRow = pushRow(rowCells, {
toCol: rowCells.length,
height: imgUrls.length > 0 ? 88 : null,
style: { alignment: { vertical: 'top', wrapText: true } },
});
imgUrls.forEach((imageUrl, imageIndex) => {
embeddedImages.push({ row: targetRow, col: detailImageColumnIndex + imageIndex, url: imageUrl, width: 96, height: 96, fallbackText: `图片${imageIndex + 1}` });
});
});
}
return [
{
name: '审核明细',
rows,
widths: [
16, 28, 18, 10, 10, 10, 10, 18, 18, 18, 24, 42, 18,
...Array(Math.max(maxDetailImageCount - 1, 0)).fill(18),
],
embeddedImages,
styledRows,
skipHeader: true,
forceExcelJs: true,
},
];
}
/**
* 发送审核完成通知(receiving_reviewed),支持文字/文件两种类型。
* @param {Object} options 发送参数
* @param {Object} options.receiving 收货单快照
* @param {Object} [options.reviewer={}] 审核人信息
* @param {Object|null} [options.reviewReport=null] 审核报表(有值则发文件通知)
* @return {Promise<Object|null>} 发送结果
*/
async sendReviewNotice({
receiving,
reviewer = {},
reviewReport = null,
} = {}) {
const { ctx } = this;
const rawNoticeService = ctx && ctx.service && ctx.service.systems && ctx.service.systems.notice;
const noticeService = rawNoticeService && typeof rawNoticeService.send === 'function'
? rawNoticeService
: (rawNoticeService && rawNoticeService.index && typeof rawNoticeService.index.send === 'function'
? rawNoticeService.index
: null);
if (!receiving || !receiving.id || !noticeService) return null;
const warehouseId = Number(receiving.warehouse_id || (ctx.user && ctx.user.store_id) || 0);
if (!Number.isFinite(warehouseId) || warehouseId <= 0) return null;
const storeId = Number(receiving.store_id || 0);
const reviewerName = String(reviewer.employees_name || reviewer.real_name || reviewer.name || '').trim();
const receivingNumber = String(receiving.receiving_number || receiving.id || '').trim();
const reportUrl = String(
(reviewReport && (reviewReport.url || reviewReport.cdnUrl || reviewReport.cosUrl || reviewReport.fileUrl)) || ''
).trim();
const reportFileName = String(
(reviewReport && (reviewReport.filename || reviewReport.fileKey || reviewReport.key)) || `审核明细_${receivingNumber}.xlsx`
).trim();
const content = [
`收货单号:${receivingNumber}`,
`货主:${receiving.store_name || '未知'}`,
`审核人:${reviewerName || '未知'}`,
`审核时间:${this.formatReportDate(receiving.updated_at || new Date())}`,
`备注:${receiving.remark || '无'}`,
].join('\n') + '。';
return await noticeService.send({
warehouseId,
storeId: Number.isFinite(storeId) && storeId > 0 ? storeId : undefined,
messageType: reportUrl ? 'file' : 'text',
businessName: 'receiving',
event: 'receiving_reviewed',
title: `收货单${receivingNumber}审核完成`,
content,
url: reportUrl || undefined,
fileName: reportUrl ? reportFileName : '',
mimeType: reportUrl ? 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' : '',
businessId: receiving.id,
subject: {
id: warehouseId,
type: 'warehouse',
name: String((ctx.user && (ctx.user.store_name || ctx.user.company_name)) || ''),
},
sender: {
id: reviewer.employees_id || reviewer.id || null,
name: reviewerName,
},
metadata: {
receivingId: receiving.id,
receivingNumber,
warehouseId,
reviewReport: reportUrl ? { fileKey: reviewReport.fileKey || '', url: reportUrl } : null,
},
});
}
isEmptyValue(value) {
if (value === undefined || value === null) {
return true;
}
if (typeof value === 'string' && value.trim() === '') {
return true;
}
if (Array.isArray(value) && value.length === 0) {
return true;
}
return false;
}
/**
* 构建Sequelize查询条件
* @param {string} fieldKey - 字段键名
* @param {Object} condition - 条件对象
* @param {Object} app - Egg应用实例
* @return {Object|null} Sequelize条件对象
*/
buildSequelizeCondition(fieldKey, condition, app) {
const {
Sequelize,
} = app;
const {
operator = 'eq', value, type,
} = condition;
// 处理字段名
const fieldName = condition.field || fieldKey;
// 特殊值处理
const processedValue = this.processConditionValue(value, type);
// 根据操作符构建条件
switch (operator.toLowerCase()) {
case 'eq':
return {
[fieldName]: processedValue,
};
case 'ne':
return {
[fieldName]: {
[Sequelize.Op.ne]: processedValue,
},
};
case 'contains':
case 'like':
// 处理多值情况
if (Array.isArray(processedValue) && processedValue.length > 0) {
// 多个值使用 OR 连接
return {
[Sequelize.Op.or]: processedValue.map(val => ({
[fieldName]: {
[Sequelize.Op.like]: `%${val}%`,
},
})),
};
}
// 单个值正常处理
return {
[fieldName]: {
[Sequelize.Op.like]: `%${processedValue}%`,
},
};
case 'startswith':
// 处理多值情况
if (Array.isArray(processedValue) && processedValue.length > 0) {
return {
[Sequelize.Op.or]: processedValue.map(val => ({
[fieldName]: {
[Sequelize.Op.like]: `${val}%`,
},
})),
};
}
return {
[fieldName]: {
[Sequelize.Op.like]: `${processedValue}%`,
},
};
case 'endswith':
// 处理多值情况
if (Array.isArray(processedValue) && processedValue.length > 0) {
return {
[Sequelize.Op.or]: processedValue.map(val => ({
[fieldName]: {
[Sequelize.Op.like]: `%${val}`,
},
})),
};
}
return {
[fieldName]: {
[Sequelize.Op.like]: `%${processedValue}`,
},
};
case 'gt':
return {
[fieldName]: {
[Sequelize.Op.gt]: processedValue,
},
};
case 'lt':
return {
[fieldName]: {
[Sequelize.Op.lt]: processedValue,
},
};
case 'ge':
return {
[fieldName]: {
[Sequelize.Op.gte]: processedValue,
},
};
case 'le':
return {
[fieldName]: {
[Sequelize.Op.lte]: processedValue,
},
};
case 'in':
return Array.isArray(processedValue) ? {
[fieldName]: {
[Sequelize.Op.in]: processedValue,
},
} :
null;
case 'notin':
return Array.isArray(processedValue) ? {
[fieldName]: {
[Sequelize.Op.notIn]: processedValue,
},
} :
null;
case 'between':
return Array.isArray(processedValue) && processedValue.length === 2 ? {
[fieldName]: {
[Sequelize.Op.between]: processedValue,
},
} :
null;
case 'notbetween':
return Array.isArray(processedValue) && processedValue.length === 2 ? {
[fieldName]: {
[Sequelize.Op.notBetween]: processedValue,
},
} :
null;
case 'isnull':
return {
[fieldName]: {
[Sequelize.Op.is]: null,
},
};
case 'isnotnull':
return {
[fieldName]: {
[Sequelize.Op.not]: null,
},
};
case 'regexp':
return {
[fieldName]: {
[Sequelize.Op.regexp]: processedValue,
},
};
case 'notregexp':
return {
[fieldName]: {
[Sequelize.Op.notRegexp]: processedValue,
},
};
default:
// 默认使用等于操作符
return {
[fieldName]: processedValue,
};
}
}
/**
* 处理条件值
* @param {any} value - 原始值
* @param {string} type - 字段类型
* @return {any} 处理后的值
*/
processConditionValue(value, type) {
const { service } = this;
if (value === undefined || value === null) {
return value;
}
switch (type) {
case 'boolean':
// 处理布尔值:true/Y -> 'Y', false/N -> 'N'
if (value === true || value === 'true' || value === 'Y' || value === 'y') {
return 'Y';
}
if (value === false || value === 'false' || value === 'N' || value === 'n') {
return 'N';
}
return value;
case 'date':
// 单个日期,根据业务需求决定是开始还是结束时间
// 通常是开始时间(00:00:00)
return service.main.normalizeDate(value, false);
case 'daterange':
// 处理日期范围:数组的第一个元素是开始时间,第二个元素是结束时间
if (Array.isArray(value) && value.length === 2) {
const [ startDate, endDate ] = value;
return [
startDate ? service.main.normalizeDate(startDate, false) : null, // 开始时间设为00:00:00
endDate ? service.main.normalizeDate(endDate, true) : null, // 结束时间设为23:59:59
];
}
return value;
case 'number':
{
const num = parseFloat(value);
return isNaN(num) ? value : num;
}
case 'text':
if (typeof value === 'string') {
return value.split(',').map(item => item.trim());
}
return value;
default:
return value;
}
}
buildReceivingNumberPrefix(date = new Date()) {
const dateStr = Math.floor(date.getTime() / (1000 * 60 * 60 * 24));
return `R${dateStr}`;
}
async generateNextReceivingNumber(prefix) {
const { app } = this.ctx;
const suffixStartIndex = prefix.length + 1;
const maxReceiving = await app.model.Receiving.findOne({
attributes: [ 'receiving_number' ],
where: {
receiving_number: {
[app.Sequelize.Op.like]: `${prefix}%`,
},
},
order: [
[ app.Sequelize.literal(`CAST(SUBSTRING(receiving_number, ${suffixStartIndex}) AS UNSIGNED)`), 'DESC' ],
[ 'receiving_number', 'DESC' ],
],
});
let sequence = 1;
if (maxReceiving && maxReceiving.receiving_number) {
const lastNumStr = String(maxReceiving.receiving_number).slice(prefix.length);
const lastNum = Number.parseInt(lastNumStr, 10);
if (Number.isFinite(lastNum) && lastNum > 0) {
sequence = lastNum + 1;
}
}
const seqLen = Math.max(3, String(sequence).length);
return `${prefix}${String(sequence).padStart(seqLen, '0')}`;
}
isReceivingNumberDuplicateError(error) {
const parentCode = error && error.parent && error.parent.code;
const sqlMessage = String((error && error.parent && error.parent.sqlMessage) || error.message || '');
return parentCode === 'ER_DUP_ENTRY'
&& /uk_receiving_number|receiving_number/i.test(sqlMessage);
}
/**
* 创建收货单并生成收货单号。
* @param {Object} data 创建参数
* @return {Promise<Object>} 新建结果(含 id 与 receiving_number)
*/
async create(data) {
const {
delivery_method,
license_plate,
loading_method,
remark,
status,
store_id,
total_boxes,
total_pallets,
tracking_number,
video_device_id,
} = data;
const { ctx } = this;
const { app } = ctx;
try {
// 1. 获取当前用户信息
const warehouse_id = ctx.user.store_id;
const creator_id = ctx.user.employees_id;
const creator_snapshot = {
name: ctx.user.employees_name,
employees_id: ctx.user.employees_id,
id: creator_id,
};
// 2. 生成收货单号。注意:`wms_receiving.receiving_number` 在数据库中是全局唯一索引,
// 不能按 warehouse_id 各自从 001 开始,否则跨仓会撞号;并发创建时也需要重试兜底。
const now = new Date();
const prefix = this.buildReceivingNumberPrefix(now);
// 3. 获取店铺名称(如果有货主)
let store_name = null;
if (store_id) {
const store = await app.model.StoreWarehouse.findOne({
where: {
store_id,
warehouse_id,
warehouse_use_status: 1,
},
});
if (store) {
store_name = store.store_remask;
}
}
// 4. 创建收货单记录(并发下若撞到唯一键则自动重试取下一个号)
const maxCreateRetries = 5;
let result = null;
let lastCreateError = null;
for (let attempt = 1; attempt <= maxCreateRetries; attempt++) {
const receiving_number = await this.generateNextReceivingNumber(prefix);
const receivingData = {
receiving_number,
creator_id,
creator_snapshot: JSON.stringify(creator_snapshot),
status: status || 'receiving',
detail_status: 'unmatched',
storage_status: 'none',
delivery_method,
license_plate: delivery_method === 'truck' ? license_plate : null,
tracking_number: delivery_method !== 'truck' && delivery_method !== 'other' ? tracking_number : null,
loading_method,
video_device_id: video_device_id || null,
total_boxes: parseInt(total_boxes) || 0,
total_pallets: parseInt(total_pallets) || 0,
total_items: 0,
total_quantity: 0,
warehouse_id,
remark: remark || null,
store_name,
store_id: store_id || null,
receiving_start_time: new Date(),
is_deleted: false,
};
try {
result = await app.model.Receiving.create(receivingData);
break;
} catch (error) {
lastCreateError = error;
if (this.isReceivingNumberDuplicateError(error) && attempt < maxCreateRetries) {
ctx.logger.warn(`[ReceivingCreateRetry] receiving_number 冲突,准备重试第 ${attempt + 1} 次`, {
prefix,
warehouse_id,
});
continue;
}
throw error;
}
}
if (!result) {
throw lastCreateError || new Error('创建收货任务失败');
}
// 记录操作日志
try {
await ctx.service.systems.operationLog.createOperationLog({
businessType: 'receiving',
businessId: result.id,
operationCode: 'RECEIVING_CREATE',
operator: {
id: ctx.user?.employees_id || ctx.user?.id,
name: ctx.user?.employees_name || '',
},
extras: {
warehouseId: warehouse_id,
},
beforeChanges: null,
});
} catch (logErr) {
ctx.logger.warn('[receiving.create] 写入操作日志失败,不影响业务', logErr);
}
return {
code: 200,
id: result.id,
receiving_number: result.receiving_number,
message: '收货任务创建成功',
};
} catch (error) {
ctx.logger.error('创建收货任务失败:', error);
return {
code: 0,
message: `创建失败: ${error.message}`,
};
}
}
/**
* 按ID修改收货单基础信息。
* @param {Object} data 修改参数
* @param {number} data.id 收货单ID
* @return {Promise<Object>} 修改结果
*/
async save(data = {}) {
const {
id,
delivery_method,
license_plate,
loading_method,
remark,
status,
store_id,
total_boxes,
total_pallets,
tracking_number,
video_device_id,
} = data;
const { ctx } = this;
const warehouseId = Number(ctx.user && ctx.user.store_id);
const receivingId = Number(id || 0);
if (!warehouseId) {
return {
code: 400,
message: '用户未绑定仓库',
};
}
if (receivingId <= 0) {
return {
code: 400,
message: '收货单ID不能为空',
};
}
const transaction = await ctx.model.transaction();
try {
const receiving = await ctx.model.Receiving.findOne({
where: {
id: receivingId,
warehouse_id: warehouseId,
is_deleted: false,
},
lock: transaction.LOCK.UPDATE,
transaction,
});
if (!receiving) {
await transaction.rollback();
return {
code: 404,
message: '收货单不存在或无权访问',
};
}
if (receiving.status === 'cancelled') {
await transaction.rollback();
return {
code: 400,
message: '已取消的收货单不允许修改',
};
}
let storeName = receiving.store_name || null;
if (Object.prototype.hasOwnProperty.call(data, 'store_id')) {
const normalizedStoreId = Number(store_id || 0);
if (normalizedStoreId > 0) {
const storeRelation = await ctx.model.StoreWarehouse.findOne({
where: {
warehouse_id: warehouseId,
store_id: normalizedStoreId,
warehouse_use_status: 1,
},
attributes: [ 'store_id', 'store_remask' ],
transaction,
});
if (!storeRelation) {
await transaction.rollback();
return {
code: 404,
message: '货主不存在或未与当前仓库建立有效签约关系',
};
}
storeName = storeRelation.store_remask || null;
} else {
storeName = null;
}
}
const updateData = {
updated_at: new Date(),
};
if (delivery_method !== undefined) {
updateData.delivery_method = delivery_method;
updateData.license_plate = delivery_method === 'truck'
? (license_plate === undefined ? (receiving.license_plate || null) : (license_plate || null))
: null;
updateData.tracking_number = delivery_method !== 'truck' && delivery_method !== 'other'
? (tracking_number === undefined ? (receiving.tracking_number || null) : (tracking_number || null))
: null;
} else {
if (license_plate !== undefined) {
updateData.license_plate = receiving.delivery_method === 'truck' ? (license_plate || null) : null;
}
if (tracking_number !== undefined) {
updateData.tracking_number = receiving.delivery_method !== 'truck' && receiving.delivery_method !== 'other'
? (tracking_number || null)
: null;
}
}
if (loading_method !== undefined) {
updateData.loading_method = loading_method;
}
if (remark !== undefined) {
updateData.remark = remark || null;
}
if (status !== undefined) {
updateData.status = status || 'receiving';
}
if (Object.prototype.hasOwnProperty.call(data, 'store_id')) {
updateData.store_id = Number(store_id || 0) > 0 ? Number(store_id) : null;
updateData.store_name = storeName;
}
if (total_boxes !== undefined) {
updateData.total_boxes = parseInt(total_boxes) || 0;
}
if (total_pallets !== undefined) {
updateData.total_pallets = parseInt(total_pallets) || 0;
}
if (video_device_id !== undefined) {
updateData.video_device_id = video_device_id || null;
}
await ctx.model.Receiving.update(updateData, {
where: {
id: receivingId,
warehouse_id: warehouseId,
},
transaction,
});
await transaction.commit();
try {
await ctx.service.systems.operationLog.createOperationLog({
businessType: 'receiving',
businessId: receivingId,
operationCode: 'RECEIVING_UPDATE',
operator: {
id: ctx.user?.employees_id || ctx.user?.id,
name: ctx.user?.employees_name || '',
},
extras: {
warehouseId,
},
beforeChanges: {
delivery_method: receiving.delivery_method,
license_plate: receiving.license_plate,
loading_method: receiving.loading_method,
remark: receiving.remark,
status: receiving.status,
store_id: receiving.store_id,
store_name: receiving.store_name,
total_boxes: receiving.total_boxes,
total_pallets: receiving.total_pallets,
tracking_number: receiving.tracking_number,
video_device_id: receiving.video_device_id,
},
});
} catch (logErr) {
ctx.logger.warn('[receiving.save] 写入操作日志失败,不影响业务', logErr);
}
return {
code: 200,
id: receivingId,
receiving_number: receiving.receiving_number,
message: '收货单修改成功',
};
} catch (error) {
await transaction.rollback();
ctx.logger.error('[receiving.save] 修改收货单失败', error);
return {
code: 0,
message: `修改失败: ${error.message}`,
};
}
}
/**
* 绑定收货单货主。
* 规则:
* 1. 已取消收货单禁止绑定;
* 2. 收货中/已完成状态下,若已存在货主,则禁止重复绑定;
* 3. 仅允许绑定与当前仓库存在有效签约关系的货主。
* @param {Object} data 请求体
* @param {number} data.id 收货单ID
* @param {number} data.store_id 货主ID
* @return {Promise<Object>} 绑定结果
*/
async bindStore(data) {
const { ctx } = this;
const { id, store_id } = data || {};
const warehouseId = Number(ctx.user && ctx.user.store_id);
const receivingId = Number(id || 0);
const storeId = Number(store_id || 0);
if (!warehouseId) {
return {
code: 400,
message: '用户未绑定仓库',
};
}
if (receivingId <= 0) {
return {
code: 400,
message: '收货单ID不能为空',
};
}
if (storeId <= 0) {
return {
code: 400,
message: '货主ID不能为空',
};
}
const transaction = await ctx.model.transaction();
try {
const receiving = await ctx.model.Receiving.findOne({
where: {
id: receivingId,
warehouse_id: warehouseId,
is_deleted: false,
},
lock: transaction.LOCK.UPDATE,
transaction,
});
if (!receiving) {
await transaction.rollback();
return {
code: 404,
message: '收货单不存在或无权访问',
};
}
if (receiving.status === 'cancelled') {
await transaction.rollback();
return {
code: 400,
message: '已取消的收货单不允许绑定货主',
};
}
if ([ 'receiving', 'completed' ].includes(receiving.status) && Number(receiving.store_id || 0) > 0) {
await transaction.rollback();
return {
code: 400,
message: '当前收货单已有货主,拒绝重复绑定',
};
}
const storeRelation = await ctx.model.StoreWarehouse.findOne({
where: {
warehouse_id: warehouseId,
store_id: storeId,
warehouse_use_status: 1,
},
attributes: [ 'store_id', 'store_remask' ],
transaction,
});
if (!storeRelation) {
await transaction.rollback();
return {
code: 404,
message: '货主不存在或未与当前仓库建立有效签约关系',
};
}
const storeName = storeRelation.store_remask || null;
await ctx.model.Receiving.update({
store_id: storeId,
store_name: storeName,
updated_at: new Date(),
}, {
where: {
id: receivingId,
warehouse_id: warehouseId,
},
transaction,
});
await transaction.commit();
// 记录操作日志
try {
await ctx.service.systems.operationLog.createOperationLog({
businessType: 'receiving',
businessId: receivingId,
operationCode: 'RECEIVING_BIND_STORE',
operator: {
id: ctx.user?.employees_id || ctx.user?.id,
name: ctx.user?.employees_name || '',
},
extras: {
warehouseId,
},
beforeChanges: {
store_id: receiving.store_id,
store_name: receiving.store_name,
},
});
} catch (logErr) {
ctx.logger.warn('[receiving.bindStore] 写入操作日志失败,不影响业务', logErr);
}
return {
code: 200,
message: '绑定货主成功',
data: {
id: receivingId,
store_id: storeId,
store_name: storeName,
status: receiving.status,
},
};
} catch (error) {
await transaction.rollback();
ctx.logger.error('绑定收货单货主失败:', error);
return {
code: 500,
message: `绑定货主失败: ${error.message}`,
};
}
}
/**
* 查询单个收货单完整信息(含明细、图片)。
* @param {Object} data 请求体
* @param {number} data.id 收货单ID
* @return {Promise<Object>} 单据详情
*/
async get(data) {
const { id } = data;
const { ctx, app } = this;
const { Op } = app.Sequelize;
// 获取用户仓库ID,增加错误处理
const warehouseId = ctx.user?.store_id;
if (!warehouseId) {
return { code: 0, message: '用户未绑定仓库', data: {} };
}
try {
// 1. 查询收货单主表
const receiving = await app.model.Receiving.findOne({
where: {
id,
warehouse_id: warehouseId,
},
include: [{
model: ctx.model.StoreWarehouse,
as: 'store',
attributes: [ 'store_remask' ],
where: {
warehouse_use_status: 1,
warehouse_id: warehouseId,
},
required: false,
}, {
model: ctx.model.AccountStoreEmployee,
as: 'creator',
attributes: [ 'real_name' ],
required: false,
}],
// 不需要order,因为根据id查询已经是唯一的
});
if (!receiving) {
return { code: 0, message: '无记录或无权访问', data: {} };
}
// 2. 查询收货单明细
const receivingItems = await app.model.ReceivingDetail.findAll({
where: {
receiving_id: id,
},
include: [
{
model: ctx.model.LocationSpace,
as: 'receiving_space',
attributes: [ 'space_code', 'custom_barcode', 'custom_name' ],
},
],
order: [[ 'id', 'DESC' ]], // 保持倒序,最新在前
});
// 3. 获取明细ID数组
const receivingItemsIds = receivingItems.map(item => item.id);
// 4. 查询明细图片(如果明细数量大于0)
const itemImagesMap = {}; // 用于存储每个明细的图片
if (receivingItemsIds.length > 0) {
const receivingItemsImages = await ctx.model.FileReference.findAll({
where: {
business_type: 'receivingItem',
business_id: {
[Op.in]: receivingItemsIds,
},
},
include: [{
model: ctx.model.File,
as: 'file',
attributes: [ 'file_url' ],
required: true,
}],
});
// 将图片按 business_id 分组
receivingItemsImages.forEach(itemImage => {
const businessId = itemImage.business_id;
if (!itemImagesMap[businessId]) {
itemImagesMap[businessId] = [];
}
itemImagesMap[businessId].push({
url: itemImage.file.file_url,
id: itemImage.file_id,
});
});
}
// 5. 将图片合并到对应的明细中
const items = receivingItems.map(item => {
const itemData = item.toJSON();
return {
...itemData,
box_remainder: itemData.box_remainder ?? 0,
box_weight: itemData.box_weight ?? 0,
images: itemImagesMap[item.id] || [], // 获取该明细的图片,如果没有则为空数组
};
});
// 6. 查询主表的图片
const receivingImages = await ctx.model.FileReference.findAll({
where: {
business_type: 'receiving',
business_id: id,
},
include: [{
model: ctx.model.File,
as: 'file',
attributes: [ 'file_url' ],
required: true,
}],
});
// 7. 组装返回数据
const result = {
...receiving.toJSON(), // 使用toJSON()确保获得纯对象
details: items, // 包含图片的明细数据
images: receivingImages.map(item => ({
url: item.file.file_url,
id: item.file_id,
})),
};
return { code: 200, message: '成功', data: result };
} catch (error) {
console.error('获取收货单详情失败:', error);
return { code: 500, message: '服务器错误', data: {} };
}
}
/**
* 向收货单新增一条收货明细。
* @param {Object} data 请求体
* @param {number} data.receiving_id 收货单ID
* @param {Object} [data.item] 可选的明细字段
* @return {Promise<Object>} 明细列表与默认选中ID
* @description 未传 `item` 时,保持原有空白明细创建行为;传入 `item` 时,合并默认值后交由 Sequelize 校验与写入,并由服务端覆盖 `receiving_id` 与 `creator_id`。
*/
async addDetail(data) {
const ctx = this.ctx;
const { receiving_id } = data;
const item = data && data.item && typeof data.item === 'object' && !Array.isArray(data.item)
? data.item
: {};
// 获取当前用户信息
const creator_id = ctx.user.employees_id;
const warehouse_id = ctx.user.store_id;
// 验证收货单是否存在
const receiving = await ctx.model.Receiving.findOne({
where: { id: receiving_id, warehouse_id },
});
if (!receiving) {
return {
code: 404,
message: '收货单不存在',
};
}
// 验证收货单状态是否允许添加明细
if (receiving.status !== 'receiving') {
return {
code: 400,
message: '收货单状态不允许添加明细',
};
}
try {
const defaultDetail = {
receiving_id,
product_name: '新商品',
barcode: '',
actual_quantity: 0,
box_quantity: 0,
boxes_per_pallet: 0,
pallet_quantity: 0,
receiving_status: 'pending',
storage_status: 'none',
stored_quantity: 0,
batch_number: '',
production_date: null,
expiry_date: null,
remark: '',
space_id: 1,
creator_id,
};
// 允许前端传入可选明细字段,但服务端字段始终覆盖。
const newDetail = await ctx.model.ReceivingDetail.create({
...defaultDetail,
...item,
receiving_id,
creator_id,
});
// 获取更新后的明细列表
const allDetails = await ctx.model.ReceivingDetail.findAll({
where: { receiving_id },
order: [[ 'id', 'DESC' ]],
});
// 格式化返回数据
const formattedDetails = allDetails.map(detail => {
const detailData = detail.toJSON();
// 处理product_snapshot
if (detailData.product_snapshot) {
try {
detailData.product_snapshot = JSON.parse(detailData.product_snapshot);
} catch (e) {
detailData.product_snapshot = null;
}
}
// 如果有关联的系统商品,可以合并信息
if (detailData.system_product) {
detailData.system_product_info = detailData.system_product;
}
return detailData;
});
await this.updateReceivingStats(receiving_id);
// 记录操作日志
try {
await ctx.service.systems.operationLog.createOperationLog({
businessType: 'receiving',
businessId: receiving_id,
operationCode: 'RECEIVING_ADD_DETAIL',
operator: {
id: ctx.user?.employees_id || ctx.user?.id,
name: ctx.user?.employees_name || '',
},
extras: {
warehouseId: warehouse_id,
},
beforeChanges: {
detail_id: newDetail.id,
},
});
} catch (logErr) {
ctx.logger.warn('[receiving.addDetail] 写入操作日志失败,不影响业务', logErr);
}
return {
code: 200,
message: '添加成功',
data: {
details: formattedDetails,
selectId: newDetail.id,
},
};
} catch (error) {
ctx.logger.error('添加收货明细失败:', error);
return {
code: 500,
message: `添加失败: ${error.message}`,
};
}
}
/**
* 绑定或改绑收货单明细的系统商品。
* @param {Object} data 请求体
* @param {number} data.detail_id 收货单明细ID(兼容 `id`)
* @param {number} data.system_product_id 商品ID
* @return {Promise<Object>} 绑定结果
*/
async bindDetailProduct(data) {
const { ctx, app } = this;
const warehouseId = Number(ctx.user && ctx.user.store_id);
const detailId = Number((data && (data.detail_id || data.id)) || 0);
const systemProductId = Number((data && data.system_product_id) || 0);
if (!warehouseId) {
return {
code: 400,
message: '用户未绑定仓库',
};
}
if (detailId <= 0) {
return {
code: 400,
message: '收货单明细ID不能为空',
};
}
if (systemProductId <= 0) {
return {
code: 400,
message: '商品ID不能为空',
};
}
try {
const receivingDetail = await app.model.ReceivingDetail.findOne({
where: { id: detailId },
include: [
{
model: app.model.Receiving,
as: 'receiving',
attributes: [ 'id', 'warehouse_id', 'store_id', 'store_name', 'status', 'is_review' ],
where: {
warehouse_id: warehouseId,
},
required: true,
},
],
});
if (!receivingDetail) {
return {
code: 404,
message: '收货单明细不存在',
};
}
if (Number(receivingDetail.receiving?.is_review) === 1) {
return {
code: 400,
message: '收货单已审核,禁止绑定或改绑商品',
};
}
if (String(receivingDetail.receiving?.status || '') === 'cancelled') {
return {
code: 400,
message: '收货单已作废,禁止绑定或改绑商品',
};
}
const stockWarehouse = await app.model.StockWarehouse.findOne({
where: {
id: systemProductId,
warehouse_id: warehouseId,
},
include: [
app.model.StoreWarehouse.buildStoreStockInclude({
warehouseId,
required: false,
attributes: [ 'store_id', 'store_remask' ],
}),
{
model: app.model.StockBarcode,
as: 'barcodes',
attributes: [ 'barcode' ],
required: false,
},
],
});
if (!stockWarehouse) {
return {
code: 404,
message: '商品不存在或不属于当前仓库',
};
}
const productStoreId = Number(stockWarehouse.store_stock?.store_id || 0);
const receivingStoreId = Number(receivingDetail.receiving?.store_id || 0);
// 货主校验:收货单已有货主时,只允许绑定同一货主的商品
if (receivingStoreId > 0 && productStoreId > 0 && receivingStoreId !== productStoreId) {
return {
code: 400,
message: '该商品不属于当前收货单的货主,不允许绑定',
};
}
// 收货单无货主时,自动设置为当前商品的货主
let autoBindStore = false;
if (receivingStoreId <= 0 && productStoreId > 0) {
const storeName = stockWarehouse.store_stock?.store_remask || null;
await app.model.Receiving.update({
store_id: productStoreId,
store_name: storeName,
updated_at: new Date(),
}, {
where: { id: receivingDetail.receiving_id, warehouse_id: warehouseId },
});
autoBindStore = true;
}
const barcodes = Array.isArray(stockWarehouse.barcodes)
? stockWarehouse.barcodes.map(item => item && item.barcode).filter(Boolean)
: [];
let productSnapshot = {};
if (receivingDetail.product_snapshot) {
try {
productSnapshot = JSON.parse(receivingDetail.product_snapshot) || {};
} catch {
productSnapshot = {};
}
}
const productName = stockWarehouse.item_name || stockWarehouse.name || receivingDetail.product_name || '未命名商品';
const updateData = {
system_product_id: systemProductId,
product_name: productName,
product_snapshot: JSON.stringify({
...productSnapshot,
system_product_id: systemProductId,
product_name: productName,
store_id: productStoreId || productSnapshot.store_id || null,
store_name: stockWarehouse.store_stock?.store_remask || productSnapshot.store_name || null,
updated_at: new Date(),
}),
};
// 判断是否为改绑(明细之前已绑定过其他商品)
const isRebind = receivingDetail.system_product_id
&& Number(receivingDetail.system_product_id) !== systemProductId;
// 如果收货明细有条码且商品尚未包含该条码,则自动为商品新增条码
// 但改绑操作不写入条码(条码属于旧商品上下文,不应污染新商品)
const detailBarcode = String(receivingDetail.barcode || '').trim();
if (!isRebind && detailBarcode && !barcodes.includes(detailBarcode)) {
try {
await app.model.StockBarcode.create({
stock_id: systemProductId,
warehouse_id: warehouseId,
barcode: detailBarcode,
});
barcodes.push(detailBarcode);
} catch (barcodeErr) {
// 唯一索引冲突说明条码已被其他商品占用,仅记录日志不阻断业务
ctx.logger.warn('[receiving.bindDetailProduct] 自动新增条码失败(可能已存在)', barcodeErr);
}
}
if (barcodes.length > 0) {
updateData.barcode = barcodes.join(';');
}
if (stockWarehouse.gross_weight !== undefined && stockWarehouse.gross_weight !== null) {
updateData.weight = stockWarehouse.gross_weight;
}
if (stockWarehouse.enable_box_spec) {
updateData.boxes_per_pallet = stockWarehouse.quantity_per_box || receivingDetail.boxes_per_pallet || 0;
updateData.box_height = stockWarehouse.box_height || receivingDetail.box_height || 0;
updateData.box_width = stockWarehouse.box_width || receivingDetail.box_width || 0;
updateData.box_length = stockWarehouse.box_length || receivingDetail.box_length || 0;
}
await ctx.model.ReceivingDetail.update(updateData, {
where: { id: detailId },
});
await this.updateReceivingStats(receivingDetail.receiving_id);
// 记录操作日志
try {
await ctx.service.systems.operationLog.createOperationLog({
businessType: 'receiving',
businessId: receivingDetail.receiving_id,
operationCode: 'RECEIVING_BIND_PRODUCT',
operator: {
id: ctx.user?.employees_id || ctx.user?.id,
name: ctx.user?.employees_name || '',
},
extras: {
warehouseId,
},
beforeChanges: {
detail_id: detailId,
old_system_product_id: receivingDetail.system_product_id,
new_system_product_id: systemProductId,
},
});
} catch (logErr) {
ctx.logger.warn('[receiving.bindDetailProduct] 写入操作日志失败,不影响业务', logErr);
}
const responseData = {
detail_id: detailId,
receiving_id: receivingDetail.receiving_id,
system_product_id: systemProductId,
product_name: productName,
};
if (autoBindStore) {
responseData.auto_bind_store_id = productStoreId;
responseData.auto_bind_store_name = stockWarehouse.store_stock?.store_remask || null;
}
return {
code: 200,
message: autoBindStore ? '绑定商品成功,已自动设置货主' : '绑定商品成功',
data: responseData,
};
} catch (error) {
ctx.logger.error('绑定收货单明细商品失败:', error);
return {
code: 500,
message: `绑定商品失败: ${error.message}`,
};
}
}
async updateDetail(data) {
const ctx = this.ctx;
const { id, ...updateData } = data;
// 验证明细是否存在
const detail = await ctx.model.ReceivingDetail.findOne({
where: { id },
include: [
{
model: ctx.model.Receiving,
as: 'receiving',
attributes: [ 'id', 'status' ],
},
],
});
if (!detail) {
return {
code: 404,
message: '明细不存在',
};
}
// 验证关联的收货单状态是否允许修改
if (detail.receiving && detail.receiving.status !== 'receiving') {
return {
code: 400,
message: '收货单状态不允许修改明细',
};
}
// 验证必填字段
if (updateData.product_name && !updateData.product_name.trim()) {
return {
code: 400,
message: '商品名称不能为空',
};
}
if (updateData.actual_quantity !== undefined && updateData.actual_quantity <= 0) {
return {
code: 400,
message: '实际数量必须大于0',
};
}
try {
// 如果需要处理商品匹配
if (updateData.barcode && updateData.barcode.trim()) {
// 尝试根据条码匹配系统商品
const systemProduct = await ctx.model.StockWarehouse.findOne({
where: { barcode: updateData.barcode },
});
if (systemProduct) {
updateData.system_product_id = systemProduct.id;
// 创建商品快照
updateData.product_snapshot = JSON.stringify({
name: systemProduct.name,
barcode: systemProduct.barcode,
spec: systemProduct.spec,
unit: systemProduct.unit,
images: systemProduct.images ? JSON.parse(systemProduct.images) : [],
});
// 如果用户没有输入商品名称,使用系统商品名称
if (!updateData.product_name) {
updateData.product_name = systemProduct.name;
}
}
}
// 处理数量类型的转换
if (updateData.actual_quantity !== undefined) {
updateData.actual_quantity = parseInt(updateData.actual_quantity) || 0;
}
if (updateData.box_quantity !== undefined) {
updateData.box_quantity = parseInt(updateData.box_quantity) || 0;
}
if (updateData.boxes_per_pallet !== undefined) {
updateData.boxes_per_pallet = parseInt(updateData.boxes_per_pallet) || 1;
}
if (updateData.pallet_quantity !== undefined) {
updateData.pallet_quantity = parseInt(updateData.pallet_quantity) || 0;
}
if (updateData.stored_quantity !== undefined) {
updateData.stored_quantity = parseInt(updateData.stored_quantity) || 0;
// 根据入库数量更新入库状态
if (updateData.stored_quantity >= updateData.actual_quantity) {
updateData.storage_status = 'all';
} else if (updateData.stored_quantity > 0) {
updateData.storage_status = 'partial';
} else {
updateData.storage_status = 'none';
}
}
// 更新明细
const [ affectedRows ] = await ctx.model.ReceivingDetail.update(updateData, {
where: { id },
});
if (affectedRows === 0) {
return {
code: 400,
message: '更新失败',
};
}
// 更新收货单统计信息
if (detail.receiving_id) {
await this.updateReceivingStats(detail.receiving_id);
}
// 获取更新后的明细
const updatedDetail = await ctx.model.ReceivingDetail.findOne({
where: { id },
include: [
{
model: ctx.model.StockWarehouse,
as: 'system_product',
attributes: [ 'id', 'name', 'barcode', 'spec', 'unit', 'images' ],
},
],
});
// 格式化返回数据
const detailData = updatedDetail.toJSON();
if (detailData.product_snapshot) {
try {
detailData.product_snapshot = JSON.parse(detailData.product_snapshot);
} catch (e) {
detailData.product_snapshot = null;
}
}
if (detailData.system_product && detailData.system_product.images) {
try {
detailData.system_product.images = JSON.parse(detailData.system_product.images);
} catch (e) {
detailData.system_product.images = [];
}
}
return {
code: 200,
message: '更新成功',
data: detailData,
};
} catch (error) {
ctx.logger.error('更新收货明细失败:', error);
return {
code: 500,
message: `更新失败: ${error.message}`,
};
}
}
async getStockStoreInfo(stock_id) {
const ctx = this.ctx;
try {
// 方法1:通过 StockWarehouse 直接关联 StoreWarehouse
const stockWarehouse = await ctx.model.StockWarehouse.findOne({
where: { id: stock_id },
include: [
ctx.model.StoreWarehouse.buildStoreStockInclude({
warehouseId: ctx.user.store_id,
required: false,
attributes: [ 'store_id', 'store_remask' ],
}),
],
});
if (!stockWarehouse || !stockWarehouse.store_stock) {
return null;
}
// 直接返回 store_stock 的信息
return {
store_id: stockWarehouse.store_stock.store_id,
store_remask: stockWarehouse.store_stock.store_remask,
};
} catch (error) {
ctx.logger.error(`获取库存 ${stock_id} 的店铺信息失败:`, error);
// 根据需求决定是否抛出错误
// throw error;
return null;
}
}
// 更新收货单统计信息的辅助方法
async updateReceivingStats(receivingId) {
const { ctx, app } = this;
const { Op } = app.Sequelize;
const transaction = await ctx.model.transaction();
const warehouseId = ctx.user.store_id;
try {
// 1. 先查询收货单,并加锁
const receiving = await ctx.model.Receiving.findOne({
where: {
warehouse_id: warehouseId,
id: receivingId,
status: {
[Op.ne]: 'cancelled',
},
},
lock: transaction.LOCK.UPDATE,
transaction,
});
if (!receiving) {
await transaction.rollback();
return;
}
// 2. 检查收货单是否已有 store_id(优先使用已有值)
let storeId = receiving.store_id;
let storeName = receiving.store_name;
// 如果收货单没有 store_id,尝试从已匹配的商品详情中获取
if (!storeId) {
// 查找第一个已匹配的商品详情(system_product_id 不为空)
const matchedDetail = await app.model.ReceivingDetail.findOne({
where: {
receiving_id: receivingId,
system_product_id: {
[Op.ne]: null,
},
},
transaction,
});
if (matchedDetail && matchedDetail.system_product_id) {
try {
// 调用 getStockStoreInfo 获取库存信息
const storeInfo = await this.getStockStoreInfo(matchedDetail.system_product_id);
if (storeInfo && storeInfo.store_id) {
storeId = storeInfo.store_id;
// 注意:这里使用 store_remask 作为 store_name
storeName = storeInfo.store_remask; // 或者 storeInfo.store_remask
}
} catch (error) {
ctx.logger.warn(`获取商品 ${matchedDetail.system_product_id} 的库存信息失败:`, error);
// 继续执行,使用默认值
}
}
}
// 3. 统计该收货单的所有明细
const stats = await ctx.model.ReceivingDetail.findAll({
where: { receiving_id: receivingId },
attributes: [
[ ctx.model.fn('COUNT', ctx.model.col('id')), 'total_items' ],
[ ctx.model.fn('SUM', ctx.model.col('actual_quantity')), 'total_quantity' ],
],
raw: true,
transaction,
});
const stat = stats[0] || {};
// 4. 判断收货单的整体状态
const allDetails = await ctx.model.ReceivingDetail.findAll({
where: { receiving_id: receivingId },
transaction,
});
let detailStatus = 'unmatched';
if (allDetails.length > 0) {
const completedCount = allDetails.filter(d => !!d.system_product_id).length;
if (completedCount === allDetails.length) {
detailStatus = 'all_matched';
} else if (completedCount > 0) {
detailStatus = 'partial_matched';
}
}
// 5. 更新收货单
const updateData = {
total_items: parseInt(stat.total_items) || 0,
total_quantity: parseFloat(stat.total_quantity) || 0,
detail_status: detailStatus,
updated_at: new Date(),
};
// 只在有值且收货单当前没有这些值时更新 store 信息
if (storeId && !receiving.store_id) {
updateData.store_id = storeId;
updateData.store_name = storeName;
} else if (storeId && storeName && receiving.store_name !== storeName) {
// 如果 store_id 已有但 store_name 不同,也更新名称
updateData.store_name = storeName;
}
await ctx.model.Receiving.update(updateData, {
where: {
id: receivingId,
warehouse_id: warehouseId,
},
transaction,
});
// 6. 提交事务
await transaction.commit();
ctx.logger.info(`成功更新收货单 ${receivingId} 的统计信息`);
} catch (error) {
// 7. 发生错误时回滚事务
if (transaction) {
await transaction.rollback();
}
ctx.logger.error('更新收货单统计失败:', error);
throw error;
}
}
/**
* 删除收货单明细并回算统计。
* @param {Object} data 请求体
* @param {number} data.detail_id 明细ID
* @return {Promise<Object>} 删除结果
*/
async deleteDetail(data) {
const ctx = this.ctx;
const { detail_id } = data;
const warehouse_id = ctx.user.store_id;
// 验证明细是否存在(通过收货单的 warehouse_id 做权限校验,不限制 creator_id,
// 以允许同一仓库下不同操作员删除彼此创建的明细,与 get 方法行为保持一致)
const detail = await ctx.model.ReceivingDetail.findOne({
where: { id: detail_id },
include: [
{
model: ctx.model.Receiving,
as: 'receiving',
attributes: [ 'id', 'status' ],
where: {
warehouse_id,
},
required: true,
},
],
});
if (!detail) {
return {
code: 404,
message: '明细不存在',
};
}
// 验证关联的收货单状态是否允许删除
if (detail.receiving && detail.receiving.status !== 'receiving') {
return {
code: 400,
message: '收货单状态不允许删除明细',
};
}
// 检查是否已入库(已入库的明细不能删除)
if (detail.storage_status !== 'none' && detail.stored_quantity > 0) {
return {
code: 400,
message: '该明细已入库,不能删除',
};
}
try {
// 获取receiving_id用于后续更新统计
const receiving_id = detail.receiving_id;
// 删除明细
const deletedCount = await ctx.model.ReceivingDetail.destroy({
where: { id: detail_id },
});
if (deletedCount === 0) {
return {
code: 400,
message: '删除失败',
};
}
// 获取删除后的所有明细
const remainingDetails = await ctx.model.ReceivingDetail.findAll({
where: { receiving_id },
order: [[ 'id', 'DESC' ]],
});
// 格式化返回数据
const formattedDetails = remainingDetails.map(detail => {
const detailData = detail.toJSON();
if (detailData.product_snapshot) {
try {
detailData.product_snapshot = JSON.parse(detailData.product_snapshot);
} catch (e) {
detailData.product_snapshot = null;
}
}
return detailData;
});
// 返回下一个选中的明细ID(如果有剩余明细)
let selectId = null;
if (remainingDetails.length > 0) {
// 默认选中第一个
selectId = remainingDetails[0].id;
}
await this.updateReceivingStats(receiving_id);
// 记录操作日志
try {
await ctx.service.systems.operationLog.createOperationLog({
businessType: 'receiving',
businessId: receiving_id,
operationCode: 'RECEIVING_DELETE_DETAIL',
operator: {
id: ctx.user?.employees_id || ctx.user?.id,
name: ctx.user?.employees_name || '',
},
extras: {
warehouseId: warehouse_id,
},
beforeChanges: {
detail_id,
product_name: detail.product_name,
actual_quantity: detail.actual_quantity,
},
});
} catch (logErr) {
ctx.logger.warn('[receiving.deleteDetail] 写入操作日志失败,不影响业务', logErr);
}
return {
code: 200,
message: '删除成功',
data: {
details: formattedDetails,
selectId,
},
};
} catch (error) {
ctx.logger.error('删除收货明细失败:', error);
return {
code: 500,
message: `删除失败: ${error.message}`,
};
}
}
/**
* 修改收货明细。
* @param {Object} data 收货明细修改参数
* @return {Promise<Object>} 修改结果
*/
async detailChange(data) {
const { ctx, app } = this;
const warehouseId = ctx.user.store_id;
try {
// 1. 提取前端输入字段
const {
id, // 收货明细ID
receiving_id, // 收货单ID
actual_quantity, // 实际收货数量
batch_number, // 批次号
production_date, // 生产日期
expiry_date, // 到期日期
box_quantity, // 箱数
boxes_per_pallet, // 每托盘箱数
pallet_quantity, // 托盘数
space_id, // 存放库位ID
remark, // 备注
system_product_id, // 系统商品ID
barcode, // 条码
product_name, // 商品名称
box_width,
box_height,
box_length,
weight,
box_remainder, // 箱余数
box_weight, // 箱重量
} = data;
// 2. 验证必填字段
if (!id) {
return {
code: 400,
message: '收货明细ID不能为空',
};
}
if (!receiving_id) {
return {
code: 400,
message: '收货单ID不能为空',
};
}
// 3. 获取收货明细信息
const receivingDetail = await app.model.ReceivingDetail.findOne({
where: { id },
include: [
{
model: app.model.Receiving,
as: 'receiving',
attributes: [ 'id', 'warehouse_id', 'store_id', 'store_name' ],
where: {
warehouse_id: warehouseId,
id: receiving_id,
status: 'receiving',
},
required: true,
},
],
});
if (!receivingDetail) {
return {
code: 404,
message: '收货明细不存在',
};
}
if (expiry_date && expiry_date !== undefined && isExpiryDateBeforeToday(expiry_date)) {
return {
code: 400,
message: '到期日期已过期,不能录入收货',
};
}
// 5. 验证箱规数据
if (box_quantity !== undefined && box_quantity < 0) {
return {
code: 400,
message: '箱数不能为负数',
};
}
if (pallet_quantity !== undefined && pallet_quantity < 0) {
return {
code: 400,
message: '托盘数不能为负数',
};
}
if (box_remainder !== undefined && box_remainder < 0) {
return {
code: 400,
message: '箱余数不能为负数',
};
}
if (box_weight !== undefined && box_weight < 0) {
return {
code: 400,
message: '箱重量不能为负数',
};
}
// 6. 准备更新数据
const updateData = {
actual_quantity,
remark: remark || '',
};
// 箱规相关字段
if (box_quantity !== undefined) updateData.box_quantity = box_quantity || 0;
if (boxes_per_pallet !== undefined) updateData.boxes_per_pallet = boxes_per_pallet || 0;
if (pallet_quantity !== undefined) updateData.pallet_quantity = pallet_quantity || 0;
if (barcode !== undefined) updateData.barcode = barcode || '';
if (box_length !== undefined) updateData.box_length = box_length || 0;
if (box_width !== undefined) updateData.box_width = box_width || 0;
if (box_height !== undefined) updateData.box_height = box_height || 0;
if (weight !== undefined) updateData.weight = weight || 0;
if (box_remainder !== undefined) updateData.box_remainder = box_remainder || 0;
if (box_weight !== undefined) updateData.box_weight = box_weight || 0;
// 批次信息
if (batch_number !== undefined) updateData.batch_number = batch_number;
if (production_date !== undefined) updateData.production_date = production_date;
if (expiry_date !== undefined) updateData.expiry_date = expiry_date;
// 库位信息
if (space_id !== undefined) updateData.space_id = space_id;
// 7. 如果携带了系统商品ID,则更新商品相关信息
if (system_product_id) {
// 获取系统商品信息
const stockWarehouse = await app.model.StockWarehouse.findOne({
where: {
id: system_product_id,
warehouse_id: warehouseId,
},
include: [
app.model.StoreWarehouse.buildStoreStockInclude({
warehouseId,
required: false,
attributes: [ 'store_id', 'store_remask' ],
}),
{
model: app.model.StockBarcode,
as: 'barcodes',
attributes: [ 'barcode' ],
required: false,
},
],
});
if (stockWarehouse) {
// 更新商品相关信息
updateData.system_product_id = system_product_id;
// 使用系统商品的条码(如果前端没有提供)
const barcodes = stockWarehouse.barcodes?.map(b => b.barcode) || [];
updateData.barcode = updateData.barcode || barcodes.join(';');
updateData.weight = updateData.weight || stockWarehouse.gross_weight;
if (stockWarehouse.enable_box_spec) {
updateData.boxes_per_pallet = updateData.boxes_per_pallet || stockWarehouse.quantity_per_box;
updateData.box_height = updateData.box_height || stockWarehouse.box_height;
updateData.box_width = updateData.box_width || stockWarehouse.box_width;
updateData.box_length = updateData.box_length || stockWarehouse.box_length;
}
// 使用系统商品的名称(如果前端没有提供)
updateData.product_name = stockWarehouse.item_name || product_name;
// 如果有货主信息,更新到产品快照中
if (stockWarehouse.store_stock) {
const productSnapshot = {
...(receivingDetail.product_snapshot ? JSON.parse(receivingDetail.product_snapshot) : {}),
store_id: stockWarehouse.store_stock.store_id,
store_name: stockWarehouse.store_stock.store_remask,
updated_at: new Date(),
};
updateData.product_snapshot = JSON.stringify(productSnapshot);
}
}
} else if (barcode !== undefined || product_name !== undefined) {
// 如果没有系统商品ID,但有条码或商品名称,也更新
if (barcode !== undefined) updateData.barcode = barcode;
if (product_name !== undefined) updateData.product_name = product_name;
updateData.system_product_id = null;
}
if (space_id) {
const sapce = await app.model.LocationSpace.findOne({
where: {
id: space_id,
[app.Sequelize.Op.or]: [
{ warehouse_id: warehouseId },
{ warehouse_id: null },
],
},
});
if (sapce) {
updateData.space_id = space_id;
}
}
// 8. 更新收货明细
await ctx.model.ReceivingDetail.update(updateData, {
where: { id },
});
await this.updateReceivingStats(receiving_id);
// 记录操作日志
try {
await ctx.service.systems.operationLog.createOperationLog({
businessType: 'receiving',
businessId: receiving_id,
operationCode: 'RECEIVING_UPDATE_DETAIL',
operator: {
id: ctx.user?.employees_id || ctx.user?.id,
name: ctx.user?.employees_name || '',
},
extras: {
warehouseId,
},
beforeChanges: {
detail_id: id,
product_name: receivingDetail.product_name,
actual_quantity: receivingDetail.actual_quantity,
system_product_id: receivingDetail.system_product_id,
},
});
} catch (logErr) {
ctx.logger.warn('[receiving.detailChange] 写入操作日志失败,不影响业务', logErr);
}
// 9. 返回成功响应
return {
code: 200,
data: {
id: receivingDetail.id,
receiving_id: receivingDetail.receiving_id,
actual_quantity: receivingDetail.actual_quantity,
product_name: receivingDetail.product_name,
barcode: receivingDetail.barcode,
system_product_id: receivingDetail.system_product_id,
box_remainder: updateData.box_remainder !== undefined ? updateData.box_remainder : receivingDetail.box_remainder,
box_weight: updateData.box_weight !== undefined ? updateData.box_weight : receivingDetail.box_weight,
updated_at: receivingDetail.updated_at,
},
message: '修改成功',
};
} catch (error) {
ctx.logger.error('修改失败:', error);
return {
code: 500,
message: '修改失败,请稍后重试',
error: process.env.NODE_ENV === 'development' ? error.message : undefined,
};
}
}
async invalid(data) {
const { ctx, app } = this;
const warehouseId = ctx.user.store_id;
const { Op } = app.Sequelize;
const { id: receivingId, invalid_reason } = data;
const transaction = await ctx.model.transaction();
try {
// 1. 查询收货单并加锁
const receiving = await ctx.model.Receiving.findOne({
where: {
id: receivingId,
warehouse_id: warehouseId,
is_deleted: false,
},
lock: transaction.LOCK.UPDATE,
transaction,
include: [{
model: ctx.model.ReceivingDetail,
as: 'details',
required: false,
}],
});
if (!receiving) {
await transaction.rollback();
ctx.throw(404, '收货单不存在或已被删除');
}
// 2. 检查状态是否允许作废
if (receiving.status === 'cancelled') {
return {
code: 200,
success: true,
message: '收货单已作废,无需重复操作',
};
}
if (receiving.status === 'completed' && receiving.storage_status === 'all') {
await transaction.rollback();
ctx.throw(400, '已全部入库完成,无法作废');
}
// 3. 获取操作人信息
const operator = ctx.user;
// 4. 更新收货单状态为作废
await ctx.model.Receiving.update({
status: 'cancelled',
remark: invalid_reason ? `已作废: ${invalid_reason}` : (receiving.remark || '') + ' - 已作废',
updated_at: new Date(),
}, {
where: { id: receivingId },
transaction,
});
// 5. 处理已匹配的商品明细
if (receiving.details && receiving.details.length > 0) {
const matchedDetails = receiving.details.filter(detail => detail.system_product_id);
if (matchedDetails.length > 0) {
// 解除已匹配的商品关联
await ctx.model.ReceivingDetail.update({
system_product_id: null,
matched_at: null,
matched_by: null,
updated_at: new Date(),
}, {
where: {
receiving_id: receivingId,
system_product_id: { [Op.ne]: null },
},
transaction,
});
// 可以在这里处理库存的释放逻辑(如果需要)
// await this.releaseLockedStock(receivingId, transaction);
}
}
// 6. 处理关联的入库记录(如果有部分入库的情况)
if (receiving.storage_status === 'partial') {
// 将关联的入库记录状态也更新为作废
await ctx.model.Storage.update({
status: 'cancelled',
remark: `关联收货单${receiving.receiving_number}已作废`,
updated_at: new Date(),
}, {
where: {
receiving_id: receivingId,
status: { [Op.ne]: 'cancelled' },
},
transaction,
});
}
// 8. 提交事务
await transaction.commit();
// 记录操作日志
try {
await ctx.service.systems.operationLog.createOperationLog({
businessType: 'receiving',
businessId: receivingId,
operationCode: 'RECEIVING_CANCEL',
operator: {
id: ctx.user?.employees_id || ctx.user?.id,
name: ctx.user?.employees_name || '',
},
extras: {
warehouseId,
},
beforeChanges: {
previous_status: receiving.status,
invalid_reason,
},
});
} catch (logErr) {
ctx.logger.warn('[receiving.invalid] 写入操作日志失败,不影响业务', logErr);
}
return {
code: 200,
success: true,
message: '作废成功',
data: {
receiving_id: receivingId,
receiving_number: receiving.receiving_number,
previous_status: receiving.status,
invalidated_at: new Date(),
invalidated_by: operator.name,
invalid_reason,
},
};
} catch (error) {
// 10. 回滚事务
if (transaction) {
await transaction.rollback();
}
ctx.logger.error(`作废收货单失败: ${error.message}`, {
receivingId,
warehouseId,
userId: ctx.user.id,
error: error.stack,
});
// 重新抛出错误,让上层处理
throw error;
}
}
formatReportDate(value) {
if (!value) {
return '';
}
const date = value instanceof Date ? value : new Date(value);
if (Number.isNaN(date.getTime())) {
return '';
}
return date.toLocaleString('zh-CN', { hour12: false });
}
formatDeliveryMethod(value) {
const methodMap = {
truck: '货车',
express: '快递',
air_freight: '空运',
sea_freight: '海运',
other: '其他',
};
const normalizedValue = String(value || '').trim();
return methodMap[normalizedValue] || normalizedValue;
}
/**
* 获取完成收货时需要展示的联系字段。
* @param {Object} receiving 收货单快照。
* @return {Array<Array>} 需要展示的联系字段列表。
*/
getCompletionContactFields(receiving) {
const deliveryMethod = String((receiving && receiving.delivery_method) || '').trim();
if (deliveryMethod === 'truck') {
return [[ '车牌号', receiving && receiving.license_plate ]];
}
if (deliveryMethod === 'express') {
return [[ '物流单号', receiving && receiving.tracking_number ]];
}
return [];
}
/**
* 生成收货完成报表的工作表数据。
* @param {Object} options 报表参数。
* @param {Object} options.receiving 收货单快照。
* @param {Object} [options.operator={}] 操作人信息。
* @param {Object} [options.stats={}] 收货统计数据。
* @param {Map} [options.detailImageMap=new Map()] 明细图片映射。
* @param {Array} [options.receivingImages=[]] 收货单图片列表。
* @return {Array<Object>} 工作表列表。
*/
buildCompletionReportSheets({
receiving,
operator = {},
stats = {},
detailImageMap = new Map(),
receivingImages = [],
}) {
const details = Array.isArray(receiving && receiving.details)
? receiving.details.map(item => (typeof item.toJSON === 'function' ? item.toJSON() : item))
: [];
const mainImageUrls = (Array.isArray(receivingImages) ? receivingImages : [])
.map(item => (item && (item.url || item.file_url || (item.file && item.file.file_url))) || '')
.filter(Boolean);
const rows = [];
const embeddedImages = [];
const styledRows = [];
const summaryImageColumnIndex = 3;
const detailColumns = [
'序号', '商品名称', '条码',
'数量', '重量', '箱数', '托数',
'批次号', '生产日期', '到期日期', '备注', '图片链接', '图片',
];
const detailImageColumnIndex = detailColumns.length;
const maxDetailImageCount = Math.max(
1,
...details.map(detail => {
const detailImages = Array.isArray(detailImageMap.get(String(detail.id)))
? detailImageMap.get(String(detail.id))
: [];
const detailImageUrls = detailImages
.map(item => (item && (item.url || item.file_url || (item.file && item.file.file_url))) || '')
.filter(Boolean);
return detailImageUrls.length;
})
);
const buildLinkCell = urls => {
const normalizedUrls = (Array.isArray(urls) ? urls : [ urls ])
.map(item => String(item || '').trim())
.filter(Boolean);
if (normalizedUrls.length === 0) {
return '';
}
return {
text: normalizedUrls.join('\n'),
hyperlink: normalizedUrls[0],
tooltip: normalizedUrls.join('\n'),
};
};
const pushReportRow = (cells = [], options = {}) => {
rows.push(cells);
const rowIndex = rows.length;
const maxCol = Math.max(Number(options.toCol || cells.length || 1), 1);
if (options.style || options.height) {
styledRows.push({
row: rowIndex,
fromCol: Math.max(Number(options.fromCol || 1), 1),
toCol: maxCol,
style: options.style || null,
height: options.height || null,
});
}
return rowIndex;
};
pushReportRow([]);
[
[ '收货单ID', receiving && receiving.id ],
[ '收货单号', receiving && receiving.receiving_number ],
[ '货主', receiving && receiving.store_name ],
[ '来货方式', this.formatDeliveryMethod(receiving && receiving.delivery_method) ],
...this.getCompletionContactFields(receiving),
[ '总明细数', stats.total_details || details.length ],
[ '已匹配明细数', stats.matched_details || 0 ],
[ '未匹配明细数', stats.unmatched_details || 0 ],
[ '总数量', stats.total_quantity || 0 ],
[ '总箱数', receiving && receiving.total_boxes ],
[ '总托盘数', receiving && receiving.total_pallets ],
[ '完成人', operator.employees_name || operator.real_name || operator.name || '' ],
[ '完成时间', this.formatReportDate(receiving && receiving.receiving_end_time) ],
[ '备注', receiving && receiving.remark ],
].forEach(([ field, value ]) => {
pushReportRow([ field, value ], {
toCol: 2,
style: {
alignment: { vertical: 'top', wrapText: true },
},
});
});
if (mainImageUrls.length === 0) {
pushReportRow([ '收货图片', '无' ], {
toCol: 2,
style: {
alignment: { vertical: 'top', wrapText: true },
},
});
} else {
const summaryLinkCell = buildLinkCell(mainImageUrls);
const imagePlaceholders = Array(Math.max(mainImageUrls.length, 1)).fill('');
const firstImageRowIndex = pushReportRow([ '收货图片', summaryLinkCell, ...imagePlaceholders ], {
toCol: 2 + imagePlaceholders.length,
height: 88,
style: {
alignment: { vertical: 'top', wrapText: true },
},
});
mainImageUrls.forEach((imageUrl, index) => {
embeddedImages.push({
row: firstImageRowIndex,
col: summaryImageColumnIndex + index,
url: imageUrl,
width: 96,
height: 96,
fallbackText: `收货图片${index + 1}`,
});
});
}
pushReportRow([]);
pushReportRow(detailColumns, {
toCol: detailColumns.length,
height: 22,
style: {
font: { bold: true, color: { argb: 'FF1F1F1F' } },
fill: {
type: 'pattern',
pattern: 'solid',
fgColor: { argb: 'FFD9EAF7' },
},
alignment: { horizontal: 'center', vertical: 'middle', wrapText: true },
},
});
if (details.length === 0) {
pushReportRow([ '', '', '无明细' ], {
toCol: detailColumns.length,
style: {
alignment: { vertical: 'top', wrapText: true },
},
});
} else {
details.forEach((detail, index) => {
const detailImages = Array.isArray(detailImageMap.get(String(detail.id)))
? detailImageMap.get(String(detail.id))
: [];
const detailImageUrls = detailImages
.map(item => (item && (item.url || item.file_url || (item.file && item.file.file_url))) || '')
.filter(Boolean);
const imageSlotCount = Math.max(detailImageUrls.length, 1);
const linkCell = buildLinkCell(detailImageUrls);
const rowCells = [
index + 1,
detail.product_name || '',
detail.barcode || '',
detail.actual_quantity || 0,
detail.weight || 0,
detail.box_quantity || 0,
detail.pallet_quantity || 0,
detail.batch_number || '',
this.formatReportDate(detail.production_date),
this.formatReportDate(detail.expiry_date),
detail.remark || '',
linkCell,
...Array(imageSlotCount).fill(''),
];
const targetRow = pushReportRow(rowCells, {
toCol: rowCells.length,
height: detailImageUrls.length > 0 ? 88 : null,
style: {
alignment: { vertical: 'top', wrapText: true },
},
});
detailImageUrls.forEach((imageUrl, imageIndex) => {
embeddedImages.push({
row: targetRow,
col: detailImageColumnIndex + imageIndex,
url: imageUrl,
width: 96,
height: 96,
fallbackText: `图片${imageIndex + 1}`,
});
});
});
}
return [
{
name: '收货清单',
rows,
widths: [
16, 28, 18, 10, 10, 10, 10, 18, 18, 18, 24, 42, 18,
...Array(Math.max(maxDetailImageCount - 1, 0)).fill(18),
],
embeddedImages,
styledRows,
skipHeader: true,
forceExcelJs: true,
},
];
}
async uploadCompletionExcelReport({
receiving,
operator = {},
stats = {},
detailImageMap = new Map(),
receivingImages = [],
}) {
const { ctx } = this;
const excelService = ctx && ctx.service && ctx.service.systems && ctx.service.systems.excel;
if (!receiving || !receiving.id || !excelService || typeof excelService.generateAndUpload !== 'function') {
return null;
}
const receivingNumber = String(receiving.receiving_number || receiving.id).replace(/[\\/:*?"<>|]/g, '_');
return await excelService.generateAndUpload({
filename: `收货明细(已完成收货)_${receivingNumber}.xlsx`,
dir: `exports/receiving/completed/${ctx.user.store_id || receiving.warehouse_id || 'common'}`,
category: 'document',
saveRecord: true,
businessType: 'receivingReport',
businessId: receiving.id,
expireDays: 90,
sheets: this.buildCompletionReportSheets({
receiving,
operator,
stats,
detailImageMap,
receivingImages,
}),
});
}
/**
* 发送收货完成统一通知,通知外部订阅 `receiving_completed` 事件。
* @param {Object} options 通知参数
* @param {Object} options.receiving 收货单快照
* @param {Object} [options.operator={}] 操作人信息
* @param {Object} [options.stats={}] 收货统计
* @param {Object|null} [options.completionReport=null] 完成报表信息
* @return {Promise<Object|null>} 通知发送结果,若条件不满足则返回 null
*/
async sendCompletionNotice({
receiving,
operator = {},
stats = {},
completionReport = null,
} = {}) {
const { ctx } = this;
const rawNoticeService = ctx && ctx.service && ctx.service.systems && ctx.service.systems.notice;
const noticeService = rawNoticeService && typeof rawNoticeService.send === 'function'
? rawNoticeService
: (rawNoticeService && rawNoticeService.index && typeof rawNoticeService.index.send === 'function'
? rawNoticeService.index
: null);
if (!receiving || !receiving.id || !noticeService) {
return null;
}
const warehouseId = Number(receiving.warehouse_id || (ctx.user && ctx.user.store_id) || 0);
if (!Number.isFinite(warehouseId) || warehouseId <= 0) {
return null;
}
const storeId = Number(receiving.store_id || 0);
const matchedDetails = Number(stats.matched_details || 0);
const unmatchedDetails = Number(stats.unmatched_details || 0);
const totalQuantity = Number(stats.total_quantity || 0);
const operatorName = String(operator.employees_name || operator.real_name || operator.name || '').trim();
const receivingNumber = String(receiving.receiving_number || receiving.id || '').trim() || String(receiving.id);
const reportUrl = String(
(completionReport && (completionReport.url || completionReport.cdnUrl || completionReport.cosUrl || completionReport.fileUrl)) || ''
).trim();
const reportFileName = String(
(completionReport && (completionReport.filename || completionReport.fileKey || completionReport.key)) || `收货完成_${receivingNumber}.xlsx`
).trim();
const detailItems = Array.isArray(receiving.details) ? receiving.details : [];
const normalizedDetails = detailItems.map(item => ({
id: Number(item.id || 0),
product_name: item.product_name || '',
barcode: item.barcode || '',
actual_quantity: Number(item.actual_quantity || 0),
box_quantity: Number(item.box_quantity || 0),
pallet_quantity: Number(item.pallet_quantity || 0),
box_remainder: Number(item.box_remainder || 0),
box_weight: Number(item.box_weight || 0),
weight: Number(item.weight || 0),
}));
const totalBoxRemainder = normalizedDetails.reduce((sum, item) => sum + Number(item.box_remainder || 0), 0);
const totalBoxWeight = normalizedDetails.reduce((sum, item) => sum + Number(item.box_weight || 0), 0);
const title = `收货单${receivingNumber}已完成`;
const contactLines = this.getCompletionContactFields(receiving).map(([ field, value ]) => `${field}:${value || '无'}`);
const content = [
`收货单号:${receivingNumber} 已完成`,
`货主:${receiving.store_name || '未知'}`,
`来货方式:${this.formatDeliveryMethod(receiving.delivery_method) || '未知'}`,
...contactLines,
`总明细数:${Number(stats.total_details || 0)}件`,
`匹配商品:${matchedDetails}件`,
`未匹配商品:${unmatchedDetails}件`,
`总数量:${totalQuantity}`,
`总箱数:${receiving.total_boxes || 0}`,
`总箱余数:${totalBoxRemainder}`,
`总箱重:${totalBoxWeight}`,
`总托盘数:${receiving.total_pallets || 0}`,
operatorName ? `完成人:${operatorName}` : '',
`开始时间:${this.formatReportDate(receiving.created_at)}`,
`完成时间:${this.formatReportDate(receiving.receiving_end_time)}`,
`备注:${receiving.remark || '无'}`,
`快速查看:${ctx.app.config.frontendUrl || ''}/storage/receiving?id=${receivingNumber}`, // 替换为实际的前端地址
].filter(Boolean).join('\n') + '。';
return await noticeService.send({
warehouseId,
storeId: Number.isFinite(storeId) && storeId > 0 ? storeId : undefined,
messageType: reportUrl ? 'file' : 'text',
businessName: 'receiving',
event: 'receiving_completed',
title,
content,
url: reportUrl || undefined,
fileName: reportUrl ? reportFileName : '',
mimeType: reportUrl ? 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' : '',
businessId: receiving.id,
subject: {
id: warehouseId,
type: 'warehouse',
name: String((ctx.user && (ctx.user.store_name || ctx.user.company_name)) || ''),
},
sender: {
id: operator.employees_id || operator.id || null,
name: operatorName,
},
metadata: {
receivingId: receiving.id,
receivingNumber,
warehouseId,
storeId: Number.isFinite(storeId) && storeId > 0 ? storeId : null,
stats: {
total_details: Number(stats.total_details || 0),
matched_details: matchedDetails,
unmatched_details: unmatchedDetails,
total_quantity: totalQuantity,
},
details: normalizedDetails,
boxSummary: {
total_box_remainder: totalBoxRemainder,
total_box_weight: totalBoxWeight,
},
completionReport: completionReport ? {
fileKey: completionReport.fileKey || completionReport.key || '',
url: reportUrl,
} : null,
},
});
}
/**
* 完成收货单:校验明细、更新状态并写入库存。
* @param {Object} data 请求体
* @param {number} data.id 收货单ID
* @param {string} [data.remark] 完成备注
* @return {Promise<Object>} 完成结果
*/
async completeReceiving(data) {
const { ctx, app } = this;
const warehouseId = ctx.user.store_id;
const { id, remark } = data;
const { Op } = app.Sequelize;
const transaction = await ctx.model.transaction();
try {
// 1. 查询收货单并加锁
const receiving = await ctx.model.Receiving.findOne({
where: {
id,
warehouse_id: warehouseId,
is_deleted: false,
},
lock: transaction.LOCK.UPDATE,
transaction,
include: [{
model: ctx.model.ReceivingDetail,
as: 'details',
required: false,
attributes: [
'id', 'system_product_id', 'product_name', 'barcode', 'actual_quantity', 'weight',
'box_quantity', 'pallet_quantity', 'box_remainder', 'box_weight',
'receiving_status', 'storage_status',
'batch_number', 'production_date', 'expiry_date', 'remark',
],
include: [{
model: ctx.model.StockWarehouse,
as: 'system_product',
required: false,
attributes: [
'id',
'item_name',
'item_code',
'is_batch_mgmt',
'is_shelf_life_mgmt',
'inbound_min_days',
'shelf_life_days',
'remaining_threshold_days',
],
}],
}],
});
if (!receiving) {
await transaction.rollback();
return {
code: 404,
message: '收货单不存在或已被删除',
};
}
// 2. 状态检查
if (receiving.status === 'completed') {
await transaction.rollback();
return {
code: 200,
message: '收货单已完成',
};
}
if (receiving.status === 'cancelled') {
await transaction.rollback();
return {
code: 400,
message: '已作废的收货单不可完成',
};
}
// 3. 检查是否有明细
if (!receiving.details || receiving.details.length === 0) {
await transaction.rollback();
return {
code: 400,
message: '收货单没有明细,请先添加商品',
};
}
// 4. 校验明细数量:不允许存在数量为 0 的明细
const zeroQuantityDetails = receiving.details.filter(d => Number(d.actual_quantity || 0) <= 0);
if (zeroQuantityDetails.length > 0) {
await transaction.rollback();
const errorMsg = zeroQuantityDetails.length === 1
? `商品“${zeroQuantityDetails[0].product_name || '未命名商品'}”的数量为0,请填写实际收货数量`
: `有${zeroQuantityDetails.length}个商品数量为0,请填写实际收货数量`;
return {
success: false,
code: 'DETAIL_QUANTITY_ZERO',
message: errorMsg,
data: {
invalid_details: zeroQuantityDetails.map(d => ({
detail_id: d.id,
item_name: d.product_name || '未命名商品',
actual_quantity: Number(d.actual_quantity || 0),
})),
},
};
}
const batchManagedDetails = receiving.details.filter(detail => detail.system_product && detail.system_product.is_batch_mgmt === 'Y');
const missingBatchNumberDetails = batchManagedDetails.filter(detail => !String(detail.batch_number || '').trim());
if (missingBatchNumberDetails.length > 0) {
await transaction.rollback();
return {
success: false,
code: 'BATCH_NUMBER_REQUIRED',
message: '批次管理商品必须填写批次号',
data: {
invalid_details: missingBatchNumberDetails.map(detail => ({
detail_id: detail.id,
item_name: detail.product_name || detail.system_product?.item_name || '未命名商品',
batch_number: detail.batch_number || '',
production_date: detail.production_date || null,
expiry_date: detail.expiry_date || null,
})),
},
};
}
const missingBatchDetails = batchManagedDetails.filter(detail => !detail.production_date || !detail.expiry_date);
if (missingBatchDetails.length > 0) {
await transaction.rollback();
return {
success: false,
code: 'PRODUCTION_DATE_REQUIRED',
message: '批次管理商品必须填写生产日期和有效期',
data: {
invalid_details: missingBatchDetails.map(detail => ({
detail_id: detail.id,
item_name: detail.product_name || detail.system_product?.item_name || '未命名商品',
batch_number: detail.batch_number || '',
production_date: detail.production_date || null,
expiry_date: detail.expiry_date || null,
})),
},
};
}
const todayStartMs = getStartOfDayMs(new Date());
const invalidExpiryDetails = batchManagedDetails.filter(detail => {
const minReceiveDays = Number(detail.system_product?.inbound_min_days) || 0;
if (minReceiveDays <= 0) return false;
const expiryTime = new Date(detail.expiry_date).getTime();
if (Number.isNaN(expiryTime)) return false;
return (expiryTime - (minReceiveDays * DAY_MS)) < todayStartMs;
});
if (invalidExpiryDetails.length > 0) {
await transaction.rollback();
const firstInvalid = invalidExpiryDetails[0];
const minReceiveDays = Number(firstInvalid.system_product?.inbound_min_days) || 0;
return {
success: false,
code: 'EXPIRY_DATE_TOO_SOON',
message: `商品“${firstInvalid.product_name || firstInvalid.system_product?.item_name || '未命名商品'}”的有效期不足最小允许收货天数(${minReceiveDays}天),无法完成收货`,
data: {
invalid_details: invalidExpiryDetails.map(detail => ({
detail_id: detail.id,
item_name: detail.product_name || detail.system_product?.item_name || '未命名商品',
batch_number: detail.batch_number || '',
production_date: detail.production_date || null,
expiry_date: detail.expiry_date || null,
inbound_min_days: Number(detail.system_product?.inbound_min_days) || 0,
})),
},
};
}
// 5. 准备明细图片与统计信息(照片/条码/重量不再强制要求)
const unmatchedDetails = receiving.details.filter(d => !d.system_product_id);
const detailsIds = receiving.details.map(item => item.id);
const images = await ctx.model.FileReference.findAll({
where: {
business_type: 'receivingItem',
business_id: {
[Op.in]: detailsIds,
},
warehouse_id: warehouseId,
},
include: [{
model: ctx.model.File,
as: 'file',
attributes: [ 'file_url' ],
required: false,
}],
transaction,
});
const imageMap = new Map();
images.forEach(image => {
const businessId = String(image.business_id).trim();
if (!imageMap.has(businessId)) {
imageMap.set(businessId, []);
}
imageMap.get(businessId).push({
id: image.file_id,
url: (image.file && image.file.file_url) || image.file_url || image.url || image.file_path || '',
});
});
// 5. 获取操作人信息
const operator = ctx.user;
// 8. 更新收货单状态
const now = new Date();
const updateData = {
status: 'completed',
receiving_end_time: now,
updated_at: now,
};
if (remark) {
const remarkPrefix = receiving.remark ? `${receiving.remark}\n` : '';
updateData.remark = `${remarkPrefix}【完成收货】${now.toLocaleString()} ${operator.employees_name} ${remark}`;
} else {
const remarkPrefix = receiving.remark ? `${receiving.remark}\n` : '';
updateData.remark = `${remarkPrefix}【完成收货】${now.toLocaleString()} ${operator.employees_name}`;
}
await ctx.model.Receiving.update(updateData, {
where: { id },
transaction,
});
// 9. 记录统计信息
const stats = {
total_details: receiving.details.length,
matched_details: receiving.details.filter(d => d.system_product_id).length,
unmatched_details: unmatchedDetails.length,
total_quantity: receiving.details.reduce((sum, d) => sum + (d.actual_quantity || 0), 0),
};
// 10. 提交事务
await transaction.commit();
// 10.1 清除收货单缓存,确保下次入库完成时匹配到最新收货单列表
const receivingCacheKey = `cache:receiving_orders:warehouse:${warehouseId}`;
app.delCacheAsync(receivingCacheKey).catch(cacheErr => {
ctx.logger.warn(`[receiving.completeReceiving] 清除收货单缓存失败: ${cacheErr.message}`, { cacheKey: receivingCacheKey });
});
// 记录操作日志
try {
await ctx.service.systems.operationLog.createOperationLog({
businessType: 'receiving',
businessId: id,
operationCode: 'RECEIVING_COMPLETE',
operator: {
id: ctx.user?.employees_id || ctx.user?.id,
name: ctx.user?.employees_name || '',
},
extras: {
warehouseId,
},
beforeChanges: {
previous_status: receiving.status,
stats,
},
});
} catch (logErr) {
ctx.logger.warn('[receiving.completeReceiving] 写入操作日志失败,不影响业务', logErr);
}
const receivingSnapshot = {
...(typeof receiving.toJSON === 'function' ? receiving.toJSON() : receiving),
...updateData,
};
const completionNoticePayload = {
receiving: receivingSnapshot,
operator,
stats,
};
// 11. 收货成功后先触发文字通知,再生成 Excel;若 Excel 成功,再补发文件通知。
try {
const textNoticeResult = await this.sendCompletionNotice(completionNoticePayload);
ctx.logger.info('收货完成文字通知结果', {
receiving_id: id,
receiving_number: receiving.receiving_number,
warehouseId,
success: !!(textNoticeResult && textNoticeResult.success),
message: textNoticeResult && textNoticeResult.message,
matchedHookCount: Number(textNoticeResult && textNoticeResult.data && textNoticeResult.data.matchedHookCount || 0),
sentCount: Number(textNoticeResult && textNoticeResult.data && textNoticeResult.data.sentCount || 0),
failedCount: Number(textNoticeResult && textNoticeResult.data && textNoticeResult.data.failedCount || 0),
});
} catch (notifyError) {
ctx.logger.error(`收货完成文字通知发送失败: ${notifyError.message}`, {
receiving_id: id,
warehouseId,
error: notifyError.stack,
});
}
ctx.logger.info('收货单已完成', {
receiving_id: id,
receiving_number: receiving.receiving_number,
completed_by: operator.employees_name,
stats,
});
// 异步补全商品图片与毛重,不阻塞主进程
this._syncProductDataFromReceiving({
receivingId: id,
warehouseId,
details: receiving.details,
}).catch(err => {
ctx.logger.warn('[receiving._syncProductDataFromReceiving] 异步补全失败,不影响业务', err.message);
});
return {
success: true,
code: 200,
message: '收货完成成功',
data: {
receiving_id: id,
receiving_number: receiving.receiving_number,
completed_at: now,
completed_by: operator.employees_name,
stats,
completion_report: null,
},
};
} catch (error) {
if (transaction && !transaction.finished) {
await transaction.rollback();
}
ctx.logger.error(`完成收货失败: ${error.message}`, {
receiving_id: id,
warehouseId,
error: error.stack,
});
if (error.code && error.code.startsWith('DETAIL_')) {
return {
success: false,
code: error.code,
message: error.message,
};
}
return {
success: false,
code: 'SYSTEM_ERROR',
message: error.message || '系统错误,请稍后重试',
};
}
}
/**
* 收货完成后异步补全商品资料:绑定图片、补填毛重。
*
* 遍历当前收货单所有已绑定系统商品的明细:
* 1. 若商品 is_images === 'N' 且该明细有收货图片,则将收货图片复制为商品图片(FileReference),
* 并将商品的 is_images 更新为 'Y'。
* 2. 若商品 gross_weight 为 0 或 null,且明细的 weight > 0,则将商品毛重更新为该明细的 weight。
*
* 本方法通过 setImmediate 调用,运行在事务提交后,任何异常只记录日志,不影响主进程。
*
* @param {Object} options 参数对象
* @param {number} options.receivingId 收货单 ID
* @param {number} options.warehouseId 仓库 ID
* @param {Array} options.details 收货明细数组(来自 completeReceiving 中已加载的 details)
* @return {Promise<void>}
*/
async _syncProductDataFromReceiving({ receivingId, warehouseId, details }) {
console.log('_syncProductDataFromReceiving异步执行中...'); // 调试日志
const { ctx, app } = this;
// 只处理已绑定系统商品的明细
const boundDetails = (Array.isArray(details) ? details : []).filter(
d => d && Number(d.system_product_id) > 0
);
if (boundDetails.length === 0) return;
for (const detail of boundDetails) {
const systemProductId = Number(detail.system_product_id);
try {
// -------- 查询当前商品资料 --------
const stock = await app.model.StockWarehouse.findOne({
where: {
id: systemProductId,
warehouse_id: warehouseId,
deleted_at: null,
},
attributes: [ 'id', 'is_images', 'gross_weight' ],
raw: true,
});
if (!stock) continue;
// 查询该明细是否有收货图片
const detailImageRefs = await app.model.FileReference.findAll({
where: {
business_type: 'receivingItem',
business_id: String(detail.id),
warehouse_id: warehouseId,
},
attributes: [ 'file_id' ],
raw: true,
});
if (detailImageRefs.length > 0) {
// 查询商品已有的图片 file_id(避免重复)
const existingStockImageFileIds = await app.model.FileReference.findAll({
where: {
business_type: 'stock',
business_id: String(systemProductId),
warehouse_id: warehouseId,
},
attributes: [ 'file_id' ],
raw: true,
}).then(rows => rows.map(r => r.file_id));
const toCreate = detailImageRefs
.filter(ref => !existingStockImageFileIds.includes(ref.file_id))
.map(ref => ({
file_id: ref.file_id,
business_type: 'stock',
business_id: String(systemProductId),
warehouse_id: warehouseId,
display_order: 0,
created_by: 'system',
created_at: new Date(),
}));
if (toCreate.length > 0) {
await app.model.FileReference.bulkCreate(toCreate, { ignoreDuplicates: true });
}
// 更新商品 is_images 标记
await app.model.StockWarehouse.update(
{ is_images: 'Y' },
{ where: { id: systemProductId } }
);
ctx.logger.info(
`[_syncProductDataFromReceiving] 商品 ${systemProductId} 已补全图片,共复制 ${toCreate.length} 张(收货单 ${receivingId} 明细 ${detail.id})`
);
}
// -------- 2. 毛重补全 --------
const currentWeight = parseFloat(stock.gross_weight) || 0;
const detailWeight = parseFloat(detail.weight) || 0;
if (currentWeight <= 0 && detailWeight > 0) {
await app.model.StockWarehouse.update(
{ gross_weight: detailWeight },
{ where: { id: systemProductId } }
);
ctx.logger.info(
`[_syncProductDataFromReceiving] 商品 ${systemProductId} 已补全毛重 ${detailWeight}(收货单 ${receivingId} 明细 ${detail.id})`
);
}
} catch (err) {
// 单条明细失败不中断后续处理
console.log(
`[_syncProductDataFromReceiving] 处理明细 ${detail.id} (商品 ${systemProductId}) 失败: ${err.message}`
);
}
}
}
/**
* PDA 扫码定位收货明细:通过入库单ID + 扫描条码快速定位收货明细。
* 搜索策略:
* 1. 通过 entry_order_id → wms_entry_order_receiving 查出关联的 receiving_id 列表;
* 2. 查出所有未绑定的收货明细(仅按 receiving_id IN + 排除已绑定过滤);
* 3. 收集明细的 system_product_id,批量调用 getStockDetails 获取条码信息;
* 4. 在内存中遍历明细进行精确匹配:
* - 若 barcode 为纯数字,优先按明细 ID 精确匹配;
* - 再按 getStockDetails 返回的 barcodes[].barcode 精确匹配商品条码;
* 5. 返回所有匹配的明细列表(同一条码可能匹配到多条收货明细)。
* @param {number} entryOrderId 入库单ID
* @param {string} barcode 扫描条码(商品条码/箱唛/托盘唛/明细ID)
* @return {Promise<Object>} 包含 code、message 与匹配明细列表 data.list 的结果对象
*/
async scanDetail(entryOrderId, barcode) {
const { ctx, app } = this;
const { Op } = app.Sequelize;
const warehouseId = ctx.user?.store_id;
// 参数校验
if (!warehouseId) {
return { code: 0, message: '用户未绑定仓库', data: null };
}
if (!entryOrderId || Number(entryOrderId) <= 0) {
return { code: 0, message: '入库单ID不能为空', data: null };
}
if (!barcode || String(barcode).trim() === '') {
return { code: 0, message: '扫描条码不能为空', data: null };
}
const normalizedBarcode = String(barcode).trim();
const normalizedEntryOrderId = Number(entryOrderId);
try {
// 1. 验证入库单存在且属于当前仓库
const entryOrder = await ctx.model.EntryOrder.findOne({
where: {
id: normalizedEntryOrderId,
warehouse_id: warehouseId,
},
attributes: [ 'id' ],
raw: true,
});
if (!entryOrder) {
return { code: 0, message: '入库单不存在或无权访问', data: null };
}
// 2. 通过 wms_entry_order_receiving 查出关联的 receiving_id 列表
const entryReceivingRows = await ctx.model.EntryOrderReceiving.findAll({
where: { entry_order_id: normalizedEntryOrderId },
attributes: [ 'receiving_id' ],
raw: true,
});
const receivingIds = entryReceivingRows.map(r => r.receiving_id).filter(Boolean);
if (receivingIds.length === 0) {
return { code: 0, message: '该入库单尚未关联收货单', data: null };
}
// 校验所有 receiving 属于当前仓库
const validReceivings = await ctx.model.Receiving.findAll({
where: { id: { [Op.in]: receivingIds }, warehouse_id: warehouseId },
attributes: [ 'id' ],
raw: true,
});
const validReceivingIds = validReceivings.map(r => r.id);
if (validReceivingIds.length === 0) {
return { code: 1, message: '收货单不存在或不属于当前仓库', list: [], total: 0 };
}
// 2.5 获取入库单的所有合法 stock_id(用于校验收货明细的 system_product_id)
const entryItems = await ctx.model.EntryItems.findAll({
where: { order_id: normalizedEntryOrderId },
attributes: [ 'stock_id' ],
raw: true,
});
const validStockIds = [ ...new Set(entryItems.map(ei => ei.stock_id).filter(Boolean)) ];
if (validStockIds.length === 0) {
return { code: 0, message: '入库单无明细,无法匹配收货明细', data: null };
}
// 排除已绑定的收货明细(wms_inbound_direct_log 中有记录且未软删除)
const notBoundCondition = app.Sequelize.literal(
'NOT EXISTS (SELECT 1 FROM wms_inbound_direct_log erb WHERE erb.receiving_detail_id = wms_receiving_detail.id AND erb.deleted_at IS NULL)'
);
// 3. 查出所有未绑定的收货明细(不再在 SQL 层做 barcode 模糊匹配)
const details = await ctx.model.ReceivingDetail.findAll({
where: {
[Op.and]: [
{ receiving_id: { [Op.in]: validReceivingIds } },
{ system_product_id: { [Op.in]: validStockIds } },
notBoundCondition,
],
},
raw: true,
});
if (details.length === 0) {
return { code: 0, message: '未找到可用的收货明细', data: null };
}
// 4. 收集所有明细的 system_product_id,批量调用 getStockDetails 获取条码
const stockIdSet = new Set();
for (const d of details) {
if (d.system_product_id != null) {
stockIdSet.add(Number(d.system_product_id));
}
}
const stockIds = [ ...stockIdSet ];
/** @type {Map<number, Object>} */
const stockDetailMap = new Map();
if (stockIds.length > 0) {
const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails(stockIds, { warehouseId });
for (const sd of stockDetails) {
if (sd && sd.id != null) {
stockDetailMap.set(sd.id, sd);
}
}
}
// 5. 在内存中遍历明细,精确匹配,收集所有命中
const isNumericBarcode = /^\d+$/.test(normalizedBarcode);
const matchedDetails = [];
for (const detail of details) {
// 优先按明细 ID 精确匹配(托盘唛头场景)
if (isNumericBarcode && detail.id === Number(normalizedBarcode)) {
const sd = stockDetailMap.get(Number(detail.system_product_id));
if (sd) {
matchedDetails.push(detail);
}
continue;
}
// 按商品条码精确匹配
const stockDetail = stockDetailMap.get(detail.system_product_id);
if (stockDetail && Array.isArray(stockDetail.barcodes)) {
const barcodeMatch = stockDetail.barcodes.some(
bc => bc.barcode === normalizedBarcode
);
if (barcodeMatch) {
matchedDetails.push(detail);
}
}
}
if (matchedDetails.length === 0) {
return { code: 0, message: '未找到匹配的收货明细', data: null };
}
const list = matchedDetails.map(matchedDetail => {
const sd = stockDetailMap.get(Number(matchedDetail.system_product_id));
const stockBarcode = (sd && Array.isArray(sd.barcodes) && sd.barcodes.length > 0)
? (sd.barcodes[0].barcode || '')
: '';
return {
detail_id: matchedDetail.id,
receiving_id: matchedDetail.receiving_id,
barcode: stockBarcode || matchedDetail.barcode || '',
product_name: matchedDetail.product_name || '',
actual_quantity: matchedDetail.actual_quantity || 0,
receiving_status: matchedDetail.receiving_status || '',
stock: sd || null,
};
});
return {
code: 200,
message: '查询成功',
data: {
list,
total: list.length,
},
};
} catch (error) {
ctx.logger.error('[receiving.scanDetail] 扫码定位收货明细失败', error);
return { code: 500, message: `服务器错误: ${error.message}`, data: null };
}
}
/**
* 导出收货单列表(双 sheet:收货单列表 + 收货单明细)。
* 复用 getStoreReceivingList 的筛选与排序语义,分页拉取全量数据后生成 Excel 并上传。
* @param {Object} options 导出选项
* @param {Object} [options.where] 筛选条件
* @param {number} options.storeId 货主ID
* @param {Object} [options.sort] 排序参数
* @param {Function} [options.onProgress] 进度回调
* @return {Promise<Object>} 上传结果与统计信息
*/
async exportReceivingList(options = {}) {
const { ctx, app } = this;
const { Sequelize } = app;
const { Op } = Sequelize;
const safeOptions = options && typeof options === 'object' ? options : {};
const where = safeOptions.where && typeof safeOptions.where === 'object' ? { ...safeOptions.where } : {};
const warehouseId = Number(ctx.user && ctx.user.store_id);
const sort = safeOptions.sort && typeof safeOptions.sort === 'object' ? { ...safeOptions.sort } : {};
const progressHandler = typeof safeOptions.onProgress === 'function'
? safeOptions.onProgress
: async () => {};
if (!warehouseId) {
throw new Error('用户未绑定仓库,无法导出');
}
const sortField = sort.sortField || 'created_at';
const sortOrder = String(sort.sortOrder || 'DESC').toUpperCase() === 'ASC' ? 'ASC' : 'DESC';
const validSortFields = [
'id', 'receiving_number', 'status', 'created_at', 'updated_at', 'store_id', 'warehouse_id',
];
const actualSortField = validSortFields.includes(sortField) ? sortField : 'created_at';
// 构建 where 条件(与 getReceivingList 一致,按仓库维度)
const queryOptions = {
where: { [Op.and]: [{ warehouse_id: warehouseId }] },
};
const normalizedWhere = { ...where };
let parsedResult = ctx.whereParsed;
if (!parsedResult || !Array.isArray(parsedResult.dynamicConditions)) {
const parsed = parseWhereConditions({
where: normalizedWhere,
app,
specialFieldMap: {
quickWhere: { bucket: 'quick' },
},
});
if (!parsed.ok) {
throw new Error(`筛选条件解析失败: ${parsed.reason}`);
}
parsedResult = parsed.result;
}
const dynamicConditions = [ ...(parsedResult.dynamicConditions || []) ];
const quickWhereRaw = (parsedResult.rawConditionsByField && parsedResult.rawConditionsByField.quickWhere)
|| normalizedWhere.quickWhere;
if (quickWhereRaw && quickWhereRaw.value && String(quickWhereRaw.value).trim() !== '') {
const quickValue = String(quickWhereRaw.value).trim();
dynamicConditions.push({
[Op.or]: {
store_name: { [Op.like]: `%${quickValue}%` },
receiving_number: { [Op.like]: `%${quickValue}%` },
tracking_number: { [Op.like]: `%${quickValue}%` },
creator_snapshot: { [Op.like]: `%${quickValue}%` },
license_plate: { [Op.like]: `%${quickValue}%` },
},
});
}
if (dynamicConditions.length > 0) {
queryOptions.where[Op.and].push({ [Op.and]: dynamicConditions });
}
// ---- 分页拉取收货单列表 ----
const totalCount = await ctx.model.Receiving.count({
where: queryOptions.where,
distinct: true,
});
await progressHandler({
status: 'running',
progress: totalCount > 0 ? 10 : 85,
message: totalCount > 0 ? `已命中 ${totalCount} 条收货单,开始导出` : '未命中数据,开始生成空文件',
});
const allReceivingOrders = [];
let page = 1;
let fetchedCount = 0;
while (fetchedCount < totalCount) {
const rows = await ctx.model.Receiving.findAll({
where: queryOptions.where,
order: [[ actualSortField, sortOrder ]],
limit: RECEIVING_EXPORT_PAGE_SIZE,
offset: (page - 1) * RECEIVING_EXPORT_PAGE_SIZE,
raw: true,
});
if (!Array.isArray(rows) || rows.length === 0) {
break;
}
allReceivingOrders.push(...rows);
fetchedCount += rows.length;
page += 1;
await progressHandler({
status: 'running',
progress: Math.min(30, 10 + Math.round((fetchedCount / Math.max(totalCount, 1)) * 20)),
message: `正在拉取收货单列表,已完成 ${fetchedCount}/${totalCount}`,
});
}
// ---- 批量拉取收货单明细 ----
const allReceivingIds = allReceivingOrders.map(r => Number(r.id)).filter(Boolean);
/** @type {Map<number, Array<Object>>} receiving_id → details */
const detailsMap = new Map();
if (allReceivingIds.length > 0) {
const batchSize = RECEIVING_ITEMS_FETCH_BATCH_SIZE;
const totalBatches = Math.ceil(allReceivingIds.length / batchSize);
for (let batchIdx = 0; batchIdx < allReceivingIds.length; batchIdx += batchSize) {
const batchIds = allReceivingIds.slice(batchIdx, batchIdx + batchSize);
const details = await ctx.model.ReceivingDetail.findAll({
where: { receiving_id: { [Op.in]: batchIds } },
order: [[ 'receiving_id', 'ASC' ], [ 'id', 'ASC' ]],
raw: true,
});
for (const detail of details) {
const rid = Number(detail.receiving_id);
if (!detailsMap.has(rid)) {
detailsMap.set(rid, []);
}
detailsMap.get(rid).push(detail);
}
const currentBatch = Math.floor(batchIdx / batchSize) + 1;
await progressHandler({
status: 'running',
progress: Math.min(50, 30 + Math.round((currentBatch / totalBatches) * 20)),
message: `正在拉取收货单明细,已完成批次 ${currentBatch}/${totalBatches}`,
});
}
}
await progressHandler({
status: 'running',
progress: 55,
message: '正在生成 Excel 文件...',
});
// ---- 生成 Excel(流式写入,两个 Sheet) ----
const tempDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'wms-receiving-export-'));
const now = new Date();
const dateToken = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}${String(now.getSeconds()).padStart(2, '0')}`;
const filename = `收货单导出_${dateToken}.xlsx`;
const filePath = path.join(tempDir, filename);
const workbook = new ExcelJS.stream.xlsx.WorkbookWriter({
filename: filePath,
useStyles: false,
useSharedStrings: false,
});
const normalizeCellValue = value => {
if (value === null || value === undefined) return '';
if (value instanceof Date) return app.formatDate ? app.formatDate(value) : value.toISOString();
return value;
};
const statusLabelMap = {
receiving: '收货中',
completed: '已完成',
cancelled: '已作废',
};
const detailStatusLabelMap = {
all_matched: '全部匹配',
partial_matched: '部分匹配',
unmatched: '未匹配',
};
const storageStatusLabelMap = {
none: '未入库',
waiting: '等待入库',
partial: '部分入库',
all: '全部入库',
};
const deliveryMethodLabelMap = {
truck: '货车',
express: '快递',
air_freight: '空运',
sea_freight: '海运',
other: '其他',
};
const loadingMethodLabelMap = {
with_pallet: '带托盘',
without_pallet: '不带托盘',
};
// Sheet 1: 收货单列表
const sheet1 = workbook.addWorksheet('收货单列表');
const receivingColumns = [
{ header: '收货单ID', key: 'id', width: 10 },
{ header: '收货单号', key: 'receiving_number', width: 22 },
{ header: '货主', key: 'store_name', width: 20 },
{ header: '收货状态', key: 'status_label', width: 12 },
{ header: '明细匹配状态', key: 'detail_status_label', width: 14 },
{ header: '入库状态', key: 'storage_status_label', width: 12 },
{ header: '来货方式', key: 'delivery_method_label', width: 12 },
{ header: '车牌号', key: 'license_plate', width: 14 },
{ header: '快递单号', key: 'tracking_number', width: 22 },
{ header: '装卸方式', key: 'loading_method_label', width: 12 },
{ header: '总商品种类', key: 'total_items', width: 12 },
{ header: '总数量', key: 'total_quantity', width: 12 },
{ header: '总箱数', key: 'total_boxes', width: 10 },
{ header: '总托盘数', key: 'total_pallets', width: 10 },
{ header: '审核状态', key: 'is_review_label', width: 10 },
{ header: '创建人', key: 'creator_name', width: 14 },
{ header: '备注', key: 'remark', width: 30 },
{ header: '收货开始时间', key: 'receiving_start_time', width: 20 },
{ header: '收货结束时间', key: 'receiving_end_time', width: 20 },
{ header: '创建时间', key: 'created_at', width: 20 },
{ header: '更新时间', key: 'updated_at', width: 20 },
];
sheet1.columns = receivingColumns;
for (const row of allReceivingOrders) {
let creatorName = '';
try {
if (row.creator_snapshot) {
const snapshot = JSON.parse(row.creator_snapshot);
creatorName = snapshot.name || '';
}
} catch (_) { /* ignore */ }
sheet1.addRow({
id: row.id,
receiving_number: normalizeCellValue(row.receiving_number),
store_name: normalizeCellValue(row.store_name),
status_label: statusLabelMap[row.status] || row.status || '',
detail_status_label: detailStatusLabelMap[row.detail_status] || row.detail_status || '',
storage_status_label: storageStatusLabelMap[row.storage_status] || row.storage_status || '',
delivery_method_label: deliveryMethodLabelMap[row.delivery_method] || row.delivery_method || '',
license_plate: normalizeCellValue(row.license_plate),
tracking_number: normalizeCellValue(row.tracking_number),
loading_method_label: loadingMethodLabelMap[row.loading_method] || row.loading_method || '',
total_items: row.total_items,
total_quantity: row.total_quantity,
total_boxes: row.total_boxes,
total_pallets: row.total_pallets,
is_review_label: row.is_review === 1 ? '已审核' : '未审核',
creator_name: creatorName,
remark: normalizeCellValue(row.remark),
receiving_start_time: normalizeCellValue(row.receiving_start_time),
receiving_end_time: normalizeCellValue(row.receiving_end_time),
created_at: normalizeCellValue(row.created_at),
updated_at: normalizeCellValue(row.updated_at),
}).commit();
}
sheet1.commit();
await progressHandler({
status: 'running',
progress: 70,
message: '正在写入收货单明细...',
});
// Sheet 2: 收货单明细
const sheet2 = workbook.addWorksheet('收货单明细');
const detailColumns = [
{ header: '收货单号', key: 'receiving_number', width: 22 },
{ header: '收货单ID', key: 'receiving_id', width: 12 },
{ header: '明细ID', key: 'detail_id', width: 10 },
{ header: '商品名称', key: 'product_name', width: 28 },
{ header: '商品条码', key: 'barcode', width: 20 },
{ header: '系统商品ID', key: 'system_product_id', width: 14 },
{ header: '实际收货数量', key: 'actual_quantity', width: 14 },
{ header: '箱数', key: 'box_quantity', width: 10 },
{ header: '托盘数', key: 'pallet_quantity', width: 10 },
{ header: '收货状态', key: 'receiving_status_label', width: 12 },
{ header: '入库状态', key: 'storage_status_label', width: 12 },
{ header: '已入库数量', key: 'stored_quantity', width: 12 },
{ header: '批次号', key: 'batch_number', width: 16 },
{ header: '生产日期', key: 'production_date', width: 14 },
{ header: '到期日期', key: 'expiry_date', width: 14 },
{ header: '备注', key: 'remark', width: 30 },
{ header: '创建时间', key: 'created_at', width: 20 },
];
sheet2.columns = detailColumns;
// 构建 receiving_number 映射
const receivingCodeMap = new Map();
for (const row of allReceivingOrders) {
receivingCodeMap.set(Number(row.id), row.receiving_number || '');
}
const detailReceivingStatusLabelMap = {
pending: '待收货',
receiving: '收货中',
completed: '已完成',
cancelled: '已作废',
};
const detailStorageStatusLabelMap = {
none: '未入库',
waiting: '等待入库',
partial: '部分入库',
all: '全部入库',
};
// 按收货单分页写入明细
const itemBatchSize = RECEIVING_ITEMS_FETCH_BATCH_SIZE;
let itemWrittenCount = 0;
const totalReceivingOrders = allReceivingIds.length;
for (let batchIdx = 0; batchIdx < allReceivingIds.length; batchIdx += itemBatchSize) {
const batchIds = allReceivingIds.slice(batchIdx, batchIdx + itemBatchSize);
for (const rid of batchIds) {
const receivingNumber = receivingCodeMap.get(rid) || '';
const details = detailsMap.get(rid) || [];
for (const detail of details) {
sheet2.addRow({
receiving_number: receivingNumber,
receiving_id: rid,
detail_id: detail.id,
product_name: normalizeCellValue(detail.product_name),
barcode: normalizeCellValue(detail.barcode),
system_product_id: normalizeCellValue(detail.system_product_id),
actual_quantity: detail.actual_quantity,
box_quantity: detail.box_quantity,
pallet_quantity: detail.pallet_quantity,
receiving_status_label: detailReceivingStatusLabelMap[detail.receiving_status] || detail.receiving_status || '',
storage_status_label: detailStorageStatusLabelMap[detail.storage_status] || detail.storage_status || '',
stored_quantity: detail.stored_quantity,
batch_number: normalizeCellValue(detail.batch_number),
production_date: normalizeCellValue(detail.production_date),
expiry_date: normalizeCellValue(detail.expiry_date),
remark: normalizeCellValue(detail.remark),
created_at: normalizeCellValue(detail.created_at),
}).commit();
}
itemWrittenCount += 1;
}
const currentBatch = Math.floor(batchIdx / itemBatchSize) + 1;
const totalBatches = Math.ceil(totalReceivingOrders / itemBatchSize);
await progressHandler({
status: 'running',
progress: Math.min(90, 70 + Math.round((currentBatch / totalBatches) * 20)),
message: `正在写入收货单明细,已完成 ${itemWrittenCount}/${totalReceivingOrders} 条收货单`,
});
}
sheet2.commit();
await workbook.commit();
await progressHandler({
status: 'running',
progress: 92,
message: '正在上传文件...',
});
// ---- 上传文件 ----
const uploadService = ctx?.service?.systems?.upload;
if (!uploadService || typeof uploadService.uploadFile !== 'function') {
throw new Error('上传服务不可用');
}
const stat = await fsp.stat(filePath);
const randomToken = crypto.randomBytes(6).toString('hex');
const uploadKey = `exports/receiving/${warehouseId}/${Date.now()}_${randomToken}.xlsx`;
const uploadStream = fs.createReadStream(filePath);
uploadStream.filename = filename;
uploadStream.mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
uploadStream.fileSize = stat.size;
const uploadResult = await uploadService.uploadFile(uploadStream, {
key: uploadKey,
category: 'document',
mimetype: 'xls,xlsx,csv',
});
let fileRecord = null;
if (typeof uploadService.uploadSuccessNotify === 'function') {
fileRecord = await uploadService.uploadSuccessNotify({
url: uploadResult.fileName,
fileKey: uploadResult.fileName,
fileName: filename,
fileType: 'document',
mimeType: uploadStream.mimeType,
fileSize: stat.size,
userId: ctx.userId,
description: `收货单导出(仓库${warehouseId}),共${totalCount}条收货单`,
});
}
// 清理临时文件
try { await fsp.rm(tempDir, { recursive: true, force: true }); } catch (_) { /* ignore */ }
const uploadInfo = fileRecord || uploadResult;
const fileUrl = typeof uploadInfo === 'object' && uploadInfo.url
? uploadInfo.url
: (typeof uploadResult === 'object' ? uploadResult.fileName : '');
await progressHandler({
status: 'running',
progress: 100,
message: '导出完成',
result: { url: fileUrl, fileKey: uploadKey, total: totalCount },
});
return {
url: fileUrl,
fileKey: uploadKey,
total: totalCount,
totalDetails: allReceivingIds.reduce((sum, rid) => sum + (detailsMap.get(rid) || []).length, 0),
};
}
/**
* 导出货主侧收货单列表(双 sheet:收货单列表 + 收货单明细)。
* 复用 getStoreReceivingList 的筛选与排序语义,以货主 store_id 过滤,分页拉取全量数据后生成 Excel 并上传。
* @param {Object} options 导出选项
* @param {Object} [options.where] 筛选条件(与 getStoreReceivingList 一致)
* @param {number} options.storeId 货主ID
* @param {Object} [options.sort] 排序参数
* @param {Function} [options.onProgress] 进度回调
* @return {Promise<Object>} 上传结果与统计信息
*/
async exportStoreReceivingList(options = {}) {
const { ctx, app } = this;
const { Sequelize } = app;
const { Op } = Sequelize;
const safeOptions = options && typeof options === 'object' ? options : {};
const where = safeOptions.where && typeof safeOptions.where === 'object' ? { ...safeOptions.where } : {};
const storeId = Number(safeOptions.storeId);
const sort = safeOptions.sort && typeof safeOptions.sort === 'object' ? { ...safeOptions.sort } : {};
const progressHandler = typeof safeOptions.onProgress === 'function'
? safeOptions.onProgress
: async () => {};
if (!storeId) {
throw new Error('货主ID不能为空,无法导出');
}
const sortField = sort.sortField || 'created_at';
const sortOrder = String(sort.sortOrder || 'DESC').toUpperCase() === 'ASC' ? 'ASC' : 'DESC';
const validSortFields = [
'id', 'receiving_number', 'status', 'created_at', 'updated_at', 'store_id', 'warehouse_id',
];
const actualSortField = validSortFields.includes(sortField) ? sortField : 'created_at';
// 构建 where 条件(与 getStoreReceivingList 一致,按货主维度)
const queryOptions = {
where: { [Op.and]: [{ store_id: storeId }] },
};
const normalizedWhere = { ...where };
let parsedResult = ctx.whereParsed;
if (!parsedResult || !Array.isArray(parsedResult.dynamicConditions)) {
const parsed = parseWhereConditions({
where: normalizedWhere,
app,
specialFieldMap: {
quickWhere: { bucket: 'quick' },
},
});
if (!parsed.ok) {
throw new Error(`筛选条件解析失败: ${parsed.reason}`);
}
parsedResult = parsed.result;
}
const dynamicConditions = [ ...(parsedResult.dynamicConditions || []) ];
const quickWhereRaw = (parsedResult.rawConditionsByField && parsedResult.rawConditionsByField.quickWhere)
|| normalizedWhere.quickWhere;
if (quickWhereRaw && quickWhereRaw.value && String(quickWhereRaw.value).trim() !== '') {
const quickValue = String(quickWhereRaw.value).trim();
dynamicConditions.push({
[Op.or]: {
store_name: { [Op.like]: `%${quickValue}%` },
receiving_number: { [Op.like]: `%${quickValue}%` },
tracking_number: { [Op.like]: `%${quickValue}%` },
creator_snapshot: { [Op.like]: `%${quickValue}%` },
license_plate: { [Op.like]: `%${quickValue}%` },
},
});
}
if (dynamicConditions.length > 0) {
queryOptions.where[Op.and].push({ [Op.and]: dynamicConditions });
}
// ---- 分页拉取收货单列表 ----
const RECEIVING_EXPORT_PAGE_SIZE = 200;
const RECEIVING_ITEMS_FETCH_BATCH_SIZE = 50;
const totalCount = await ctx.model.Receiving.count({
where: queryOptions.where,
distinct: true,
});
await progressHandler({
status: 'running',
progress: totalCount > 0 ? 10 : 85,
message: totalCount > 0 ? `已命中 ${totalCount} 条收货单,开始导出` : '未命中数据,开始生成空文件',
});
const allReceivingOrders = [];
let page = 1;
let fetchedCount = 0;
while (fetchedCount < totalCount) {
const rows = await ctx.model.Receiving.findAll({
where: queryOptions.where,
order: [[ actualSortField, sortOrder ]],
limit: RECEIVING_EXPORT_PAGE_SIZE,
offset: (page - 1) * RECEIVING_EXPORT_PAGE_SIZE,
raw: true,
});
if (!Array.isArray(rows) || rows.length === 0) {
break;
}
allReceivingOrders.push(...rows);
fetchedCount += rows.length;
page += 1;
await progressHandler({
status: 'running',
progress: Math.min(30, 10 + Math.round((fetchedCount / Math.max(totalCount, 1)) * 20)),
message: `正在拉取收货单列表,已完成 ${fetchedCount}/${totalCount}`,
});
}
// ---- 批量拉取收货单明细 ----
const allReceivingIds = allReceivingOrders.map(r => Number(r.id)).filter(Boolean);
/** @type {Map<number, Array<Object>>} receiving_id → details */
const detailsMap = new Map();
if (allReceivingIds.length > 0) {
const batchSize = RECEIVING_ITEMS_FETCH_BATCH_SIZE;
const totalBatches = Math.ceil(allReceivingIds.length / batchSize);
for (let batchIdx = 0; batchIdx < allReceivingIds.length; batchIdx += batchSize) {
const batchIds = allReceivingIds.slice(batchIdx, batchIdx + batchSize);
const details = await ctx.model.ReceivingDetail.findAll({
where: { receiving_id: { [Op.in]: batchIds } },
order: [[ 'receiving_id', 'ASC' ], [ 'id', 'ASC' ]],
raw: true,
});
for (const detail of details) {
const rid = Number(detail.receiving_id);
if (!detailsMap.has(rid)) {
detailsMap.set(rid, []);
}
detailsMap.get(rid).push(detail);
}
const currentBatch = Math.floor(batchIdx / batchSize) + 1;
await progressHandler({
status: 'running',
progress: Math.min(50, 30 + Math.round((currentBatch / totalBatches) * 20)),
message: `正在拉取收货单明细,已完成批次 ${currentBatch}/${totalBatches}`,
});
}
}
await progressHandler({
status: 'running',
progress: 55,
message: '正在生成 Excel 文件...',
});
// ---- 生成 Excel(流式写入,两个 Sheet) ----
const tempDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'wms-receiving-store-export-'));
const now = new Date();
const dateToken = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}${String(now.getSeconds()).padStart(2, '0')}`;
const filename = `收货单导出(货主)_${dateToken}.xlsx`;
const filePath = path.join(tempDir, filename);
const workbook = new ExcelJS.stream.xlsx.WorkbookWriter({
filename: filePath,
useStyles: false,
useSharedStrings: false,
});
const normalizeCellValue = value => {
if (value === null || value === undefined) return '';
if (value instanceof Date) return app.formatDate ? app.formatDate(value) : value.toISOString();
return value;
};
const statusLabelMap = {
receiving: '收货中',
completed: '已完成',
cancelled: '已作废',
};
const detailStatusLabelMap = {
all_matched: '全部匹配',
partial_matched: '部分匹配',
unmatched: '未匹配',
};
const storageStatusLabelMap = {
none: '未入库',
waiting: '等待入库',
partial: '部分入库',
all: '全部入库',
};
const deliveryMethodLabelMap = {
truck: '货车',
express: '快递',
air_freight: '空运',
sea_freight: '海运',
other: '其他',
};
const loadingMethodLabelMap = {
with_pallet: '带托盘',
without_pallet: '不带托盘',
};
// Sheet 1: 收货单列表
const sheet1 = workbook.addWorksheet('收货单列表');
const receivingColumns = [
{ header: '收货单ID', key: 'id', width: 10 },
{ header: '收货单号', key: 'receiving_number', width: 22 },
{ header: '货主', key: 'store_name', width: 20 },
{ header: '收货状态', key: 'status_label', width: 12 },
{ header: '明细匹配状态', key: 'detail_status_label', width: 14 },
{ header: '入库状态', key: 'storage_status_label', width: 12 },
{ header: '来货方式', key: 'delivery_method_label', width: 12 },
{ header: '车牌号', key: 'license_plate', width: 14 },
{ header: '快递单号', key: 'tracking_number', width: 22 },
{ header: '装卸方式', key: 'loading_method_label', width: 12 },
{ header: '总商品种类', key: 'total_items', width: 12 },
{ header: '总数量', key: 'total_quantity', width: 12 },
{ header: '总箱数', key: 'total_boxes', width: 10 },
{ header: '总托盘数', key: 'total_pallets', width: 10 },
{ header: '审核状态', key: 'is_review_label', width: 10 },
{ header: '创建人', key: 'creator_name', width: 14 },
{ header: '备注', key: 'remark', width: 30 },
{ header: '收货开始时间', key: 'receiving_start_time', width: 20 },
{ header: '收货结束时间', key: 'receiving_end_time', width: 20 },
{ header: '创建时间', key: 'created_at', width: 20 },
{ header: '更新时间', key: 'updated_at', width: 20 },
];
sheet1.columns = receivingColumns;
for (const row of allReceivingOrders) {
let creatorName = '';
try {
if (row.creator_snapshot) {
const snapshot = JSON.parse(row.creator_snapshot);
creatorName = snapshot.name || '';
}
} catch (_) { /* ignore */ }
sheet1.addRow({
id: row.id,
receiving_number: normalizeCellValue(row.receiving_number),
store_name: normalizeCellValue(row.store_name),
status_label: statusLabelMap[row.status] || row.status || '',
detail_status_label: detailStatusLabelMap[row.detail_status] || row.detail_status || '',
storage_status_label: storageStatusLabelMap[row.storage_status] || row.storage_status || '',
delivery_method_label: deliveryMethodLabelMap[row.delivery_method] || row.delivery_method || '',
license_plate: normalizeCellValue(row.license_plate),
tracking_number: normalizeCellValue(row.tracking_number),
loading_method_label: loadingMethodLabelMap[row.loading_method] || row.loading_method || '',
total_items: row.total_items,
total_quantity: row.total_quantity,
total_boxes: row.total_boxes,
total_pallets: row.total_pallets,
is_review_label: row.is_review === 1 ? '已审核' : '未审核',
creator_name: creatorName,
remark: normalizeCellValue(row.remark),
receiving_start_time: normalizeCellValue(row.receiving_start_time),
receiving_end_time: normalizeCellValue(row.receiving_end_time),
created_at: normalizeCellValue(row.created_at),
updated_at: normalizeCellValue(row.updated_at),
}).commit();
}
sheet1.commit();
await progressHandler({
status: 'running',
progress: 70,
message: '正在写入收货单明细...',
});
// Sheet 2: 收货单明细
const sheet2 = workbook.addWorksheet('收货单明细');
const detailColumns = [
{ header: '收货单号', key: 'receiving_number', width: 22 },
{ header: '收货单ID', key: 'receiving_id', width: 12 },
{ header: '明细ID', key: 'detail_id', width: 10 },
{ header: '商品名称', key: 'product_name', width: 28 },
{ header: '商品条码', key: 'barcode', width: 20 },
{ header: '系统商品ID', key: 'system_product_id', width: 14 },
{ header: '实际收货数量', key: 'actual_quantity', width: 14 },
{ header: '箱数', key: 'box_quantity', width: 10 },
{ header: '托盘数', key: 'pallet_quantity', width: 10 },
{ header: '收货状态', key: 'receiving_status_label', width: 12 },
{ header: '入库状态', key: 'storage_status_label', width: 12 },
{ header: '已入库数量', key: 'stored_quantity', width: 12 },
{ header: '批次号', key: 'batch_number', width: 16 },
{ header: '生产日期', key: 'production_date', width: 14 },
{ header: '到期日期', key: 'expiry_date', width: 14 },
{ header: '备注', key: 'remark', width: 30 },
{ header: '创建时间', key: 'created_at', width: 20 },
];
sheet2.columns = detailColumns;
const receivingCodeMap = new Map();
for (const row of allReceivingOrders) {
receivingCodeMap.set(Number(row.id), row.receiving_number || '');
}
const detailReceivingStatusLabelMap = {
pending: '待收货',
receiving: '收货中',
completed: '已完成',
cancelled: '已作废',
};
const detailStorageStatusLabelMap = {
none: '未入库',
waiting: '等待入库',
partial: '部分入库',
all: '全部入库',
};
const itemBatchSize = RECEIVING_ITEMS_FETCH_BATCH_SIZE;
let itemWrittenCount = 0;
const totalReceivingOrders = allReceivingIds.length;
for (let batchIdx = 0; batchIdx < allReceivingIds.length; batchIdx += itemBatchSize) {
const batchIds = allReceivingIds.slice(batchIdx, batchIdx + itemBatchSize);
for (const rid of batchIds) {
const receivingNumber = receivingCodeMap.get(rid) || '';
const details = detailsMap.get(rid) || [];
for (const detail of details) {
sheet2.addRow({
receiving_number: receivingNumber,
receiving_id: rid,
detail_id: detail.id,
product_name: normalizeCellValue(detail.product_name),
barcode: normalizeCellValue(detail.barcode),
system_product_id: normalizeCellValue(detail.system_product_id),
actual_quantity: detail.actual_quantity,
box_quantity: detail.box_quantity,
pallet_quantity: detail.pallet_quantity,
receiving_status_label: detailReceivingStatusLabelMap[detail.receiving_status] || detail.receiving_status || '',
storage_status_label: detailStorageStatusLabelMap[detail.storage_status] || detail.storage_status || '',
stored_quantity: detail.stored_quantity,
batch_number: normalizeCellValue(detail.batch_number),
production_date: normalizeCellValue(detail.production_date),
expiry_date: normalizeCellValue(detail.expiry_date),
remark: normalizeCellValue(detail.remark),
created_at: normalizeCellValue(detail.created_at),
}).commit();
}
itemWrittenCount += 1;
}
const currentBatch = Math.floor(batchIdx / itemBatchSize) + 1;
const totalBatches = Math.ceil(totalReceivingOrders / itemBatchSize);
await progressHandler({
status: 'running',
progress: Math.min(90, 70 + Math.round((currentBatch / totalBatches) * 20)),
message: `正在写入收货单明细,已完成 ${itemWrittenCount}/${totalReceivingOrders} 条收货单`,
});
}
sheet2.commit();
await workbook.commit();
await progressHandler({
status: 'running',
progress: 92,
message: '正在上传文件...',
});
// ---- 上传文件 ----
const uploadService = ctx?.service?.systems?.upload;
if (!uploadService || typeof uploadService.uploadFile !== 'function') {
throw new Error('上传服务不可用');
}
const stat = await fsp.stat(filePath);
const randomToken = crypto.randomBytes(6).toString('hex');
const uploadKey = `exports/receiving/store/${storeId}/${Date.now()}_${randomToken}.xlsx`;
const uploadStream = fs.createReadStream(filePath);
uploadStream.filename = filename;
uploadStream.mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
uploadStream.fileSize = stat.size;
const uploadResult = await uploadService.uploadFile(uploadStream, {
key: uploadKey,
category: 'document',
mimetype: 'xls,xlsx,csv',
});
let fileRecord = null;
if (typeof uploadService.uploadSuccessNotify === 'function') {
fileRecord = await uploadService.uploadSuccessNotify({
url: uploadResult.fileName,
fileKey: uploadResult.fileName,
fileName: filename,
fileType: 'document',
mimeType: uploadStream.mimeType,
fileSize: stat.size,
userId: ctx.userId,
description: `收货单导出(货主${storeId}),共${totalCount}条收货单`,
});
}
// 清理临时文件
try { await fsp.rm(tempDir, { recursive: true, force: true }); } catch (_) { /* ignore */ }
const uploadInfo = fileRecord || uploadResult;
const fileUrl = typeof uploadInfo === 'object' && uploadInfo.url
? uploadInfo.url
: (typeof uploadResult === 'object' ? uploadResult.fileName : '');
await progressHandler({
status: 'running',
progress: 100,
message: '导出完成',
result: { url: fileUrl, fileKey: uploadKey, total: totalCount },
});
return {
url: fileUrl,
fileKey: uploadKey,
total: totalCount,
totalDetails: allReceivingIds.reduce((sum, rid) => sum + (detailsMap.get(rid) || []).length, 0),
};
}
}
module.exports = ReceivingService;