forked from Yara724/api
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.
This commit is contained in:
@@ -0,0 +1,36 @@
|
||||
# Combined Parsian expert seed
|
||||
|
||||
The seed merges the original `branches.json`, `file-reviewers.json`, `file-makers.json`, the assessor records in `field-experts.json`, and the fixed `remaining-experts.json`. No Excel reader or generation step is needed.
|
||||
|
||||
Run from `api/`, using that API's `.env`:
|
||||
|
||||
```bash
|
||||
npm run seed:parsian-all -- --dry-run
|
||||
npm run seed:parsian-all
|
||||
```
|
||||
|
||||
`npm run seed:parsian-remaining` runs the same combined seed, so the previous command also works. Use this combined seed instead of rerunning the old Tehran seed.
|
||||
|
||||
Combined source totals: **120 people, 50 branches, 88 claim experts, 88 file reviewers and 39 file makers**. Actual inserts depend on the accounts/branches already in the database.
|
||||
|
||||
Merge rules:
|
||||
|
||||
- A national code identifies a person; role + national code identifies an account. Existing account IDs, passwords, email/username aliases and activation states are retained. New accounts use national-code usernames and the hashed password `123321`.
|
||||
- Existing primary branches stay unchanged. Additional source locations are merged and deduplicated into `locations`; differing branch lists no longer abort the import. This does not grant multiple primary branches in the application's branch-based authorization.
|
||||
- A new claim/reviewer counterpart inherits the existing counterpart's valid primary branch and assessment codes. File makers retain their own role-specific source locations.
|
||||
- Original JSON product codes take precedence over conflicting values in the remaining list. Existing database codes take precedence over imported values. Missing codes are filled; differing existing codes are kept and reported as merge notes, without stopping the batch.
|
||||
- Missing branches are created. Existing branch data is preserved, and missing details can be filled from the original directory. New branches without an address keep it blank. No address, contact or Fanavaran code is invented.
|
||||
- Ambiguous duplicate accounts, identities belonging to another insurer, incorrect stored roles, or unresolved primary branches are skipped with an explicit note. They are not silently moved, deleted or merged across insurers; the rest of the batch can continue.
|
||||
- No cases, case owners, signatures, SMS or Fanavaran requests are changed.
|
||||
|
||||
The reported reviewer ending **8521** remains at their existing primary branch and gains the additional source location. The assessment-code differences for the reviewer ending **8118** preserve existing/original codes rather than choosing the new conflicting values.
|
||||
|
||||
The historical `field-experts.json` contains assessor titles; those become claim experts + file reviewers, not FIELD_EXPERT accounts. Generic assessors are included without guessing product-specific codes. File-responsible / مسئول خسارت / ثبات titles create file makers only.
|
||||
|
||||
Excel row **37** remains excluded because its national code has 11 digits. The remaining source's `skippedRows` records it. National-code checksum warnings for rows 11, 26 and 27 retain the supplied ten-digit values for verification.
|
||||
|
||||
`--dry-run` performs reads only and prints planned creates, updates, skips and merge notes. Applying ensures the role identity indexes and sparse unique email indexes needed for email-less accounts, with a temporary uniqueness guard during legacy email-index replacement (MongoDB 5.0+). Keep the corresponding API changes supporting claim experts without email/mobile.
|
||||
|
||||
The seed is resumable. If an unexpected database/index error occurs, earlier successful writes remain. Conditional updates reject concurrent edits instead of overwriting them. Re-running merges the data again without resetting passwords or duplicating accounts.
|
||||
|
||||
Regression tests: `node scripts/data/parsian-tehran/seed-remaining-experts.test.cjs`.
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,663 @@
|
||||
#!/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,
|
||||
};
|
||||
@@ -0,0 +1,390 @@
|
||||
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: "ویرایش همزمان" },
|
||||
]);
|
||||
});
|
||||
Reference in New Issue
Block a user