/** * 合并 wms_inbox_group 中 (warehouse_id, group_id) 相同的重复群记录。 * * 背景:receiver.js 历史上按 (group_name, warehouse_id) 登记群, * 群改名后会插入同群ID的新记录,产生重复。 * 合并策略: * 1. 保留记录:is_blocked=0(启用)优先,其次 created_at 最早。 * 2. 保留记录的名称:取 updated_at 最新一条的名称(即当前最新群名)。 * 3. 其余字段:保留记录为空时,从重复记录中补齐非空值。 * 4. 其余重复记录软删除(deleted_at = NOW())。 * * 用法: * node script/merge-inbox-group-duplicates.cjs --dry-run # 只预览,默认 * node script/merge-inbox-group-duplicates.cjs --apply # 实际执行 */ const fs = require('fs'); const path = require('path'); const mysql = require('mysql2/promise'); const ROOT = process.cwd(); const DEFAULT_CONFIG_PATH = path.join(ROOT, 'config', 'config.local.js'); const TABLE_NAME = 'wms_inbox_group'; /** 允许从重复记录补齐到保留记录的字段 */ const FILLABLE_FIELDS = [ 'store_id', 'group_type', 'sub_type', 'source_type', 'source_extra', 'express_interfaces', 'system_express_code', ]; function parseArgs(argv) { const args = { dryRun: true, apply: false, dbClient: 'wms', configPath: DEFAULT_CONFIG_PATH }; for (const item of argv) { if (item === '--apply') args.apply = true; if (item === '--dry-run') args.dryRun = true; if (item.startsWith('--db-client=')) args.dbClient = String(item.split('=')[1] || '').trim() || 'wms'; if (item.startsWith('--config-path=')) args.configPath = path.resolve(ROOT, String(item.split('=')[1] || '').trim()); } if (args.apply) args.dryRun = false; return args; } function loadDbClient(configPath, dbClientName) { if (!fs.existsSync(configPath)) { throw new Error(`Config file not found: ${configPath}`); } const configFactory = require(configPath); const cfg = typeof configFactory === 'function' ? configFactory({ name: 'wms-inbox-group-merge' }) : configFactory; const dbClient = cfg && cfg.mysql && cfg.mysql.clients && cfg.mysql.clients[dbClientName]; if (!dbClient) { throw new Error(`MySQL client not found in config.mysql.clients: ${dbClientName}`); } return dbClient; } async function findDuplicateGroups(conn) { const [ rows ] = await conn.query( `SELECT warehouse_id, group_id, COUNT(*) AS cnt FROM \`${TABLE_NAME}\` WHERE group_id IS NOT NULL AND group_id <> '' AND deleted_at IS NULL GROUP BY warehouse_id, group_id HAVING cnt > 1 ORDER BY warehouse_id, group_id` ); return rows || []; } async function fetchGroupRows(conn, warehouseId, groupId) { const [ rows ] = await conn.query( `SELECT id, group_name, group_id, warehouse_id, store_id, group_type, sub_type, source_type, source_extra, express_interfaces, system_express_code, ai_enabled, is_blocked, created_at, updated_at, deleted_at FROM \`${TABLE_NAME}\` WHERE warehouse_id = ? AND group_id = ? AND deleted_at IS NULL`, [ warehouseId, groupId ] ); return rows || []; } function pickKeepRow(rows) { // 启用优先,其次创建时间最早,最后 id 最小 return [ ...rows ].sort((a, b) => { if (Number(a.is_blocked) !== Number(b.is_blocked)) return Number(a.is_blocked) - Number(b.is_blocked); if (a.created_at !== b.created_at) return new Date(a.created_at) - new Date(b.created_at); return a.id - b.id; })[0]; } function pickNewestNameRow(rows) { return [ ...rows ].sort((a, b) => { const da = new Date(a.updated_at); const db = new Date(b.updated_at); if (da !== db) return db - da; return b.id - a.id; })[0]; } function buildMergePlan(rows) { const keepRow = pickKeepRow(rows); const nameRow = pickNewestNameRow(rows); const dropRows = rows.filter(r => r.id !== keepRow.id); const updates = {}; if (keepRow.group_name !== nameRow.group_name) { updates.group_name = nameRow.group_name; } // 保留记录字段为空时,从重复记录补齐非空值 for (const field of FILLABLE_FIELDS) { if (keepRow[field] === null || keepRow[field] === undefined || keepRow[field] === '') { for (const row of rows) { if (row.id === keepRow.id) continue; if (row[field] !== null && row[field] !== undefined && row[field] !== '') { updates[field] = row[field]; break; } } } } return { keepRow, nameRow, dropRows, updates }; } async function main() { const args = parseArgs(process.argv.slice(2)); const dbClient = loadDbClient(args.configPath, args.dbClient); const conn = await mysql.createConnection({ host: dbClient.host, port: dbClient.port, user: dbClient.user, password: dbClient.password, database: dbClient.database, }); try { const duplicates = await findDuplicateGroups(conn); console.log(`发现 ${duplicates.length} 组重复群 (group_id 相同):\n`); if (duplicates.length === 0) { console.log('无重复群,无需处理。'); return; } let mergedCount = 0; let updateCount = 0; for (const dup of duplicates) { const rows = await fetchGroupRows(conn, dup.warehouse_id, dup.group_id); if (rows.length < 2) continue; const { keepRow, nameRow, dropRows, updates } = buildMergePlan(rows); mergedCount += 1; if (Object.keys(updates).length > 0) updateCount += 1; console.log( `[${dup.warehouse_id}] ${dup.group_id} (${rows.length} 条): ` + `保留 id=${keepRow.id} "${keepRow.group_name}"` ); if (updates.group_name) { console.log(` 名称更新: "${keepRow.group_name}" → "${updates.group_name}"`); } const otherUpdates = { ...updates }; delete otherUpdates.group_name; if (Object.keys(otherUpdates).length > 0) { console.log(` 字段补齐: ${JSON.stringify(otherUpdates)}`); } for (const drop of dropRows) { console.log(` 软删除: id=${drop.id} "${drop.group_name}" (${drop.is_blocked ? '屏蔽' : '启用'})`); } console.log(` 最新名称来源: id=${nameRow.id} "${nameRow.group_name}"`); if (!args.dryRun) { if (Object.keys(updates).length > 0) { await conn.query( `UPDATE \`${TABLE_NAME}\` SET ? WHERE id = ?`, [ updates, keepRow.id ] ); } for (const drop of dropRows) { await conn.query( `UPDATE \`${TABLE_NAME}\` SET deleted_at = NOW() WHERE id = ?`, [ drop.id ] ); } } } console.log(`\n${args.dryRun ? '[dry-run] 预览完成' : '执行完成'}: ` + `共 ${mergedCount} 组重复群,其中 ${updateCount} 组需要更新保留记录。`); } finally { await conn.end(); } } main().catch(err => { console.error('执行失败:', err.message); process.exit(1); });