packServer/backend/database/migrations/20261019120000-dedupe-scan-records.js

48 lines
1.8 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';
/**
* 清理历史重复运单号:同一个运单号只保留「最后一条」
*
* 背景:
* - 旧版本的扫码上报规则是「首次扫描即入库、24 小时内再扫直接丢弃」,
* 加上中途换过几次去重键,库里留下了同一运单号的多条记录;
* - 2026-10-19 起后端改成「同运单 24 小时内只保留一条、后扫的覆盖前一条」,
* 但**历史数据不会自动清理**,查询页仍会把重复记录全列出来。
*
* 清理规则(与 service/scan.js 的 mergeExisting 保持一致):
* - 分组:`subject_id`(空值按 0 归组)+ `barcode`,**跨主体互不影响**;
* - 每组保留:`scan_time` 最新的那一条,时间相同时保留 `id` 最大的(最后写入);
* - 其余行**物理删除**(scan_records 是流水表,没有软删除)。
*
* 不可逆:down() 不做恢复(被删的都是同一运单的旧记录,没有保留价值)。
*/
module.exports = {
async up(queryInterface) {
const [ rows ] = await queryInterface.sequelize.query(`
SELECT id FROM (
SELECT id,
ROW_NUMBER() OVER (
PARTITION BY COALESCE(subject_id, 0), barcode
ORDER BY scan_time DESC, id DESC
) AS rn
FROM scan_records
) ranked
WHERE rn > 1
`);
const ids = rows.map(row => Number(row.id));
if (!ids.length) {
console.log('[dedupe] scan_records 没有重复运单号,跳过');
return;
}
await queryInterface.bulkDelete('scan_records', { id: ids });
console.log(`[dedupe] 已删除 ${ids.length} 条重复扫码记录(同一运单号只保留最后一条)`);
},
async down() {
// 数据清理不可逆:不恢复被删的历史记录
},
};