Files
api_health/scripts/drop_stale_indexes_and_orphan_payments.js
T
lik 420f379ce8 chore(scripts): 新增旧索引与孤儿支付流水清理脚本
删除 schema 已不声明的旧索引(hospital 旧结构 5 个、employee name 1 个)
与指向已删订单的孤儿 payment_record(仅 closed 未实付且无退款时允许删除),
支持 dry-run 与 --apply 两种模式。
2026-11-06 18:02:08 +08:00

80 lines
3.2 KiB
JavaScript

/**
* 一次性清理:
* 1. 删除数据库里 schema 已不再声明的旧索引
* - hospital: basic.name / location.city+basic.level / service.isEnabled / fudanRank / fudanOrder
* - employee: name
* 2. 删除指向已不存在订单的孤儿 payment_record(均为 closed 未实付,无关联退款)
*
* 用法(在 api/health 下):
* node scripts/drop_stale_indexes_and_orphan_payments.js # 仅检查,不执行
* node scripts/drop_stale_indexes_and_orphan_payments.js --apply # 实际执行
*/
import { DBModel } from "../models/index.js";
DBModel.init();
const conn = DBModel.dbConnection;
const apply = process.argv.includes("--apply");
// 键定义 -> 索引名。dropIndex 既可按名也可按键,这里按名删,避免键顺序歧义
const STALE_INDEXES = [
{ coll: "hospital", key: { "basic.name": 1 } },
{ coll: "hospital", key: { "location.city": 1, "basic.level": 1 } },
{ coll: "hospital", key: { "service.isEnabled": 1 } },
{ coll: "hospital", key: { fudanRank: 1 } },
{ coll: "hospital", key: { fudanOrder: 1 } },
{ coll: "employee", key: { name: 1 } },
];
async function main() {
const db = conn.db;
// ---------- 1. 旧索引 ----------
for (const { coll, key } of STALE_INDEXES) {
const indexes = await db.collection(coll).indexes();
// 匹配键定义完全一致的索引(忽略 _id 之类附加字段)
const hit = indexes.find(
(idx) => JSON.stringify(idx.key) === JSON.stringify(key)
);
if (!hit) {
console.log(`index ${coll} ${JSON.stringify(key)}: not found (already dropped)`);
continue;
}
if (!apply) {
console.log(`index ${coll} ${JSON.stringify(key)}: found as "${hit.name}" (dry-run)`);
continue;
}
await db.collection(coll).dropIndex(hit.name);
console.log(`index ${coll} ${JSON.stringify(key)}: dropped "${hit.name}"`);
}
// ---------- 2. 孤儿 payment_record ----------
const orphans = await db.collection("payment_record").aggregate([
{ $match: { recordId: { $ne: null } } },
{ $lookup: { from: "escort_record", localField: "recordId", foreignField: "_id", as: "hit" } },
{ $match: { hit: { $size: 0 } } },
]).toArray();
console.log(`\norphan payment_record docs: ${orphans.length}`);
for (const p of orphans) {
console.log(` ${p._id} outTradeNo=${p.outTradeNo} status=${p.status} payerTotal=${p.payerTotal}`);
// 安全阀:只删 closed 且未实付、无关联退款的流水,其余跳过人工处理
const refunds = await db.collection("refund_record").countDocuments({ paymentId: p._id });
if (p.status !== "closed" || p.payerTotal > 0 || refunds > 0) {
console.log(` skipped (status/paid/refund safety check failed)`);
continue;
}
if (!apply) continue;
await db.collection("payment_record").deleteOne({ _id: p._id });
console.log(` deleted`);
}
if (!apply) console.log("\ndry-run only. re-run with --apply to execute.");
}
if (conn.readyState === 1) {
main().catch((e) => { console.error(e); process.exitCode = 1; }).finally(() => conn.close());
} else {
conn.once("connected", () => main().catch((e) => { console.error(e); process.exitCode = 1; }).finally(() => conn.close()));
conn.once("error", (e) => { console.error(e); process.exit(1); });
}