Files
yara724api/scripts/data/parsian-tehran/seed-remaining-experts.test.cjs
T
SepehrYahyaee 83376df4ad feat: manage expert access and merge Parsian expert seeds
Allow role-specific identities and admin account activation, support national-code-only claim experts, and remove required voice from v4/v5. Add a combined, resumable Parsian seed that preserves existing accounts and merges locations and product codes.
2026-11-18 17:16:26 +03:30

391 lines
13 KiB
JavaScript

const { test } = require("node:test");
const assert = require("node:assert/strict");
const { isDeepStrictEqual } = require("node:util");
const mongoose = require("mongoose");
const {
loadMergedData,
buildPlan,
applyPlan,
} = require("./seed-remaining-experts");
const nationalCode = "0012345678";
const branch = (code, name, address = "") => ({
code,
name,
city: "تهران",
state: "تهران",
address,
isActive: true,
});
const west = branch("210050", "شعبه غرب", "نشانی اصلی");
const poonak = branch("210110", "شعبه پونک");
function sources() {
return {
branches: { clientCode: 8, branches: [west] },
reviewers: {
clientCode: 8,
fileReviewers: [
{
nationalCode,
firstName: "نام",
lastName: "آزمایشی",
locations: [{ id: west.code, name: west.name }],
ThirdPartyExpertiseClaim: "11",
CarBodyExpertiseClaim: "12",
},
],
},
makers: {
clientCode: 8,
fileMakers: [
{
nationalCode,
firstName: "نام",
lastName: "آزمایشی",
locations: [{ id: poonak.code, name: poonak.name }],
ThirdPartyClaimExpertId: "21",
},
],
},
legacy: { clientCode: 8, fieldExperts: [] },
remaining: {
clientCode: 8,
branches: [poonak, { ...west, address: "" }],
skippedRows: [],
experts: [
{
nationalCode,
firstName: "نام",
lastName: "آزمایشی",
branchCode: poonak.code,
roles: ["damage_expert", "file_reviewer"],
ThirdPartyExpertiseClaim: "99",
},
],
},
};
}
const same = (a, b) =>
Array.isArray(a) || Array.isArray(b)
? isDeepStrictEqual(a, b)
: String(a ?? "") === String(b ?? "");
function matches(record, filter) {
return Object.entries(filter).every(([key, value]) => {
if (key === "$or") return value.some((part) => matches(record, part));
if (value?.$in) return value.$in.some((entry) => same(record[key], entry));
if (value?.$exists !== undefined)
return (record[key] !== undefined) === value.$exists;
return same(record[key], value);
});
}
function database() {
const clientKey = new mongoose.Types.ObjectId();
const store = {
clients: [{ _id: clientKey, clientCode: 8 }],
branches: [],
"damage-expert": [],
"file-reviewer": [],
"file-maker": [],
};
const writes = [],
indexMap = {};
return {
clientKey,
store,
writes,
collection(name) {
assert.ok(
Object.hasOwn(store, name),
`The seed must not access case/history collections: ${name}`,
);
indexMap[name] ??= [{ key: { email: 1 }, name: "email_1", unique: true }];
return {
find: (filter) => ({
toArray: async () =>
store[name].filter((record) => matches(record, filter)),
}),
indexes: async () => indexMap[name],
createIndex: async (key, options) => {
const label =
options.name ??
Object.entries(key)
.map(([field, order]) => `${field}_${order}`)
.join("_");
writes.push({ action: "index", name, label });
if (!indexMap[name].some((index) => index.name === label))
indexMap[name].push({ key, name: label, ...options });
},
dropIndex: async (label) => {
writes.push({ action: "drop", name, label });
indexMap[name] = indexMap[name].filter(
(index) => index.name !== label,
);
},
insertOne: async (record) => {
store[name].push({
...record,
_id: record._id ?? new mongoose.Types.ObjectId(),
});
writes.push({ action: "insert", name });
},
updateOne: async (filter, update) => {
const record = store[name].find((row) => matches(row, filter));
if (!record) return { matchedCount: 0 };
Object.assign(record, update.$set);
writes.push({ action: "update", name });
return { matchedCount: 1 };
},
};
},
};
}
function existingReviewer(db) {
const existingWest = {
...west,
_id: new mongoose.Types.ObjectId(),
clientKey: db.clientKey,
isActive: false,
address: "",
};
db.store.branches.push(existingWest);
const reviewer = {
_id: new mongoose.Types.ObjectId(),
nationalCode,
role: "file_reviewer",
clientKey: db.clientKey,
branchId: existingWest._id,
locations: [{ id: west.code, name: west.name }],
password: "kept-password",
username: "kept-alias",
isActive: false,
ThirdPartyExpertiseClaim: "77",
};
db.store["file-reviewer"].push(reviewer);
return { existingWest, reviewer };
}
test("merges all real JSON sources and resolves the reported branch/code disagreements", () => {
const merged = loadMergedData();
assert.equal(merged.experts.length, 120);
assert.equal(merged.branches.length, 50);
for (const [role, expected] of [
["damage_expert", 88],
["file_reviewer", 88],
["file_maker", 39],
])
assert.equal(
merged.experts.filter((expert) => expert.roles.includes(role)).length,
expected,
);
const reported = merged.experts.find((expert) =>
expert.nationalCode.endsWith("8521"),
);
assert.deepEqual(
reported.roleLocations.file_reviewer.map((location) => location.id),
["210050", "210110"],
);
const codes = merged.experts.find((expert) =>
expert.nationalCode.endsWith("8118"),
);
assert.equal(codes.ThirdPartyExpertiseClaim, "3985");
assert.equal(codes.CarBodyExpertiseClaim, "3986");
assert.ok(
merged.notes.some((note) => note.action === "kept-original-source-code"),
);
});
test("retains role-specific source branches and the original address when building a fresh database", async () => {
const db = database(),
seed = loadMergedData(sources());
const plan = await buildPlan(db, seed);
assert.equal(
db.writes.length,
0,
"Planning/dry-run must not write indexes or documents",
);
await applyPlan(db, plan, async () => "new-hash");
assert.equal(
db.store.branches.find((record) => record.code === west.code).address,
west.address,
);
const claim = db.store["damage-expert"][0],
maker = db.store["file-maker"][0];
assert.equal(
String(claim.branchId),
String(db.store.branches.find((record) => record.code === west.code)._id),
);
assert.equal(
String(maker.branchId),
String(db.store.branches.find((record) => record.code === poonak.code)._id),
);
assert.equal(claim.ThirdPartyExpertiseClaim, "11");
assert.equal(claim.ThirdPartyClaimExpertId, "21");
assert.equal(maker.ThirdPartyExpertiseClaim, undefined);
});
test("reconciles the complete original Tehran seed with the remaining list without aborting", async () => {
const db = database();
for (const record of require("./branches.json").branches)
db.store.branches.push({
...record,
_id: new mongoose.Types.ObjectId(),
clientKey: db.clientKey,
});
for (const [file, key, role, collection] of [
[
"./file-reviewers.json",
"fileReviewers",
"file_reviewer",
"file-reviewer",
],
["./file-makers.json", "fileMakers", "file_maker", "file-maker"],
])
for (const record of require(file)[key]) {
db.store[collection].push({
...record,
_id: new mongoose.Types.ObjectId(),
clientKey: db.clientKey,
branchId: db.store.branches.find(
(branch) => branch.code === record.locations[0].id,
)._id,
username: record.nationalCode,
password: "preserved",
role,
isActive: true,
});
}
const reviewer = db.store["file-reviewer"].find((record) =>
record.nationalCode.endsWith("8521"),
);
const before = {
id: String(reviewer._id),
branchId: String(reviewer.branchId),
};
const plan = await buildPlan(db);
assert.equal(plan.filter((action) => action.kind === "branch").length, 44);
assert.equal(plan.filter((action) => action.kind === "create").length, 171);
assert.ok(!plan.notes.some((note) => note.action.startsWith("skipped-")));
await applyPlan(db, plan, async () => "new-hash");
assert.equal(db.store.branches.length, 50);
assert.equal(db.store["damage-expert"].length, 88);
assert.equal(db.store["file-reviewer"].length, 88);
assert.equal(db.store["file-maker"].length, 39);
assert.equal(String(reviewer._id), before.id);
assert.equal(String(reviewer.branchId), before.branchId);
assert.equal(reviewer.password, "preserved");
assert.deepEqual(
reviewer.locations.map((location) => location.id),
["210050", "210110"],
);
const again = await buildPlan(db);
assert.ok(again.every((action) => action.kind === "keep"));
});
test("merges existing reviewer locations/codes without moving it or replacing credentials; new claim inherits its branch/codes", async () => {
const db = database(),
{ existingWest, reviewer } = existingReviewer(db);
const previousId = String(reviewer._id);
const seed = loadMergedData(sources()),
plan = await buildPlan(db, seed);
assert.ok(
plan.notes.some(
(note) => note.action === "kept-existing-primary-branch",
) === false,
);
assert.ok(plan.notes.some((note) => note.action === "kept-existing-code"));
await applyPlan(db, plan, async () => "new-hash");
assert.equal(String(reviewer._id), previousId);
assert.equal(String(reviewer.branchId), String(existingWest._id));
assert.equal(reviewer.password, "kept-password");
assert.equal(reviewer.username, "kept-alias");
assert.equal(reviewer.isActive, false);
assert.equal(reviewer.ThirdPartyExpertiseClaim, "77");
assert.equal(reviewer.CarBodyExpertiseClaim, "12");
assert.deepEqual(
reviewer.locations.map((location) => location.id),
[west.code, poonak.code],
);
assert.equal(existingWest.isActive, false);
assert.equal(existingWest.address, west.address);
const claim = db.store["damage-expert"][0];
assert.equal(String(claim.branchId), String(reviewer.branchId));
assert.equal(claim.ThirdPartyExpertiseClaim, "77");
assert.equal(claim.username, nationalCode);
assert.equal(claim.password, "new-hash");
const again = await buildPlan(db, seed);
assert.ok(again.every((action) => action.kind === "keep"));
await applyPlan(db, again, async () => {
throw new Error("Rerun must not create/reset passwords");
});
assert.equal(db.store["file-reviewer"].length, 1);
assert.equal(db.store["damage-expert"].length, 1);
});
test("an existing primary branch absent from the imported primary is preserved and reported", async () => {
const db = database(),
{ reviewer } = existingReviewer(db);
db.store.branches.push({
...poonak,
_id: new mongoose.Types.ObjectId(),
clientKey: db.clientKey,
});
reviewer.branchId = db.store.branches[1]._id;
reviewer.locations = [{ id: poonak.code, name: poonak.name }];
const plan = await buildPlan(db, loadMergedData(sources()));
assert.ok(
plan.notes.some((note) => note.action === "kept-existing-primary-branch"),
);
await applyPlan(db, plan, async () => "hash");
assert.equal(String(reviewer.branchId), String(db.store.branches[1]._id));
assert.deepEqual(
reviewer.locations.map((location) => location.id),
[poonak.code, west.code],
);
});
test("skips cross-insurer and ambiguous accounts while importing unrelated roles/accounts", async () => {
const db = database(),
{ reviewer } = existingReviewer(db);
reviewer.clientKey = new mongoose.Types.ObjectId();
const before = { ...reviewer };
const plan = await buildPlan(db, loadMergedData(sources()));
assert.ok(
plan.notes.some(
(note) =>
note.role === "file_reviewer" && note.action.startsWith("skipped-"),
),
);
await applyPlan(db, plan, async () => "hash");
assert.deepEqual(reviewer, before);
assert.equal(db.store["damage-expert"].length, 1);
assert.equal(db.store["file-maker"].length, 1);
});
test("normalizes a stored numeric national code without changing its account ID", async () => {
const db = database(),
{ reviewer } = existingReviewer(db);
reviewer.nationalCode = Number(nationalCode);
const id = reviewer._id;
await applyPlan(
db,
await buildPlan(db, loadMergedData(sources())),
async () => "hash",
);
assert.equal(reviewer.nationalCode, nationalCode);
assert.equal(reviewer._id, id);
});
test("concurrent location edits are not overwritten by a stale merge", async () => {
const db = database(),
{ reviewer } = existingReviewer(db);
const plan = await buildPlan(db, loadMergedData(sources()));
reviewer.locations = [{ id: "999999", name: "ویرایش همزمان" }];
await assert.rejects(
applyPlan(db, plan, async () => "hash"),
/changed after preflight/,
);
assert.deepEqual(reviewer.locations, [
{ id: "999999", name: "ویرایش همزمان" },
]);
});