diff --git a/models/schema/organization.js b/models/schema/organization.js index 04d7378..de21bc4 100644 --- a/models/schema/organization.js +++ b/models/schema/organization.js @@ -5,14 +5,15 @@ import { pinyin } from "pinyin-pro"; /** * Organization Schema - * 组织/机构基础信息,支持医院、诊所、体检中心等多种机构类型; + * 组织/机构基础信息,支持诊所、体检中心等机构类型; + * 医院基础信息统一在 hospital 集合(schema/hospital.js),此处不再维护。 * 分院/院区用 parentId 指向总院,先只做一层,更多层级按需再加 */ const OrganizationSchema = mongoose.Schema( { // 基础信息 - name: { type: String, required: true, index: true, comment: "机构全称;分院/院区需带总院名,如 北京协和医院西单院区" }, - shortName: { type: String, default: "", comment: "机构简称/别名,如 协和西院" }, + name: { type: String, required: true, index: true, comment: "机构全称;分院/分点需带主机构名,如 美年大健康西单分院" }, + shortName: { type: String, default: "", comment: "机构简称/别名,如 美年西单店" }, pinyin: { type: String, default: "", index: true, comment: "机构名称全拼(小写无分隔,用于搜索)" }, pinyinFL: { type: String, default: "", index: true, comment: "机构名称拼音首字母(用于搜索)" }, code: { type: String, unique: true, sparse: true, comment: "机构编码(不填时字段缺省,避免与 unique sparse 索引冲突)" }, @@ -29,18 +30,12 @@ const OrganizationSchema = mongoose.Schema( // 机构类型 type: { type: String, - enum: ["hospital", "clinic", "checkup_center", "other"], - default: "hospital", - comment: "机构类型:医院、诊所、体检中心、其他", + enum: ["clinic", "checkup_center", "other"], + default: "clinic", + comment: "机构类型:诊所、体检中心、其他(医院在 hospital 集合)", }, - // 等级/性质 - level: { - type: String, - enum: ["三级甲等", "三级乙等", "二级甲等", "二级乙等", "一级", "未定级", ""], - default: "", - comment: "医院等级", - }, + // 性质 nature: { type: String, enum: ["public", "private", "joint", "other", ""], @@ -77,27 +72,6 @@ const OrganizationSchema = mongoose.Schema( description: { type: String, default: "", comment: "机构简介" }, remark: { type: String, default: "", comment: "备注" }, - // 就医信息:agent-first,字段已平铺,先保留够用的部分,后续按需增加 - overview: { type: String, default: "", comment: "医院级信息全文(门诊/挂号/缴费/医保/交通)" }, - photos: [{ - url: { type: String, default: "", comment: "图片链接" }, - caption: { type: String, default: "", comment: "说明(医院照片/导引照片 + 描述)" }, - }], - departments: [{ - name: { type: String, comment: "科室名称(锚点)" }, - detail: { type: String, default: "", comment: "科室信息全文(位置/电话/类型/就诊提示)" }, - photo: { type: String, default: "", comment: "科室位置导引照片链接" }, - }], - doctors: [{ - name: { type: String, comment: "医生姓名(锚点)" }, - department: { type: String, comment: "所属科室(锚点)" }, - detail: { type: String, default: "", comment: "医生信息全文(职称/擅长/号别/坐班停诊)" }, - photo: { type: String, default: "", comment: "医生照片链接" }, - }], - guides: { type: mongoose.Schema.Types.Mixed, comment: "场景指南(键为场景名,值为文本)" }, - infoUpdatedAt: { type: Date, comment: "就医信息最近更新时间" }, - infoUpdatedBy: { type: String, default: "", comment: "就医信息最近更新人" }, - // 元数据 meta: { createtime: { type: Date, default: Date.now, comment: "创建时间" }, diff --git a/scripts/check_db_schema_sync.js b/scripts/check_db_schema_sync.js new file mode 100644 index 0000000..d5979e1 --- /dev/null +++ b/scripts/check_db_schema_sync.js @@ -0,0 +1,143 @@ +/** + * 只读体检:对比 models/schema 定义与实际 MongoDB,不做任何写操作。 + * + * 检查项: + * 1. 实际集合 vs 已注册模型(多出的集合 / 缺失的集合) + * 2. 每个模型:schema 声明的索引 vs 数据库实际索引(缺的 / 多的) + * 3. 各集合文档数 + * 4. 跨集合孤儿引用(删除订单后的 payment/refund 残留、employee.orgId、healthProfileId 等) + * 5. 明显脏数据(旧式 status=cancelled、缺失 cancelStatus、organization 残留医院字段) + * + * 用法(在 api/health 下):node scripts/check_db_schema_sync.js + */ +import { DBModel } from "../models/index.js"; +import mongoose from "mongoose"; + +DBModel.init(); +const conn = DBModel.dbConnection; + +const report = (title, rows) => { + console.log(`\n===== ${title} =====`); + if (!rows.length) { + console.log(" (none)"); + return; + } + rows.forEach((row) => console.log(` ${row}`)); +}; + +const keyOf = (indexDef) => JSON.stringify(indexDef); + +async function main() { + const db = conn.db; + + // ---------- 1. 集合 vs 模型 ---------- + const collections = (await db.listCollections().toArray()).map((c) => c.name); + const modelNames = conn.modelNames(); // 小写 collection 名 + report("1. collections in DB but no model", collections.filter((c) => !modelNames.includes(c))); + report("1. models without collection in DB", modelNames.filter((m) => !collections.includes(m))); + + // ---------- 2/3. 索引与文档数 ---------- + for (const name of modelNames) { + const model = conn.model(name); + const actual = await db.collection(name).indexes(); + // schema.indexes() 返回 [ [indexDef, options], ... ],第一个元素才是键定义 + const expected = [{ key: { _id: 1 } }, ...model.schema.indexes().map(([def]) => ({ key: def }))]; + const actualKeys = new Set(actual.map((idx) => keyOf(idx.key))); + + // 模型里声明的但库里没有的 + const missing = expected.filter((idx) => !actualKeys.has(keyOf(idx.key))); + // 额外声明:unique/sparse/partial 选项差异只提示名字,人工确认 + const expectedKeys = new Set(expected.map((idx) => keyOf(idx.key))); + const extra = actual.filter((idx) => !expectedKeys.has(keyOf(idx.key))); + + const count = await db.collection(name).countDocuments({}); + console.log(`\n===== ${name} =====`); + console.log(` docs: ${count}`); + if (missing.length) console.log(` MISSING indexes (in schema, not in DB): ${missing.map((m) => keyOf(m.key)).join(", ")}`); + if (extra.length) console.log(` EXTRA indexes (in DB, not in schema): ${extra.map((e) => `${keyOf(e.key)}${e.unique ? " [unique]" : ""}${e.sparse ? " [sparse]" : ""}${e.partialFilterExpression ? " [partial]" : ""}`).join(", ")}`); + if (!missing.length && !extra.length) console.log(" indexes: in sync"); + } + + // ---------- 4. 孤儿引用 ---------- + const orphans = async (label, fromColl, fromField, toColl, detail = null) => { + const rows = await db.collection(fromColl).aggregate([ + { $match: { [fromField]: { $ne: null } } }, + { $group: { _id: `$${fromField}` } }, + { $lookup: { from: toColl, localField: "_id", foreignField: "_id", as: "hit" } }, + { $match: { hit: { $size: 0 } } }, + { $count: "n" }, + ]).toArray(); + if (!rows.length) { + report(`4. orphan ${fromColl}.${fromField} -> ${toColl}`, []); + return; + } + let lines = [` ${rows[0].n} distinct missing refs`]; + if (detail) { + const missingIds = await db.collection(fromColl).aggregate([ + { $match: { [fromField]: { $ne: null } } }, + { $group: { _id: `$${fromField}` } }, + { $lookup: { from: toColl, localField: "_id", foreignField: "_id", as: "hit" } }, + { $match: { hit: { $size: 0 } } }, + { $project: { _id: 1 } }, + ]).toArray(); + const idSet = new Set(missingIds.map((d) => String(d._id))); + const docs = await db.collection(fromColl).find({ [fromField]: { $in: [...idSet] } }).toArray(); + lines = lines.concat(docs.map((d) => detail(d))); + } + report(`4. orphan ${fromColl}.${fromField} -> ${toColl}`, lines); + }; + await orphans( + "payment_record.recordId", "payment_record", "recordId", "escort_record", + (d) => ` ${d._id} outTradeNo=${d.outTradeNo} status=${d.status} totalFee=${d.totalFee} createdAt=${d.createdAt?.toISOString?.() ?? d.createdAt}` + ); + await orphans("refund_record.recordId", "refund_record", "recordId", "escort_record"); + await orphans("refund_record.paymentId", "refund_record", "paymentId", "payment_record"); + await orphans("escort_record.healthProfileId", "escort_record", "healthProfileId", "health_profile"); + await orphans("employee.orgId", "employee", "orgId", "organization"); + await orphans("employee_review.recordId", "employee_review", "recordId", "escort_record"); + await orphans("employee_review.employeeId", "employee_review", "employeeId", "employee"); + await orphans("escort_record.paymentRecordId", "escort_record", "paymentRecordId", "payment_record"); + + // ---------- 5. 脏数据 ---------- + const dirty = []; + const cnt = async (label, filter, coll) => { + const n = await db.collection(coll).countDocuments(filter); + if (n > 0) dirty.push(`${coll}: ${label} = ${n}`); + }; + await cnt("status=cancelled(旧式取消写法)", { status: "cancelled" }, "escort_record"); + await cnt("缺少 cancelStatus 字段", { cancelStatus: { $exists: false } }, "escort_record"); + await cnt("type=hospital(应已清理)", { type: "hospital" }, "organization"); + await cnt("残留 forAgent 字段", { forAgent: { $exists: true } }, "organization"); + + // hospital name 唯一索引是否真生效:查重复名 + const dupNames = await db.collection("hospital").aggregate([ + { $group: { _id: "$name", n: { $sum: 1 } } }, + { $match: { n: { $gt: 1 } } }, + { $limit: 10 }, + ]).toArray(); + if (dupNames.length) dirty.push(`hospital: 重复 name = ${dupNames.map((d) => `${d._id}(${d.n})`).join(", ")}`); + + // organization 残留医院专属字段 + const orgHospitalFields = await db.collection("organization").countDocuments({ + $or: [ + { overview: { $exists: true } }, { photos: { $exists: true } }, + { departments: { $exists: true } }, { doctors: { $exists: true } }, + { guides: { $exists: true } }, { level: { $exists: true } }, + ], + }); + if (orgHospitalFields > 0) dirty.push(`organization: 残留医院字段文档 = ${orgHospitalFields}`); + + // user 集合存在性(多模型 ref user) + if (!collections.includes("user")) dirty.push("user 集合不存在,但多张表 ref user"); + + report("5. dirty/stale data", dirty.map((d) => d.replace(/^/, ""))); + + console.log("\n(check done, read-only)"); +} + +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); }); +} diff --git a/scripts/check_orphan_payments.js b/scripts/check_orphan_payments.js new file mode 100644 index 0000000..a508731 --- /dev/null +++ b/scripts/check_orphan_payments.js @@ -0,0 +1,54 @@ +/** + * 只读补查:孤儿 payment_record 明细 + user/users 集合归属确认。 + * 用法(在 api/health 下):node scripts/check_orphan_payments.js + */ +import { DBModel } from "../models/index.js"; + +DBModel.init(); +const conn = DBModel.dbConnection; + +async function main() { + const db = conn.db; + + // 找出 recordId 在 escort_record 中不存在的 payment_record + const orphanPayments = 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(`orphan payment_record docs: ${orphanPayments.length}`); + for (const p of orphanPayments) { + console.log(` ${p._id} outTradeNo=${p.outTradeNo} status=${p.status} totalFee=${p.totalFee} payerTotal=${p.payerTotal} userId=${p.userId} createdAt=${p.createdAt?.toISOString?.() ?? p.createdAt}`); + const refunds = await db.collection("refund_record").find({ paymentId: p._id }).toArray(); + refunds.forEach((r) => console.log(` refund: ${r._id} outRefundNo=${r.outRefundNo} status=${r.status} amount=${r.refundAmount}`)); + } + + // user / users 集合情况 + for (const name of ["user", "users"]) { + const exists = await db.listCollections({ name }).hasNext(); + if (!exists) { + console.log(`\ncollection ${name}: NOT EXIST`); + continue; + } + const n = await db.collection(name).countDocuments({}); + const sample = await db.collection(name).findOne({}, { projection: { mobile: 1, phone: 1, name: 1, nickname: 1, createdAt: 1, "meta.createtime": 1 } }); + console.log(`\ncollection ${name}: ${n} docs, sample=${JSON.stringify(sample)}`); + } + + // 现存 escort_record 的 userId 是否在 users 里能对上 + const records = await db.collection("escort_record").find({}, { projection: { userId: 1 } }).toArray(); + for (const r of records) { + const inUsers = r.userId ? await db.collection("users").countDocuments({ _id: r.userId }) : 0; + console.log(`escort_record ${r._id} userId=${r.userId} in users: ${inUsers}`); + } + + console.log("\n(check done, read-only)"); +} + +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); }); +} diff --git a/scripts/delete_escort_records_before_202611.js b/scripts/delete_escort_records_before_202611.js new file mode 100644 index 0000000..b83ae1e --- /dev/null +++ b/scripts/delete_escort_records_before_202611.js @@ -0,0 +1,48 @@ +/** + * 一次性清理:物理删除 escort_record(陪诊订单)里 2026-11-01 之前创建的记录。 + * + * 注意:已确认要全删(含已支付/已完成订单),不受「已收款订单需留存审计」的常规约束。 + * 时间口径:meta.createtime < 2026-11-01 00:00:00(Asia/Shanghai)。 + * + * 用法(在 api/health 下): + * node scripts/delete_escort_records_before_202611.js # 仅统计,不删除 + * node scripts/delete_escort_records_before_202611.js --apply # 实际删除 + */ +import { DBModel } from "../models/index.js"; + +DBModel.init(); +const conn = DBModel.dbConnection; +const apply = process.argv.includes("--apply"); + +// 东八区 2026-11-01 00:00:00,避免服务器时区差异 +const CUTOFF = new Date("2026-11-01T00:00:00+08:00"); +const filter = { "meta.createtime": { $lt: CUTOFF } }; + +async function cleanup() { + const matched = await DBModel.EscortRecord.countDocuments(filter).exec(); + const byStatus = await DBModel.EscortRecord.aggregate([ + { $match: filter }, + { $group: { _id: "$status", count: { $sum: 1 } } }, + ]).exec(); + + console.log(`cutoff=${CUTOFF.toISOString()} (2026-11-01 00:00:00 +08:00)`); + console.log(`matched escort records created before cutoff: ${matched}`); + byStatus.forEach((row) => console.log(` status=${row._id ?? "none"}: ${row.count}`)); + + if (!apply) { + console.log("dry-run only. re-run with --apply to delete."); + return; + } + + const result = await DBModel.EscortRecord.deleteMany(filter); + console.log(`deleted: ${result.deletedCount}`); +} + +cleanup() + .catch((error) => { + console.error(error); + process.exitCode = 1; + }) + .finally(() => { + conn.close(); + }); diff --git a/scripts/delete_organization_hospitals.js b/scripts/delete_organization_hospitals.js new file mode 100644 index 0000000..71607e0 --- /dev/null +++ b/scripts/delete_organization_hospitals.js @@ -0,0 +1,42 @@ +/** + * 一次性清理:删除 organization 集合里医院相关的记录。 + * + * 医院基础信息已统一迁移到 hospital 集合(schema/hospital.js), + * organization 集合不再维护医院数据;本脚本删除 type=hospital 的记录。 + * + * 用法:在 api/health 下执行 `node scripts/delete_organization_hospitals.js` + */ +import { DBModel } from "../models/index.js"; + +DBModel.init(); +const conn = DBModel.dbConnection; + +async function cleanup() { + // 非医院记录(历史数据里可能有未填 type 的)统一保留,只删明确标记为医院的 + const filter = { type: "hospital" }; + const matched = await DBModel.Organization.countDocuments(filter).exec(); + const result = await DBModel.Organization.deleteMany(filter); + + console.log(`deleted: matched=${matched}, deletedCount=${result.deletedCount}`); + const remaining = await DBModel.Organization.countDocuments({}).exec(); + console.log(`remaining organizations: ${remaining}`); + await conn.close(); +} + +if (conn.readyState === 1) { + cleanup().catch((error) => { + console.error(error); + process.exit(1); + }); +} else { + conn.once("connected", () => { + cleanup().catch((error) => { + console.error(error); + process.exit(1); + }); + }); + conn.once("error", (error) => { + console.error(error); + process.exit(1); + }); +}