Files
yara724-api/scripts/data/parsian-tehran/seed-remaining-experts.js
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

664 lines
21 KiB
JavaScript

#!/usr/bin/env node
"use strict";
// Merge the original Parsian JSON directory and the fixed remaining-experts data.
const fs = require("node:fs");
const path = require("node:path");
const crypto = require("node:crypto");
const { promisify } = require("node:util");
const mongoose = require("mongoose");
const scrypt = promisify(crypto.scrypt);
const roles = {
damage_expert: {
collection: "damage-expert",
codes: [
"ThirdPartyClaimExpertId",
"CarBodyClaimExpertId",
"ThirdPartyExpertiseClaim",
"CarBodyExpertiseClaim",
],
},
file_reviewer: {
collection: "file-reviewer",
codes: ["ThirdPartyExpertiseClaim", "CarBodyExpertiseClaim"],
},
file_maker: {
collection: "file-maker",
codes: ["ThirdPartyClaimExpertId", "CarBodyClaimExpertId"],
},
};
const string = (value) => String(value ?? "");
const empty = (value) => value == null || value === "";
class SeedError extends Error {}
function mergeLocations(...lists) {
const merged = new Map();
for (const location of lists.flat()) {
const id = string(location?.id).trim();
if (id && !merged.has(id))
merged.set(id, { id, name: string(location.name).trim() });
}
return [...merged.values()];
}
function loadMergedData(
sources = {
branches: require("./branches.json"),
reviewers: require("./file-reviewers.json"),
makers: require("./file-makers.json"),
legacy: require("./field-experts.json"),
remaining: require("./remaining-experts.json"),
},
) {
if (Object.values(sources).some((source) => source.clientCode !== 8))
throw new SeedError(
"All input JSON files must belong to Parsian (clientCode=8).",
);
const branches = new Map(),
experts = new Map(),
notes = [];
// The established branch directory wins; new data fills missing details only.
for (const branch of [
...sources.branches.branches,
...sources.remaining.branches,
]) {
const code = string(branch.code),
current = branches.get(code);
if (!current) branches.set(code, { ...branch, code });
else
for (const [field, value] of Object.entries(branch))
if (empty(current[field]) && !empty(value)) current[field] = value;
}
const allCodeFields = [
...new Set(Object.values(roles).flatMap((role) => role.codes)),
];
function addExpert(record, assignedRoles, locations, source) {
const nationalCode = string(record.nationalCode);
let expert = experts.get(nationalCode);
if (!expert) {
expert = {
nationalCode,
firstName: record.firstName,
lastName: record.lastName,
roles: [],
locations: [],
roleLocations: {},
};
experts.set(nationalCode, expert);
}
for (const field of ["firstName", "lastName", "mobile"])
if (empty(expert[field]) && !empty(record[field]))
expert[field] = record[field];
expert.locations = mergeLocations(expert.locations, locations);
expert.branchCode = expert.locations[0]?.id;
for (const role of assignedRoles) {
if (!expert.roles.includes(role)) expert.roles.push(role);
expert.roleLocations[role] = mergeLocations(
expert.roleLocations[role] ?? [],
locations,
);
}
for (const field of allCodeFields)
if (!empty(record[field])) {
const value = string(record[field]);
if (empty(expert[field])) expert[field] = value;
else if (expert[field] !== value)
notes.push({
nationalCode: `******${nationalCode.slice(-4)}`,
field,
source,
action: "kept-original-source-code",
});
}
}
for (const record of sources.reviewers.fileReviewers)
addExpert(
record,
["damage_expert", "file_reviewer"],
record.locations,
"file-reviewers.json",
);
for (const record of sources.makers.fileMakers)
addExpert(record, ["file_maker"], record.locations, "file-makers.json");
// This older file contains assessor titles, rather than FIELD_EXPERT accounts.
for (const record of sources.legacy.fieldExperts) {
const title = string(record.title).replace(/ي/g, "ی").replace(/ك/g, "ک");
if (!title.includes("ارزیاب") || !title.includes("خسارت")) continue;
const mapped = { ...record };
if (record.expertCode) {
if (/ثالث|مالی/.test(title))
mapped.ThirdPartyExpertiseClaim = string(record.expertCode);
if (/بدنه/.test(title))
mapped.CarBodyExpertiseClaim = string(record.expertCode);
}
addExpert(
mapped,
["damage_expert", "file_reviewer"],
[{ id: record.branchCode, name: record.branchName }],
"field-experts.json",
);
}
for (const record of sources.remaining.experts)
addExpert(
record,
record.roles,
[{ id: record.branchCode, name: branches.get(record.branchCode)?.name }],
"remaining-experts.json",
);
const result = {
clientCode: 8,
branches: [...branches.values()],
experts: [...experts.values()],
skippedRows: sources.remaining.skippedRows,
notes,
};
validateData(result);
return result;
}
function validateData(seed) {
if (seed.clientCode !== 8)
throw new SeedError("This seed is for Parsian (clientCode=8) only.");
const branches = new Set(seed.branches.map((branch) => branch.code));
if (branches.size !== seed.branches.length)
throw new SeedError("Duplicate branch codes in JSON.");
for (const branch of seed.branches)
if (
!/^\d+$/.test(branch.code) ||
!branch.name ||
!branch.city ||
!branch.state
)
throw new SeedError("Invalid branch data in JSON.");
const identities = new Set();
for (const expert of seed.experts) {
if (
!/^\d{10}$/.test(expert.nationalCode) ||
!expert.firstName ||
!expert.lastName ||
!branches.has(expert.branchCode)
)
throw new SeedError("Invalid expert identity or branch in JSON.");
if (
!expert.roles?.length ||
new Set(expert.roles).size !== expert.roles.length ||
expert.roles.some((role) => !Object.hasOwn(roles, role))
)
throw new SeedError("Invalid or repeated expert role in JSON.");
if (expert.mobile && !/^09\d{9}$/.test(expert.mobile))
throw new SeedError("Invalid mobile in JSON.");
for (const location of [
...(expert.locations ?? []),
...Object.values(expert.roleLocations ?? {}).flat(),
])
if (!branches.has(location.id))
throw new SeedError(
"Expert location has no matching branch in the combined JSON data.",
);
for (const role of expert.roles) {
const identity = `${role}:${expert.nationalCode}`;
if (identities.has(identity))
throw new SeedError("Duplicate role/national code in JSON.");
identities.add(identity);
for (const field of roles[role].codes)
if (
expert[field] != null &&
(!/^\d+$/.test(expert[field]) ||
!Number.isSafeInteger(Number(expert[field])) ||
Number(expert[field]) <= 0)
)
throw new SeedError("Invalid Fanavaran expert code in JSON.");
}
}
}
function databaseConfig() {
const env = { ...process.env },
filename = path.resolve(__dirname, "../../../.env");
if (fs.existsSync(filename))
for (const line of fs.readFileSync(filename, "utf8").split(/\r?\n/)) {
const match = line.match(/^\s*(?:export\s+)?([A-Za-z_]\w*)\s*=\s*(.*)$/);
if (!match || Object.hasOwn(env, match[1])) continue;
let value = match[2].trim();
if (/^["']/.test(value))
value = value.slice(1, value.lastIndexOf(value[0]));
else value = value.replace(/\s+#.*$/, "").trim();
env[match[1]] = value;
}
let uri = env.MONGO_URI ?? "";
for (let pass = 0; pass < 10 && /\$\{/.test(uri); pass++)
uri = uri.replace(/\$\{([^}]+)\}/g, (_, key) => env[key] ?? "");
if (!/^mongodb(?:\+srv)?:\/\//.test(uri) || /\$\{/.test(uri))
throw new SeedError(
"MONGO_URI is missing or invalid in the API environment.",
);
return {
uri,
options: {
tls: env.MONGO_TLS === "true",
tlsAllowInvalidCertificates: env.MONGO_TLS_ALLOW_INVALID_CERTS === "true",
serverSelectionTimeoutMS: 10000,
autoIndex: false,
autoCreate: false,
},
};
}
async function buildPlan(db, seed = loadMergedData()) {
validateData(seed);
const clients = await db
.collection("clients")
.find({ clientCode: 8 }, { projection: { _id: 1 } })
.toArray();
if (clients.length !== 1)
throw new SeedError(
"Exactly one existing Parsian insurer (clientCode=8) is required.",
);
const clientKey = clients[0]._id;
const branches = await db
.collection("branches")
.find({ clientKey: { $in: [clientKey, string(clientKey)] } })
.toArray();
const branchIds = new Map(),
plan = [];
plan.notes = [...(seed.notes ?? [])];
function conditionalUpdate(record, changes) {
const filter = { _id: record._id, clientKey: record.clientKey };
for (const field of Object.keys(changes))
filter[field] = Object.hasOwn(record, field)
? record[field]
: { $exists: false };
return filter;
}
for (const branch of seed.branches) {
const matches = branches.filter(
(record) => string(record.code) === branch.code,
);
if (matches.length > 1) {
plan.notes.push({
branchCode: branch.code,
action: "skipped-ambiguous-database-branch",
});
continue;
}
const current = matches[0],
_id = current?._id ?? new mongoose.Types.ObjectId();
branchIds.set(branch.code, _id);
if (!current) {
plan.push({
kind: "branch",
collection: "branches",
document: {
...branch,
_id,
clientKey,
createdAt: new Date(),
updatedAt: new Date(),
},
});
continue;
}
const changes = {};
for (const [field, value] of Object.entries(branch))
if (field !== "code" && empty(current[field]) && !empty(value))
changes[field] = value;
if (Object.keys(changes).length)
plan.push({
kind: "branchUpdate",
collection: "branches",
filter: conditionalUpdate(current, changes),
changes,
});
}
const identifiers = seed.experts.map((expert) => expert.nationalCode);
const storedCodes = [
...new Set([
...identifiers,
...identifiers.map((value) => String(Number(value))),
...identifiers.map(Number),
]),
];
const existingByRole = {};
for (const [role, config] of Object.entries(roles))
existingByRole[role] = await db
.collection(config.collection)
.find(
{
$or: [
{ nationalCode: { $in: storedCodes } },
{ username: { $in: identifiers } },
{ email: { $in: identifiers } },
],
},
{ projection: { password: 0, otp: 0, personalDocs: 0 } },
)
.toArray();
for (const expert of seed.experts) {
const matches = {};
for (const role of Object.keys(roles))
matches[role] = existingByRole[role].filter(
(record) =>
string(record.nationalCode).padStart(10, "0") ===
expert.nationalCode ||
record.username === expert.nationalCode ||
record.email === expert.nationalCode,
);
const validExisting = (role) => {
const records = matches[role];
const record = records.length === 1 ? records[0] : null;
return record &&
string(record.clientKey) === string(clientKey) &&
string(record.nationalCode).padStart(10, "0") === expert.nationalCode &&
(!record.role || record.role === role)
? record
: null;
};
for (const role of expert.roles) {
const config = roles[role],
records = matches[role];
const note = (action, details = {}) =>
plan.notes.push({
nationalCode: `******${expert.nationalCode.slice(-4)}`,
role,
action,
...details,
});
if (
records.length > 1 ||
records.some((record) => string(record.clientKey) !== string(clientKey))
) {
note("skipped-ambiguous-or-foreign-insurer-account");
continue;
}
const current = records[0];
if (current && !validExisting(role)) {
note("skipped-different-identity-or-role");
continue;
}
const sourceLocations = expert.roleLocations?.[role] ??
expert.locations ?? [
{
id: expert.branchCode,
name: seed.branches.find(
(branch) => branch.code === expert.branchCode,
)?.name,
},
];
const counterpart =
role === "damage_expert"
? validExisting("file_reviewer")
: role === "file_reviewer"
? validExisting("damage_expert")
: null;
const inheritedBranch =
!current?.branchId &&
counterpart?.branchId &&
branches.find(
(branch) => string(branch._id) === string(counterpart.branchId),
);
const branchId =
current?.branchId ??
(inheritedBranch
? inheritedBranch._id
: branchIds.get(sourceLocations[0]?.id));
const primaryBranch =
branches.find((branch) => string(branch._id) === string(branchId)) ??
seed.branches.find(
(branch) => string(branchIds.get(branch.code)) === string(branchId),
);
if (!branchId || !primaryBranch) {
note("skipped-unresolved-primary-branch");
continue;
}
if (
current?.branchId &&
string(primaryBranch.code) !== sourceLocations[0]?.id
)
note("kept-existing-primary-branch", {
primaryBranchCode: string(primaryBranch.code),
addedBranchCodes: sourceLocations.map((location) => location.id),
});
const locations = mergeLocations(
current?.locations ?? [],
[{ id: primaryBranch.code, name: primaryBranch.name }],
sourceLocations,
!current ? (counterpart?.locations ?? []) : [],
);
const codes = {};
for (const field of config.codes) {
const candidates = field.endsWith("ExpertiseClaim")
? [validExisting("file_reviewer"), validExisting("damage_expert")]
: [validExisting("file_maker"), validExisting("damage_expert")];
const inherited = candidates
.map((record) => record?.[field])
.find(
(value) =>
/^\d+$/.test(string(value)) &&
Number(value) > 0 &&
Number.isSafeInteger(Number(value)),
);
if (!empty(inherited) || !empty(expert[field]))
codes[field] = string(inherited ?? expert[field]);
if (
!empty(current?.[field]) &&
!empty(expert[field]) &&
string(current[field]) !== expert[field]
)
note("kept-existing-code", { field });
}
const values = {
firstName: expert.firstName,
lastName: expert.lastName,
username: expert.nationalCode,
nationalCode: expert.nationalCode,
role,
clientKey,
branchId,
locations,
city: primaryBranch.city,
state: primaryBranch.state,
...(expert.mobile ? { mobile: expert.mobile } : {}),
...(role === "damage_expert"
? { userType: "legal", insuActivityCo: string(clientKey) }
: {}),
...codes,
};
if (!current) {
plan.push({
kind: "create",
collection: config.collection,
role,
document: {
...values,
isActive: true,
otp: "",
createdAt: new Date(),
updatedAt: new Date(),
},
});
continue;
}
const changes = {};
for (const [field, value] of Object.entries(values)) {
if (field === "clientKey") continue;
if (field === "locations") {
if (JSON.stringify(current.locations ?? []) !== JSON.stringify(value))
changes.locations = value;
} else if (
(field === "nationalCode" &&
current.nationalCode !== expert.nationalCode) ||
empty(current[field])
)
changes[field] = value;
}
plan.push({
kind: Object.keys(changes).length ? "update" : "keep",
collection: config.collection,
role,
filter: conditionalUpdate(current, changes),
changes,
});
}
}
return plan;
}
async function indexes(collection) {
try {
return await collection.indexes();
} catch (error) {
if (error.code === 26) return [];
throw error;
}
}
async function ensureEmailIndex(collection) {
const emailKey = (index) =>
Object.keys(index.key ?? {}).length === 1 && index.key.email === 1;
const legacy = (await indexes(collection)).filter(
(index) =>
emailKey(index) &&
index.unique &&
!index.sparse &&
!index.partialFilterExpression,
);
const guard = "remaining_experts_email_guard";
if (legacy.length) {
// Preserve uniqueness of real emails while allowing multiple email-less logins.
await collection.createIndex(
{ email: 1 },
{
name: guard,
unique: true,
partialFilterExpression: { email: { $type: "string" } },
},
);
for (const index of legacy) await collection.dropIndex(index.name);
}
if (
!(await indexes(collection)).some(
(index) => emailKey(index) && index.unique && index.sparse,
)
)
await collection.createIndex(
{ email: 1 },
{ name: "email_1", unique: true, sparse: true },
);
if (
(await indexes(collection)).some(
(index) =>
index.name === guard &&
emailKey(index) &&
index.unique &&
JSON.stringify(index.partialFilterExpression) ===
JSON.stringify({ email: { $type: "string" } }),
)
)
await collection.dropIndex(guard);
}
async function hashPassword() {
const salt = crypto.randomBytes(16).toString("hex");
const derived = await scrypt("123321", salt, 64);
return `${salt}:${derived.toString("hex")}`;
}
async function applyPlan(db, plan, hash = hashPassword) {
await db
.collection("branches")
.createIndex({ clientKey: 1, code: 1 }, { unique: true });
for (const role of new Set(
plan.filter((action) => action.role).map((action) => action.role),
)) {
const collection = db.collection(roles[role].collection);
await ensureEmailIndex(collection);
await collection.createIndex(
role === "damage_expert"
? { nationalCode: 1 }
: { clientKey: 1, nationalCode: 1 },
role === "damage_expert"
? { unique: true }
: { unique: true, sparse: true },
);
}
for (const action of plan) {
const collection = db.collection(action.collection);
if (action.kind === "branch") await collection.insertOne(action.document);
if (action.kind === "create")
await collection.insertOne({
...action.document,
password: await hash(),
});
if (["update", "branchUpdate"].includes(action.kind)) {
const result = await collection.updateOne(action.filter, {
$set: { ...action.changes, updatedAt: new Date() },
});
if (result.matchedCount !== 1)
throw new SeedError(
"An account changed after preflight. Import stopped instead of overwriting it; rerun after reviewing.",
);
}
}
}
async function main(argv = process.argv.slice(2)) {
if (argv.some((arg) => arg !== "--dry-run"))
throw new SeedError("Usage: npm run seed:parsian-remaining -- [--dry-run]");
const dryRun = argv.includes("--dry-run");
const data = loadMergedData();
const config = databaseConfig(),
connection = mongoose.createConnection(config.uri, config.options);
try {
try {
await connection.asPromise();
} catch {
throw new SeedError(
"Could not connect to MongoDB. Check the API environment and TLS settings.",
);
}
const plan = await buildPlan(connection.db);
console.log({
dryRun,
clientCode: data.clientCode,
people: data.experts.length,
branchesToCreate: plan.filter((action) => action.kind === "branch")
.length,
branchesToFill: plan.filter((action) => action.kind === "branchUpdate")
.length,
accountsToCreate: plan.filter((action) => action.kind === "create")
.length,
accountsToFill: plan.filter((action) => action.kind === "update").length,
accountsUnchanged: plan.filter((action) => action.kind === "keep").length,
skippedAccounts: plan.notes.filter(
(note) => note.role && note.action.startsWith("skipped-"),
).length,
mergeNotes: plan.notes,
skippedSpreadsheetRows: data.skippedRows.flatMap((row) => row.rows),
});
if (dryRun) return;
await applyPlan(connection.db, plan);
console.log(
"Combined Parsian experts seeded successfully. Existing passwords, primary branches, codes and active states were preserved.",
);
} finally {
await connection.close();
}
}
if (require.main === module)
main().catch((error) => {
console.error(
error instanceof SeedError
? error.message
: "Seed stopped because of a database/index error. Existing passwords were not reset. Review a dry-run before retrying.",
);
process.exitCode = 1;
});
module.exports = {
validateData,
loadMergedData,
mergeLocations,
buildPlan,
applyPlan,
hashPassword,
ensureEmailIndex,
main,
};