diff --git a/docs/blame-claim-flow-architecture.html b/docs/blame-claim-flow-architecture.html index 59ce37f..9a99e6e 100644 --- a/docs/blame-claim-flow-architecture.html +++ b/docs/blame-claim-flow-architecture.html @@ -1143,7 +1143,7 @@

Two actors handle the same V3 work split across two controllers. FileMaker (v4/file-maker/blame-request-management/) - handles the party narrative (OTPs, inquiries, details, signatures) and + handles the party narrative (OTPs, inquiries, written details, signatures) and uploads the initial claim documents. FileReviewer (v4/file-reviewer/blame-request-management/) handles the damage assessment pass. The final blame video (upload-video) is a no-op @@ -1204,11 +1204,11 @@

5
- Location · description · voice (guilty) + Written description (guilty; voice optional)
- POST /add-detail-location, /add-detail-description, - /upload-voice + POST /add-detail-description + (location skipped; voice not required)
diff --git a/docs/expert-access-and-optional-voice.md b/docs/expert-access-and-optional-voice.md new file mode 100644 index 0000000..b07a7b4 --- /dev/null +++ b/docs/expert-access-and-optional-voice.md @@ -0,0 +1,45 @@ +# Expert access, multiple roles and optional voice + +## Account activation + +In the expert panel, a super-admin selects an insurer, opens **اعضا و کارشناسان → مدیریت**, and uses **غیرفعال کردن / فعال کردن** beside the relevant role account. Insurers can see the status but cannot change it. + +The endpoint is: + +```http +PATCH /super-admin/management/staff/:role/:id/status?clientId= +Authorization: Bearer +Content-Type: application/json + +{"isActive": false} +``` + +Only a boolean is accepted. The selected account must belong to the supplied insurer. The response excludes passwords and OTPs. The general staff-edit endpoints, including insurer endpoints, do not accept `isActive`. + +Supported roles: `expert`, `damage_expert`, `field_expert`, `file_maker`, `file_reviewer`, `call_center`. Disabling one role account does not disable another role account belonging to the same person. Login and protected expert requests check the saved flag; previously issued tokens cannot be used while that account is disabled. Existing documents without `isActive` are treated as active. + +No existing account, password, case owner or assignment is migrated. Deploy the API before the updated expert UI. No database backfill or index deletion is needed. + +## Same person in several flows + +Create an account for each required role using the same national code, email and password. Continue using the existing login URLs and role selectors. For example, one person can log into `/v4/expert-login` as either a file maker or a file reviewer with the same credentials, provided both assignments have been created. The expert panel likewise uses its existing role selector. + +The creation and edit checks now reject duplicate identifiers **within the selected role**, rather than across all roles. Role collections already have separate indexes, so cross-role reuse requires no production index changes. Within-role uniqueness remains important because login has no insurer selector. This change does not grant another role automatically or merge existing records. + +Credentials remain attached to their existing role records. Administrators should enter the same password when adding another role; changing one role's password does not silently overwrite credentials on another production account. National codes on existing accounts should only be corrected after verifying the person's identity. + +## Voice in v4/v5 + +FileMaker flows v4 and v5 no longer display or require the blame voice recorder. Following each party's inquiry, the workflow goes to written details, then signature. Written accident information, car-body description validation, signatures, required documents and reviewer handoff remain in place. + +Older v4/v5 files waiting at `FIRST_VOICE` or `SECOND_VOICE` resume at the corresponding description step. The details page fetches the FileMaker's case through its own `my-files/:requestId` endpoint, with loading/retry states, so reopening does not depend on a previously cached party or case type. The voice-permission notice is also hidden in these flows. Existing recordings, completed-step history and events are retained. The optional upload endpoints are retained for older clients. Other flows keep their voice requirements. The separate claim walk-around video requirement is unchanged. + +## Verification + +- Management tests exercise real Mongoose schemas, cross-role creation/editing, same-role duplicate rejection, activation/reactivation, legacy defaults and tenant boundaries. +- HTTP tests use the real management/auth controllers and JWT guards with isolated repositories to verify login, status permissions, rejection of an old token, and the other role remaining usable. +- Auth tests cover all staff roles and JWT guard entry points. +- Workflow tests cover v4/v5, car-body/third-party, both parties, signatures without voice and older resume states. +- Frontend regression scripts cover the status proxy allowlist and v4/v5 submission without voice while retaining the other flows' requirements. + +Run the API suite with `npm test -- --runInBand`, and each frontend suite with `npm run test:ui`. These checks do not use production data or send SMS messages. diff --git a/docs/insurer-staff-management.md b/docs/insurer-staff-management.md index 2276023..5ef31a8 100644 --- a/docs/insurer-staff-management.md +++ b/docs/insurer-staff-management.md @@ -24,6 +24,7 @@ All endpoints require bearer authentication and strictly validate their DTOs. Sw | Edit insurer login account | `PATCH /super-admin/management/clients/:clientId/accounts/:id` | Unavailable | | List/create staff | `GET/POST /super-admin/management/staff?clientId=...` | `GET/POST /expert-insurer/management/staff` | | Edit staff | `PATCH /super-admin/management/staff/:role/:id?clientId=...` | `PATCH /expert-insurer/management/staff/:role/:id` | +| Activate/deactivate a staff role account | `PATCH /super-admin/management/staff/:role/:id/status?clientId=...` | Unavailable | | List/create branches | `GET/POST /super-admin/management/branches?clientId=...` | `GET/POST /expert-insurer/management/branches` | | Edit branch | `PATCH /super-admin/management/branches/:id?clientId=...` | `PATCH /expert-insurer/management/branches/:id` | @@ -33,7 +34,9 @@ Staff list queries accept `search`, `role`, `page` and `limit` (default 20, capp `role` is one of `expert`, `damage_expert`, `field_expert`, `file_maker`, `file_reviewer`, or `call_center`, and is selected only during creation. These use the existing collections and actor login mechanism. -Staff creation requires `firstName`, `lastName`, a ten-digit `nationalCode` and a password of at least six characters. Email and mobile are optional for field experts, file makers, file reviewers and call-center agents, matching the seed format. Blame and claim experts require email and mobile to match their existing account contracts. Seed-style accounts without email log in using their national code. National-code and email aliases cannot be duplicated across new managed accounts. +Staff creation requires `firstName`, `lastName`, a ten-digit `nationalCode` and a password of at least six characters. Email and mobile are optional for claim experts, field experts, file makers, file reviewers and call-center agents, matching the seed format. Blame experts still require email and mobile. Seed-style accounts without email log in using their national code. National-code and email aliases can be reused across different roles; they remain unique within a role because login has no tenant selector. Create each required role with the same credentials to let one person use several flows. Existing records and passwords are preserved. The remaining-experts seed prepares sparse email indexes for older claim-expert databases before inserting email-less accounts. + +Staff lists include `isActive`, treating older records with no flag as active. Only super-admins can change this flag using the status endpoint and a boolean body, e.g. `{"isActive": false}`. Disabled accounts cannot log in or reuse existing JWTs. Status belongs to the selected role account; the same person's other assignments are unaffected. See [expert access and optional voice](expert-access-and-optional-voice.md). Common optional properties are `branchId`, `phone`, `mobile`, `email`, `city`, `state`, `address` and `expertCode`. A branch, when supplied, must belong to the account's insurer. `expertCode` and the role-specific Fanavaran IDs are positive integer strings, matching existing persistence and mapping contracts. @@ -71,6 +74,6 @@ PATCH sends only changed fields. Omit `password` to preserve it; supply a replac ## Verification -`npm test -- --runInBand` includes schema-backed management tests for all six roles, optional seed fields, role-specific IDs, locations, tenant isolation, branch updates, account passwords, protected fields and strict DTO validation. The route contract keeps the 383 existing routes and adds 18 guarded management routes. +`npm test -- --runInBand` includes schema-backed management tests for all six roles, optional seed fields, role-specific IDs, locations, tenant isolation, branch updates, account passwords, protected fields and strict DTO validation. The route contract retains the existing routes and records the additional super-admin status endpoint. HTTP tests cover cross-role login, activation, status permissions, and rejection of existing sessions after deactivation. The expert UI's `npm run test:ui` includes management proxy and payload regression checks. Desktop/mobile browser checks use mocked local API responses, rather than modifying a real insurer. Live credential login, database indexes under concurrent writes and outbound Fanavaran submission remain integration QA responsibilities. diff --git a/package.json b/package.json index d4ade58..47b1309 100644 --- a/package.json +++ b/package.json @@ -14,6 +14,8 @@ "start:prod": "node dist/main", "sms:test:mic": "ts-node -r tsconfig-paths/register scripts/test-mic-sms.ts", "seed:parsian-tehran": "ts-node scripts/seed-parsian-tehran.ts", + "seed:parsian-remaining": "node scripts/data/parsian-tehran/seed-remaining-experts.js", + "seed:parsian-all": "node scripts/data/parsian-tehran/seed-remaining-experts.js", "seed:reports-fixtures": "ts-node scripts/seed-insurer-reports-fixtures.ts", "lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix", "test": "jest", diff --git a/scripts/data/parsian-tehran/README.md b/scripts/data/parsian-tehran/README.md new file mode 100644 index 0000000..f6e5462 --- /dev/null +++ b/scripts/data/parsian-tehran/README.md @@ -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`. diff --git a/scripts/data/parsian-tehran/remaining-experts.json b/scripts/data/parsian-tehran/remaining-experts.json new file mode 100644 index 0000000..af0f448 --- /dev/null +++ b/scripts/data/parsian-tehran/remaining-experts.json @@ -0,0 +1,1492 @@ +{ + "clientCode": 8, + "branches": [ + { + "code": "265010", + "name": "شعبه رشت", + "fullName": "شعبه رشت(265010)", + "city": "رشت", + "state": "گیلان", + "address": "", + "isActive": true + }, + { + "code": "278012", + "name": "شعبه ساوه", + "fullName": "شعبه ساوه(278012)", + "city": "ساوه", + "state": "مرکزی", + "address": "", + "isActive": true + }, + { + "code": "265014", + "name": "شعبه بندرانزلی", + "fullName": "شعبه بندرانزلی(265014)", + "city": "بندر انزلی", + "state": "گیلان", + "address": "", + "isActive": true + }, + { + "code": "272013", + "name": "شعبه آبادان", + "fullName": "شعبه آبادان(272013)", + "city": "آبادان", + "state": "خوزستان", + "address": "", + "isActive": true + }, + { + "code": "285010", + "name": "شعبه کرمانشاه", + "fullName": "شعبه کرمانشاه (285010)", + "city": "کرمانشاه", + "state": "کرمانشاه", + "address": "", + "isActive": true + }, + { + "code": "293012", + "name": "شعبه شاهرود", + "fullName": "شعبه شاهرود(293012)", + "city": "شاهرود", + "state": "سمنان", + "address": "", + "isActive": true + }, + { + "code": "276010", + "name": "شعبه قم", + "fullName": "شعبه قم( 276010)", + "city": "قم", + "state": "قم", + "address": "", + "isActive": true + }, + { + "code": "250015", + "name": "شعبه تنکابن", + "fullName": "شعبه تنکابن(250015)", + "city": "تنکابن", + "state": "مازندران", + "address": "", + "isActive": true + }, + { + "code": "292011", + "name": "شعبه یاسوج", + "fullName": "شعبه یاسوج(292011)", + "city": "یاسوج", + "state": "کهگیلویه وبویراحمد", + "address": "", + "isActive": true + }, + { + "code": "272010", + "name": "شعبه اهواز", + "fullName": "شعبه اهواز(272010)", + "city": "اهواز", + "state": "خوزستان", + "address": "", + "isActive": true + }, + { + "code": "210120", + "name": "شعبه والفجر", + "fullName": "شعبه والفجر (210120)", + "city": "تهران", + "state": "تهران", + "address": "", + "isActive": true + }, + { + "code": "290012", + "name": "شعبه بروجرد", + "fullName": "شعبه بروجرد(290012)", + "city": "بروجرد", + "state": "لرستان", + "address": "", + "isActive": true + }, + { + "code": "298012", + "name": "شعبه گنبد کاووس", + "fullName": "شعبه گنبد کاووس(298012)", + "city": "گنبدکاووس", + "state": "گلستان", + "address": "", + "isActive": true + }, + { + "code": "260010", + "name": "شعبه بندرعباس", + "fullName": "شعبه بندرعباس(260010)", + "city": "بندرعباس", + "state": "هرمزگان", + "address": "", + "isActive": true + }, + { + "code": "283010", + "name": "شعبه زاهدان", + "fullName": "شعبه زاهدان(283010)", + "city": "زاهدان", + "state": "سیستان و بلوچستان", + "address": "", + "isActive": true + }, + { + "code": "291010", + "name": "شعبه ایلام", + "fullName": "شعبه ایلام(291010)", + "city": "ایلام", + "state": "ایلام", + "address": "", + "isActive": true + }, + { + "code": "281010", + "name": "شعبه ارومیه", + "fullName": "شعبه ارومیه (281010)", + "city": "ارومیه", + "state": "آذربایجان غربی", + "address": "", + "isActive": true + }, + { + "code": "250013", + "name": "شعبه بابل", + "fullName": "شعبه بابل(250013)", + "city": "بابل", + "state": "مازندران", + "address": "", + "isActive": true + }, + { + "code": "265013", + "name": "شعبه لاهیجان", + "fullName": "شعبه لاهیجان(265013)", + "city": "لاهیجان", + "state": "گیلان", + "address": "", + "isActive": true + }, + { + "code": "274012", + "name": "شعبه رفسنجان", + "fullName": "شعبه رفسنجان(274012)", + "city": "رفسنجان", + "state": "کرمان", + "address": "", + "isActive": true + }, + { + "code": "220014", + "name": "شعبه بیرجند", + "fullName": "شعبه بیرجند(220014)", + "city": "بیرجند", + "state": "خراسان جنوبی", + "address": "", + "isActive": true + }, + { + "code": "297011", + "name": "شعبه بوشهر", + "fullName": "شعبه بوشهر (297011)", + "city": "بوشهر", + "state": "بوشهر", + "address": "", + "isActive": true + }, + { + "code": "310010", + "name": "شعبه کرج", + "fullName": "شعبه کرج(310010)", + "city": "کرج", + "state": "البرز", + "address": "", + "isActive": true + }, + { + "code": "296010", + "name": "شعبه یزد", + "fullName": "شعبه یزد(296010)", + "city": "یزد", + "state": "یزد", + "address": "", + "isActive": true + }, + { + "code": "220011", + "name": "شعبه مشهد", + "fullName": "شعبه مشهد(220011)", + "city": "مشهد", + "state": "خراسان رضوی", + "address": "", + "isActive": true + }, + { + "code": "240010", + "name": "شیراز", + "fullName": "شیراز(240010)", + "city": "شیراز", + "state": "فارس", + "address": "", + "isActive": true + }, + { + "code": "220015", + "name": "شعبه نیشابور", + "fullName": "شعبه نیشابور(220015)", + "city": "نیشابور", + "state": "خراسان رضوی", + "address": "", + "isActive": true + }, + { + "code": "294011", + "name": "اردبیل", + "fullName": "اردبیل (294011)", + "city": "اردبیل", + "state": "اردبیل", + "address": "", + "isActive": true + }, + { + "code": "210110", + "name": "شعبه پونک", + "fullName": "شعبه پونک(210110)", + "city": "تهران", + "state": "تهران", + "address": "", + "isActive": true + }, + { + "code": "270010", + "name": "شعبه قزوین", + "fullName": "شعبه قزوین(270010)", + "city": "قزوین", + "state": "قزوین", + "address": "", + "isActive": true + }, + { + "code": "255011", + "name": "شعبه زنجان", + "fullName": "شعبه زنجان(255011)", + "city": "زنجان", + "state": "زنجان", + "address": "", + "isActive": true + }, + { + "code": "278010", + "name": "شعبه اراک", + "fullName": "شعبه اراک (278010)", + "city": "اراک", + "state": "مرکزی", + "address": "", + "isActive": true + }, + { + "code": "250016", + "name": "چالوس", + "fullName": "چالوس(250016)", + "city": "چالوس", + "state": "مازندران", + "address": "", + "isActive": true + }, + { + "code": "272012", + "name": "دزفول", + "fullName": "دزفول(272012)", + "city": "دزفول", + "state": "خوزستان", + "address": "", + "isActive": true + }, + { + "code": "287010", + "name": "همدان", + "fullName": "همدان(287010)", + "city": "همدان", + "state": "همدان", + "address": "", + "isActive": true + }, + { + "code": "245010", + "name": "شعبه تبریز", + "fullName": "شعبه تبریز(245010)", + "city": "تبریز", + "state": "آذربایجان شرقی", + "address": "", + "isActive": true + }, + { + "code": "220013", + "name": "شعبه بجنورد", + "fullName": "شعبه بجنورد (220013)", + "city": "بجنورد", + "state": "خراسان شمالی", + "address": "", + "isActive": true + }, + { + "code": "250010", + "name": "شعبه ساری", + "fullName": "شعبه ساری(250010)", + "city": "ساری", + "state": "مازندران", + "address": "", + "isActive": true + }, + { + "code": "283012", + "name": "چابهار", + "fullName": "چابهار(283012)", + "city": "چابهار", + "state": "چابهار", + "address": "", + "isActive": true + }, + { + "code": "297012", + "name": "شعبه عسلویه", + "fullName": "شعبه عسلویه(297012)", + "city": "عسلویه", + "state": "بوشهر", + "address": "", + "isActive": true + }, + { + "code": "298010", + "name": "گرگان", + "fullName": "گرگان(298010)", + "city": "گرگان", + "state": "گلستان", + "address": "", + "isActive": true + }, + { + "code": "260012", + "name": "شعبه کیش", + "fullName": "شعبه کیش (260012)", + "city": "کیش", + "state": "هرمزگان", + "address": "", + "isActive": true + }, + { + "code": "293010", + "name": "شعبه سمنان", + "fullName": "شعبه سمنان (293010)", + "city": "سمنان", + "state": "سمنان", + "address": "", + "isActive": true + }, + { + "code": "210050", + "name": "شعبه غرب", + "fullName": "شعبه غرب(210050)", + "city": "تهران", + "state": "تهران", + "address": "", + "isActive": true + }, + { + "code": "230010", + "name": "شعبه اصفهان", + "fullName": "شعبه اصفهان (230010)", + "city": "اصفهان", + "state": "اصفهان", + "address": "", + "isActive": true + }, + { + "code": "289011", + "name": "شعبه شهرکرد", + "fullName": "شعبه شهرکرد(289011)", + "city": "شهرکرد", + "state": "چهارمحال و بختیاری", + "address": "", + "isActive": true + }, + { + "code": "286010", + "name": "شعبه سنندج", + "fullName": "شعبه سنندج(286010)", + "city": "سنندج", + "state": "کردستان", + "address": "", + "isActive": true + }, + { + "code": "210040", + "name": "شعبه شرق", + "fullName": "شعبه شرق(210040)", + "city": "تهران", + "state": "تهران", + "address": "", + "isActive": true + } + ], + "experts": [ + { + "nationalCode": "5169608209", + "firstName": "آذرنوش", + "lastName": "حسین زاده سیاه دله", + "mobile": "09118826327", + "branchCode": "265010", + "roles": [ + "damage_expert", + "file_reviewer" + ], + "ThirdPartyExpertiseClaim": "3949", + "CarBodyExpertiseClaim": "3948" + }, + { + "nationalCode": "0603364047", + "firstName": "مهرداد", + "lastName": "محمدی", + "mobile": "09906090143", + "branchCode": "278012", + "roles": [ + "damage_expert", + "file_reviewer" + ] + }, + { + "nationalCode": "2649945915", + "firstName": "سعید", + "lastName": "خزری صیقلی", + "mobile": "09111843216", + "branchCode": "265014", + "roles": [ + "damage_expert", + "file_reviewer" + ], + "CarBodyExpertiseClaim": "5054", + "ThirdPartyExpertiseClaim": "5054" + }, + { + "nationalCode": "2210068754", + "firstName": "علیرضا", + "lastName": "مژدهی طارمسری", + "mobile": "09118174106", + "branchCode": "265014", + "roles": [ + "damage_expert", + "file_reviewer" + ], + "CarBodyExpertiseClaim": "4376", + "ThirdPartyExpertiseClaim": "4376" + }, + { + "nationalCode": "1810049989", + "firstName": "محمد", + "lastName": "محمودی", + "mobile": "09337569794", + "branchCode": "272013", + "roles": [ + "damage_expert", + "file_reviewer" + ], + "ThirdPartyExpertiseClaim": "50256" + }, + { + "nationalCode": "1810049990", + "firstName": "محمد", + "lastName": "محمودی", + "mobile": "09337569794", + "branchCode": "272013", + "roles": [ + "damage_expert", + "file_reviewer" + ], + "CarBodyExpertiseClaim": "50256" + }, + { + "nationalCode": "3860384813", + "firstName": "مهدی", + "lastName": "مهدیان مهر", + "mobile": "09184463606", + "branchCode": "285010", + "roles": [ + "damage_expert", + "file_reviewer" + ], + "ThirdPartyExpertiseClaim": "5071", + "CarBodyExpertiseClaim": "5071" + }, + { + "nationalCode": "3256849350", + "firstName": "محسن", + "lastName": "سهرابی", + "mobile": "09183303545", + "branchCode": "285010", + "roles": [ + "damage_expert", + "file_reviewer" + ], + "ThirdPartyExpertiseClaim": "7310", + "CarBodyExpertiseClaim": "7310" + }, + { + "nationalCode": "4539924583", + "firstName": "مسعود", + "lastName": "فراستی", + "mobile": "09333110600", + "branchCode": "285010", + "roles": [ + "damage_expert", + "file_reviewer" + ], + "ThirdPartyExpertiseClaim": "5194", + "CarBodyExpertiseClaim": "5194" + }, + { + "nationalCode": "4592184858", + "firstName": "ابوالفضل", + "lastName": "آشوری", + "mobile": "09127732689", + "branchCode": "293012", + "roles": [ + "damage_expert", + "file_reviewer" + ], + "ThirdPartyExpertiseClaim": "4333", + "CarBodyExpertiseClaim": "4333" + }, + { + "nationalCode": "2200702000", + "firstName": "فرید", + "lastName": "رضوانی مقدم", + "mobile": "09363404891", + "branchCode": "293012", + "roles": [ + "damage_expert", + "file_reviewer" + ], + "ThirdPartyExpertiseClaim": "4415", + "CarBodyExpertiseClaim": "4415" + }, + { + "nationalCode": "0384788513", + "firstName": "محمدجواد", + "lastName": "شاه محمدی", + "mobile": "09109977285", + "branchCode": "276010", + "roles": [ + "damage_expert", + "file_reviewer" + ], + "ThirdPartyExpertiseClaim": "7493", + "CarBodyExpertiseClaim": "7493" + }, + { + "nationalCode": "2219888649", + "firstName": "سید مصطفی", + "lastName": "نژاد هاشمی", + "mobile": "09113966073", + "branchCode": "250015", + "roles": [ + "damage_expert", + "file_reviewer" + ] + }, + { + "nationalCode": "4231650705", + "firstName": "سید مسعود", + "lastName": "یوسفی", + "mobile": "09171450122", + "branchCode": "292011", + "roles": [ + "damage_expert", + "file_reviewer" + ], + "ThirdPartyExpertiseClaim": "4430" + }, + { + "nationalCode": "1755857535", + "firstName": "مهدی", + "lastName": "دهقان", + "mobile": "09357731291", + "branchCode": "272010", + "roles": [ + "damage_expert", + "file_reviewer" + ], + "ThirdPartyExpertiseClaim": "4362" + }, + { + "nationalCode": "1751496422", + "firstName": "علی اکبر", + "lastName": "امیری", + "mobile": "09167035380", + "branchCode": "272010", + "roles": [ + "damage_expert", + "file_reviewer" + ], + "CarBodyExpertiseClaim": "4442" + }, + { + "nationalCode": "0044009141", + "firstName": "مهدی", + "lastName": "معمارباشی", + "mobile": "09339103762", + "branchCode": "210120", + "roles": [ + "damage_expert", + "file_reviewer" + ], + "ThirdPartyExpertiseClaim": "50043", + "CarBodyExpertiseClaim": "50043" + }, + { + "nationalCode": "0083720397", + "firstName": "مجید", + "lastName": "کاظمی", + "mobile": "09125759960", + "branchCode": "210120", + "roles": [ + "damage_expert", + "file_reviewer" + ], + "ThirdPartyExpertiseClaim": "7429", + "CarBodyExpertiseClaim": "7429" + }, + { + "nationalCode": "4073439219", + "firstName": "محمدجواد", + "lastName": "فرهادی", + "mobile": "09166619910", + "branchCode": "290012", + "roles": [ + "damage_expert", + "file_reviewer" + ], + "ThirdPartyExpertiseClaim": "4479" + }, + { + "nationalCode": "4879886424", + "firstName": "مهدی", + "lastName": "مهاجری", + "mobile": "09364495105", + "branchCode": "298012", + "roles": [ + "damage_expert", + "file_reviewer" + ], + "ThirdPartyExpertiseClaim": "4327", + "CarBodyExpertiseClaim": "4327" + }, + { + "nationalCode": "3470030596", + "firstName": "مهدی", + "lastName": "خادمی پور", + "mobile": "09176942533", + "branchCode": "260010", + "roles": [ + "damage_expert", + "file_reviewer" + ] + }, + { + "nationalCode": "3392078522", + "firstName": "ابراهیم", + "lastName": "ترکی زاده", + "mobile": "09179781239", + "branchCode": "260010", + "roles": [ + "damage_expert", + "file_reviewer" + ] + }, + { + "nationalCode": "4559976171", + "firstName": "وحید", + "lastName": "محمدزاده", + "mobile": "09175801095", + "branchCode": "260010", + "roles": [ + "damage_expert", + "file_reviewer" + ] + }, + { + "nationalCode": "3610060085", + "firstName": "رامین", + "lastName": "مهرپرور", + "mobile": "09151402800", + "branchCode": "283010", + "roles": [ + "file_maker" + ], + "ThirdPartyClaimExpertId": "4428", + "CarBodyClaimExpertId": "4428" + }, + { + "nationalCode": "4490253621", + "firstName": "سیدعلی", + "lastName": "موسوی", + "mobile": "09187418548", + "branchCode": "291010", + "roles": [ + "damage_expert", + "file_reviewer" + ], + "ThirdPartyExpertiseClaim": "4489", + "CarBodyExpertiseClaim": "4489" + }, + { + "nationalCode": "2751828973", + "firstName": "غلامرضا", + "lastName": "عباس زاده", + "mobile": "09141466522", + "branchCode": "281010", + "roles": [ + "damage_expert", + "file_reviewer" + ] + }, + { + "nationalCode": "2050332246", + "firstName": "سعید", + "lastName": "عالمیان درونکلائی", + "mobile": "09111121767", + "branchCode": "250013", + "roles": [ + "damage_expert", + "file_reviewer" + ], + "ThirdPartyExpertiseClaim": "5041", + "CarBodyExpertiseClaim": "5041" + }, + { + "nationalCode": "2691159116", + "firstName": "یاسر", + "lastName": "محمدزاده", + "mobile": "09113453622", + "branchCode": "265013", + "roles": [ + "damage_expert", + "file_reviewer" + ], + "ThirdPartyExpertiseClaim": "7503", + "CarBodyExpertiseClaim": "7503" + }, + { + "nationalCode": "3051391761", + "firstName": "علی", + "lastName": "بشارت", + "mobile": "09132926492", + "branchCode": "274012", + "roles": [ + "damage_expert", + "file_reviewer" + ], + "ThirdPartyExpertiseClaim": "4298" + }, + { + "nationalCode": "3051349259", + "firstName": "سید بهنام", + "lastName": "اوحدی رفسنجانی", + "mobile": "09131915911", + "branchCode": "274012", + "roles": [ + "damage_expert", + "file_reviewer" + ], + "CarBodyExpertiseClaim": "5063" + }, + { + "nationalCode": "0640022669", + "firstName": "ایمان", + "lastName": "دزگی", + "mobile": "09158636164", + "branchCode": "220014", + "roles": [ + "file_maker" + ] + }, + { + "nationalCode": "3521214011", + "firstName": "رضا", + "lastName": "قنبری", + "mobile": "09173064353", + "branchCode": "297011", + "roles": [ + "file_maker" + ] + }, + { + "nationalCode": "0945253028", + "firstName": "افشین", + "lastName": "سمیعی", + "mobile": "09123638553", + "branchCode": "310010", + "roles": [ + "damage_expert", + "file_reviewer" + ] + }, + { + "nationalCode": "0321665090", + "firstName": "مهدی", + "lastName": "کلانتری", + "mobile": "09125162285", + "branchCode": "310010", + "roles": [ + "damage_expert", + "file_reviewer" + ] + }, + { + "nationalCode": "5809527825", + "firstName": "کامران", + "lastName": "کریمی", + "branchCode": "310010", + "roles": [ + "damage_expert", + "file_reviewer" + ] + }, + { + "nationalCode": "4432410302", + "firstName": "علی", + "lastName": "حسنی قوام آباد", + "mobile": "09132506731", + "branchCode": "296010", + "roles": [ + "damage_expert", + "file_reviewer" + ], + "ThirdPartyExpertiseClaim": "7222", + "CarBodyExpertiseClaim": "7222" + }, + { + "nationalCode": "4450000129", + "firstName": "محمد", + "lastName": "خانی", + "mobile": "09132578168", + "branchCode": "296010", + "roles": [ + "damage_expert", + "file_reviewer" + ], + "CarBodyExpertiseClaim": "5002", + "ThirdPartyExpertiseClaim": "5002" + }, + { + "nationalCode": "0932313884", + "firstName": "هاشم", + "lastName": "عطائی گوجگی", + "mobile": "09336750473", + "branchCode": "220011", + "roles": [ + "damage_expert", + "file_reviewer" + ], + "ThirdPartyExpertiseClaim": "7367" + }, + { + "nationalCode": "0931388864", + "firstName": "محمد", + "lastName": "قادری", + "mobile": "09393114979", + "branchCode": "220011", + "roles": [ + "damage_expert", + "file_reviewer" + ], + "CarBodyExpertiseClaim": "7366" + }, + { + "nationalCode": "2470815967", + "firstName": "مهدی", + "lastName": "هنری", + "mobile": "09337111700", + "branchCode": "240010", + "roles": [ + "damage_expert", + "file_reviewer" + ], + "CarBodyExpertiseClaim": "1917520", + "ThirdPartyExpertiseClaim": "1917520" + }, + { + "nationalCode": "2291268422", + "firstName": "جواد", + "lastName": "مهندسان", + "mobile": "09178863008", + "branchCode": "240010", + "roles": [ + "damage_expert", + "file_reviewer" + ], + "CarBodyExpertiseClaim": "1917589", + "ThirdPartyExpertiseClaim": "1917589" + }, + { + "nationalCode": "0078976596", + "firstName": "رضا", + "lastName": "سلیمانی", + "mobile": "09375223585", + "branchCode": "220015", + "roles": [ + "damage_expert", + "file_reviewer" + ], + "ThirdPartyExpertiseClaim": "4410" + }, + { + "nationalCode": "1465384634", + "firstName": "داود", + "lastName": "دلاور گندیشمین", + "mobile": "09113953266", + "branchCode": "294011", + "roles": [ + "damage_expert", + "file_reviewer" + ], + "ThirdPartyExpertiseClaim": "7462" + }, + { + "nationalCode": "1466133211", + "firstName": "سیامک", + "lastName": "نعمتی اردبیلی", + "mobile": "09144561347", + "branchCode": "294011", + "roles": [ + "damage_expert", + "file_reviewer" + ], + "ThirdPartyExpertiseClaim": "7240" + }, + { + "nationalCode": "0066868521", + "firstName": "علیرضا", + "lastName": "گودرزی پور", + "mobile": "09129344240", + "branchCode": "210110", + "roles": [ + "damage_expert", + "file_reviewer" + ] + }, + { + "nationalCode": "0076988961", + "firstName": "مهدی", + "lastName": "روشن دل", + "mobile": "09108357378", + "branchCode": "210110", + "roles": [ + "damage_expert", + "file_reviewer" + ] + }, + { + "nationalCode": "0493217789", + "firstName": "مصطفی", + "lastName": "محمدزاده", + "mobile": "09126966943", + "branchCode": "210110", + "roles": [ + "damage_expert", + "file_reviewer" + ] + }, + { + "nationalCode": "0311161634", + "firstName": "زهرا", + "lastName": "فتحی", + "mobile": "09102006939", + "branchCode": "210110", + "roles": [ + "damage_expert", + "file_reviewer" + ] + }, + { + "nationalCode": "4380169499", + "firstName": "شهاب", + "lastName": "اسدی", + "mobile": "09127817503", + "branchCode": "270010", + "roles": [ + "damage_expert", + "file_reviewer" + ], + "ThirdPartyExpertiseClaim": "1916994", + "CarBodyExpertiseClaim": "1916994" + }, + { + "nationalCode": "4284493124", + "firstName": "اصغر", + "lastName": "رضائی", + "mobile": "09192771214", + "branchCode": "255011", + "roles": [ + "damage_expert", + "file_reviewer" + ], + "ThirdPartyExpertiseClaim": "7483" + }, + { + "nationalCode": "0533481309", + "firstName": "مجید", + "lastName": "مشهدی", + "mobile": "09188496672", + "branchCode": "278010", + "roles": [ + "damage_expert", + "file_reviewer" + ], + "ThirdPartyExpertiseClaim": "3041" + }, + { + "nationalCode": "0621490865", + "firstName": "مجید", + "lastName": "بهرامی", + "mobile": "09183677752", + "branchCode": "278010", + "roles": [ + "damage_expert", + "file_reviewer" + ], + "CarBodyExpertiseClaim": "992" + }, + { + "nationalCode": "6279929299", + "firstName": "یاسر", + "lastName": "پوربهرام", + "mobile": "09113914071", + "branchCode": "250016", + "roles": [ + "damage_expert", + "file_reviewer" + ], + "ThirdPartyExpertiseClaim": "1091", + "CarBodyExpertiseClaim": "1092" + }, + { + "nationalCode": "2003265228", + "firstName": "امین", + "lastName": "روغن چراغی", + "mobile": "09377423801", + "branchCode": "272012", + "roles": [ + "damage_expert", + "file_reviewer" + ], + "ThirdPartyExpertiseClaim": "4368", + "CarBodyExpertiseClaim": "4368" + }, + { + "nationalCode": "6169850612", + "firstName": "حسین", + "lastName": "فتحی", + "mobile": "09181411355", + "branchCode": "287010", + "roles": [ + "file_maker" + ] + }, + { + "nationalCode": "4051649725", + "firstName": "احمد", + "lastName": "فخاری همت", + "mobile": "09013163863", + "branchCode": "287010", + "roles": [ + "file_maker" + ] + }, + { + "nationalCode": "1370868431", + "firstName": "محمد حسن", + "lastName": "رونقی", + "mobile": "09144161227", + "branchCode": "245010", + "roles": [ + "damage_expert", + "file_reviewer" + ], + "ThirdPartyExpertiseClaim": "7230", + "CarBodyExpertiseClaim": "7230" + }, + { + "nationalCode": "5069919253", + "firstName": "توحید", + "lastName": "نقدی", + "mobile": "09363726604", + "branchCode": "245010", + "roles": [ + "damage_expert", + "file_reviewer" + ], + "ThirdPartyExpertiseClaim": "4342", + "CarBodyExpertiseClaim": "4342" + }, + { + "nationalCode": "1381738672", + "firstName": "کاظم", + "lastName": "تیموری", + "mobile": "09144142155", + "branchCode": "245010", + "roles": [ + "damage_expert", + "file_reviewer" + ], + "ThirdPartyExpertiseClaim": "50760", + "CarBodyExpertiseClaim": "50760" + }, + { + "nationalCode": "0682425990", + "firstName": "فرزاد", + "lastName": "سبحانی", + "mobile": "09374946608", + "branchCode": "220013", + "roles": [ + "damage_expert", + "file_reviewer" + ] + }, + { + "nationalCode": "0681371919", + "firstName": "محمود", + "lastName": "رستمی", + "mobile": "09155847945", + "branchCode": "220013", + "roles": [ + "damage_expert", + "file_reviewer" + ], + "CarBodyExpertiseClaim": "2704480" + }, + { + "nationalCode": "5769987456", + "firstName": "شهرام", + "lastName": "رجبی", + "mobile": "09120223373", + "branchCode": "250010", + "roles": [ + "damage_expert", + "file_reviewer" + ], + "CarBodyExpertiseClaim": "50497", + "ThirdPartyExpertiseClaim": "50497" + }, + { + "nationalCode": "2150037191", + "firstName": "سهیل", + "lastName": "علی نیا نجار", + "mobile": "09364780669", + "branchCode": "250010", + "roles": [ + "damage_expert", + "file_reviewer" + ], + "ThirdPartyExpertiseClaim": "4370", + "CarBodyExpertiseClaim": "4370" + }, + { + "nationalCode": "3610886420", + "firstName": "ابوالفضل", + "lastName": "مهر پرور", + "mobile": "09135934461", + "branchCode": "283012", + "roles": [ + "damage_expert", + "file_reviewer" + ] + }, + { + "nationalCode": "3510094727", + "firstName": "منصور", + "lastName": "غلامی", + "mobile": "09170129203", + "branchCode": "297012", + "roles": [ + "damage_expert", + "file_reviewer" + ], + "ThirdPartyExpertiseClaim": "50717", + "CarBodyExpertiseClaim": "50717" + }, + { + "nationalCode": "2240161140", + "firstName": "رجب", + "lastName": "کشیری", + "mobile": "09376423491", + "branchCode": "298010", + "roles": [ + "damage_expert", + "file_reviewer" + ], + "ThirdPartyExpertiseClaim": "1917047", + "CarBodyExpertiseClaim": "1917047" + }, + { + "nationalCode": "2269870514", + "firstName": "سید محمدرضا", + "lastName": "میرجنگلده", + "mobile": "09119978984", + "branchCode": "298010", + "roles": [ + "damage_expert", + "file_reviewer" + ], + "ThirdPartyExpertiseClaim": "1742032", + "CarBodyExpertiseClaim": "1742032" + }, + { + "nationalCode": "0067703666", + "firstName": "علی", + "lastName": "شربتی", + "mobile": "09113711768", + "branchCode": "298010", + "roles": [ + "file_maker" + ], + "ThirdPartyClaimExpertId": "1917766", + "CarBodyClaimExpertId": "1917766" + }, + { + "nationalCode": "1091200904", + "firstName": "رضا", + "lastName": "منتظری نجف آبادی", + "mobile": "09133310979", + "branchCode": "260012", + "roles": [ + "damage_expert", + "file_reviewer" + ], + "ThirdPartyExpertiseClaim": "5095", + "CarBodyExpertiseClaim": "5095" + }, + { + "nationalCode": "2093576351", + "firstName": "علی", + "lastName": "امیری", + "mobile": "09115211100", + "branchCode": "260012", + "roles": [ + "damage_expert", + "file_reviewer" + ], + "ThirdPartyExpertiseClaim": "4320", + "CarBodyExpertiseClaim": "4320" + }, + { + "nationalCode": "6429972623", + "firstName": "حسین", + "lastName": "احمدی", + "mobile": "09369685025", + "branchCode": "293010", + "roles": [ + "damage_expert", + "file_reviewer" + ] + }, + { + "nationalCode": "0321819276", + "firstName": "حسین", + "lastName": "عبداله دخت", + "mobile": "09120852454", + "branchCode": "210050", + "roles": [ + "damage_expert", + "file_reviewer" + ] + }, + { + "nationalCode": "0084130938", + "firstName": "رسول", + "lastName": "کرکی", + "mobile": "09120852454", + "branchCode": "210050", + "roles": [ + "damage_expert", + "file_reviewer" + ] + }, + { + "nationalCode": "2595546929", + "firstName": "ابراهیم", + "lastName": "طبع خوشنود", + "mobile": "09113336134", + "branchCode": "265010", + "roles": [ + "damage_expert", + "file_reviewer" + ], + "ThirdPartyExpertiseClaim": "7264", + "CarBodyExpertiseClaim": "7264" + }, + { + "nationalCode": "2679790588", + "firstName": "محمد", + "lastName": "غلامی کلدهی", + "mobile": "09112367964", + "branchCode": "265010", + "roles": [ + "damage_expert", + "file_reviewer" + ], + "ThirdPartyExpertiseClaim": "7266", + "CarBodyExpertiseClaim": "7266" + }, + { + "nationalCode": "1286128307", + "firstName": "اسماعیل", + "lastName": "مومنی", + "mobile": "09135727030", + "branchCode": "230010", + "roles": [ + "damage_expert", + "file_reviewer" + ], + "ThirdPartyExpertiseClaim": "55", + "CarBodyExpertiseClaim": "55" + }, + { + "nationalCode": "1219911763", + "firstName": "میثم", + "lastName": "بستاکی", + "mobile": "09132712047", + "branchCode": "230010", + "roles": [ + "damage_expert", + "file_reviewer" + ], + "ThirdPartyExpertiseClaim": "4166", + "CarBodyExpertiseClaim": "4166" + }, + { + "nationalCode": "2380300488", + "firstName": "علی", + "lastName": "امینی", + "mobile": "09177883061", + "branchCode": "230010", + "roles": [ + "damage_expert", + "file_reviewer" + ] + }, + { + "nationalCode": "4620157015", + "firstName": "امیر", + "lastName": "حیدری", + "mobile": "09131073299", + "branchCode": "230010", + "roles": [ + "damage_expert", + "file_reviewer" + ] + }, + { + "nationalCode": "4232176764", + "firstName": "ستار", + "lastName": "عادل نژاد اصل", + "mobile": "09177413685", + "branchCode": "289011", + "roles": [ + "damage_expert", + "file_reviewer" + ], + "ThirdPartyExpertiseClaim": "50680", + "CarBodyExpertiseClaim": "50680" + }, + { + "nationalCode": "3761485123", + "firstName": "هادی", + "lastName": "سعیدی", + "mobile": "09186579547", + "branchCode": "286010", + "roles": [ + "damage_expert", + "file_reviewer" + ], + "ThirdPartyExpertiseClaim": "2172" + }, + { + "nationalCode": "3720318222", + "firstName": "آروین", + "lastName": "قصیری", + "mobile": "09189695321", + "branchCode": "286010", + "roles": [ + "damage_expert", + "file_reviewer" + ], + "ThirdPartyExpertiseClaim": "5093", + "CarBodyExpertiseClaim": "5093" + }, + { + "nationalCode": "0670358118", + "firstName": "مجید", + "lastName": "امیری", + "mobile": "09124421539", + "branchCode": "210040", + "roles": [ + "damage_expert", + "file_reviewer" + ], + "ThirdPartyExpertiseClaim": "5121", + "CarBodyExpertiseClaim": "5121" + }, + { + "nationalCode": "0013480261", + "firstName": "علیرضا", + "lastName": "خازنی", + "mobile": "09360096643", + "branchCode": "210040", + "roles": [ + "damage_expert", + "file_reviewer" + ], + "ThirdPartyExpertiseClaim": "5081", + "CarBodyExpertiseClaim": "5081" + }, + { + "nationalCode": "3932143930", + "firstName": "محسن", + "lastName": "کرمی", + "mobile": "09366354052", + "branchCode": "210040", + "roles": [ + "damage_expert", + "file_reviewer" + ], + "ThirdPartyExpertiseClaim": "3259", + "CarBodyExpertiseClaim": "3259" + }, + { + "nationalCode": "0069608210", + "firstName": "عباس", + "lastName": "سلطانی محمدی", + "mobile": "09120766792", + "branchCode": "210040", + "roles": [ + "damage_expert", + "file_reviewer" + ], + "ThirdPartyExpertiseClaim": "7622", + "CarBodyExpertiseClaim": "7622" + } + ], + "skippedRows": [ + { + "rows": [ + 37 + ], + "reason": "National code must contain 8–10 digits; an 11-digit value is never truncated." + } + ] +} diff --git a/scripts/data/parsian-tehran/seed-remaining-experts.js b/scripts/data/parsian-tehran/seed-remaining-experts.js new file mode 100644 index 0000000..a6a95ad --- /dev/null +++ b/scripts/data/parsian-tehran/seed-remaining-experts.js @@ -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, +}; diff --git a/scripts/data/parsian-tehran/seed-remaining-experts.test.cjs b/scripts/data/parsian-tehran/seed-remaining-experts.test.cjs new file mode 100644 index 0000000..1ef206c --- /dev/null +++ b/scripts/data/parsian-tehran/seed-remaining-experts.test.cjs @@ -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: "ویرایش همزمان" }, + ]); +}); diff --git a/src/auth/auth-services/actor.auth.service.ts b/src/auth/auth-services/actor.auth.service.ts index b863cfc..68c5bd5 100644 --- a/src/auth/auth-services/actor.auth.service.ts +++ b/src/auth/auth-services/actor.auth.service.ts @@ -183,7 +183,9 @@ export class ActorAuthService { dbService: { findOne: (filter: any) => Promise }, identifier: string, ) { - const id = identifier.trim(); + const id = identifier.includes("@") + ? identifier.trim().toLowerCase() + : identifier.trim(); const or: Record[] = [{ email: id }, { username: id }]; if (/^\d{10}$/.test(id)) { or.push({ nationalCode: id }); @@ -234,9 +236,47 @@ export class ActorAuthService { if (!(await this.hashService.compare(pass, user.password))) { throw new UnauthorizedException("نام کاربری یا رمز عبور اشتباه است"); } + this.assertActive(user); return user; } + private assertActive(actor: { isActive?: boolean }) { + // Legacy accounts have no flag and remain active. + if (actor.isActive === false) + throw new UnauthorizedException( + "حساب کاری شما غیرفعال شده است. با مدیر سامانه تماس بگیرید.", + ); + } + + /** Recheck persisted status so a disabled account cannot reuse an old JWT. */ + async assertActorActive(payload: { role?: string; sub?: string }) { + if ( + ![ + RoleEnum.EXPERT, + RoleEnum.DAMAGE_EXPERT, + RoleEnum.FIELD_EXPERT, + RoleEnum.FILE_MAKER, + RoleEnum.FILE_REVIEWER, + RoleEnum.CALL_CENTER, + ].includes(payload?.role as RoleEnum) + ) + return; + if (!payload.sub || !Types.ObjectId.isValid(payload.sub)) + throw new UnauthorizedException( + "حساب کاربری معتبر نیست. دوباره وارد شوید.", + ); + const actor = await this.dynamicDbController( + payload.role, + null, + payload.sub, + ); + if (!actor) + throw new UnauthorizedException( + "حساب کاربری یافت نشد. دوباره وارد شوید.", + ); + this.assertActive(actor); + } + /** * Authenticates an actor from a login request body (role, username/email, password). */ diff --git a/src/auth/auth-services/expert-role-access.spec.ts b/src/auth/auth-services/expert-role-access.spec.ts new file mode 100644 index 0000000..f9a5ace --- /dev/null +++ b/src/auth/auth-services/expert-role-access.spec.ts @@ -0,0 +1,226 @@ +import { ExecutionContext, UnauthorizedException } from "@nestjs/common"; +import { Types } from "mongoose"; +import { ActorAuthService } from "./actor.auth.service"; +import { RoleEnum } from "src/Types&Enums/role.enum"; +import { GlobalGuard } from "../guards/global.guard"; +import { LocalActorAuthGuard } from "../guards/actor-local.guard"; +import { SettingsJwtGuard } from "../guards/settings-jwt.guard"; +import { AuthGuard } from "src/common/auth/guards/auth.guard"; +import { ClaimAccessGuard } from "../guards/claim-access.guard"; +import { ExpertInsurerService } from "src/expert-insurer/expert-insurer.service"; + +const roles = [ + RoleEnum.EXPERT, + RoleEnum.DAMAGE_EXPERT, + RoleEnum.FIELD_EXPERT, + RoleEnum.FILE_MAKER, + RoleEnum.FILE_REVIEWER, + RoleEnum.CALL_CENTER, +]; +const dbNames = [ + "expertDbService", + "damageExpertDbService", + "fieldExpertDbService", + "fileMakerDbService", + "fileReviewerDbService", + "callCenterAgentDbService", +]; + +function setup() { + const service = new (ActorAuthService as any)() as ActorAuthService; + const actors = roles.map((role) => ({ + _id: new Types.ObjectId(), + role, + email: "person@example.test", + nationalCode: "0012345678", + password: "hash:shared-password", + })); + const dbs = actors.map((actor, index) => { + const db = { + findOne: jest.fn().mockResolvedValue(actor), + findByLoginIdentifier: jest.fn().mockResolvedValue(actor), + }; + (service as any)[dbNames[index]] = db; + return db; + }); + (service as any).hashService = { + compare: jest.fn(async (plain, hashed) => `hash:${plain}` === hashed), + }; + return { service, actors, dbs }; +} + +describe("expert role identities and activation", () => { + it.each(["person@example.test", "0012345678"])( + "authenticates the same %s and password in every assigned role", + async (identifier) => { + const { service, actors, dbs } = setup(); + for (const [index, role] of roles.entries()) { + expect( + await service.validateActor(identifier, "shared-password", role), + ).toBe(actors[index]); + expect( + dbs[index].findOne.mock.calls.length + + dbs[index].findByLoginIdentifier.mock.calls.length, + ).toBe(1); + } + for (const db of dbs) + expect( + db.findOne.mock.calls.length + + db.findByLoginIdentifier.mock.calls.length, + ).toBe(1); + }, + ); + it.each(roles)( + "blocks inactive %s login and tokens, with legacy-active and reactivation support", + async (role) => { + const { service, actors } = setup(); + const actor: any = actors[roles.indexOf(role)]; + const token = { role, sub: String(actor._id) }; + await expect( + service.validateActor(actor.email, "shared-password", role), + ).resolves.toBe(actor); + await expect(service.assertActorActive(token)).resolves.toBeUndefined(); + actor.isActive = false; + await expect( + service.validateActor(actor.email, "shared-password", role), + ).rejects.toThrow("غیرفعال"); + await expect(service.assertActorActive(token)).rejects.toThrow("غیرفعال"); + actor.isActive = true; + await expect( + service.validateActor(actor.nationalCode, "shared-password", role), + ).resolves.toBe(actor); + }, + ); + it("disabling the maker leaves the reviewer's credentials and access intact", async () => { + const { service, actors } = setup(); + (actors[3] as any).isActive = false; + await expect( + service.validateActor( + "0012345678", + "shared-password", + RoleEnum.FILE_MAKER, + ), + ).rejects.toThrow("غیرفعال"); + await expect( + service.validateActor( + "0012345678", + "shared-password", + RoleEnum.FILE_REVIEWER, + ), + ).resolves.toBe(actors[4]); + await expect( + service.validateActor( + "0012345678", + "wrong-password", + RoleEnum.FILE_REVIEWER, + ), + ).rejects.toBeInstanceOf(UnauthorizedException); + }); + it("does not resolve ordinary user, insurer or super-admin JWTs through expert storage", async () => { + const { service, dbs } = setup(); + for (const role of [RoleEnum.USER, RoleEnum.COMPANY, RoleEnum.SUPER_ADMIN]) + await service.assertActorActive({ role, sub: "existing-subject" }); + for (const db of dbs) expect(db.findOne).not.toHaveBeenCalled(); + }); + it("rejects missing/deleted expert subjects", async () => { + const { service, dbs } = setup(); + await expect( + service.assertActorActive({ role: RoleEnum.EXPERT, sub: "bad-id" }), + ).rejects.toBeInstanceOf(UnauthorizedException); + dbs[0].findOne.mockResolvedValue(null); + await expect( + service.assertActorActive({ + role: RoleEnum.EXPERT, + sub: String(new Types.ObjectId()), + }), + ).rejects.toBeInstanceOf(UnauthorizedException); + }); +}); + +describe("expert access status at every JWT entry point", () => { + it.each(["actor", "user-panel", "settings", "common", "claim"])( + "checks current account state in %s guard", + async (entry) => { + const auth = { assertActorActive: jest.fn() }; + const payload = { + role: entry === "claim" ? RoleEnum.DAMAGE_EXPERT : RoleEnum.FILE_MAKER, + sub: String(new Types.ObjectId()), + }; + const jwt = { verifyAsync: jest.fn().mockResolvedValue(payload) }; + const guard = + entry === "actor" + ? new LocalActorAuthGuard(auth as any, jwt as any) + : entry === "user-panel" + ? new GlobalGuard(jwt as any, auth as any) + : entry === "settings" + ? new SettingsJwtGuard(jwt as any, auth as any) + : entry === "claim" + ? new ClaimAccessGuard(jwt as any, {} as any, auth as any) + : new AuthGuard(jwt as any, auth as any); + const request = { + headers: { authorization: "Bearer existing-token" }, + url: "/protected", + }; + const context = { + switchToHttp: () => ({ getRequest: () => request }), + } as ExecutionContext; + await expect(guard.canActivate(context)).resolves.toBe(true); + expect(auth.assertActorActive).toHaveBeenCalledWith(payload); + auth.assertActorActive.mockRejectedValue( + new UnauthorizedException("حساب کاری غیرفعال است."), + ); + await expect(guard.canActivate(context)).rejects.toThrow("غیرفعال"); + }, + ); +}); + +describe("older insurer expert-creation endpoints", () => { + it.each([RoleEnum.EXPERT, RoleEnum.DAMAGE_EXPERT])( + "limits duplicate checks to the selected %s role", + async (role) => { + const service = new (ExpertInsurerService as any)() as any; + const key = new Types.ObjectId(); + service.getClientId = () => key; + service.assertBranchBelongsToClient = async () => ({ + _id: new Types.ObjectId(), + name: "شعبه", + }); + service.hashService = { hash: async () => "hash:password" }; + service.sanitizeExpertResponse = (value) => ({ role: value.role }); + const makeDb = () => ({ + findOne: jest.fn().mockResolvedValue(null), + create: jest.fn(async (body) => body), + }); + service.expertDbService = makeDb(); + service.damageExpertDbService = makeDb(); + const selected = + role === RoleEnum.EXPERT + ? service.expertDbService + : service.damageExpertDbService; + const other = + role === RoleEnum.EXPERT + ? service.damageExpertDbService + : service.expertDbService; + other.findOne.mockResolvedValue({ + nationalCode: "0012345678", + email: "person@example.test", + }); + await service.createExpertForInsurer( + String(key), + { + email: "person@example.test", + nationalCode: "0012345678", + password: "password", + branchId: String(new Types.ObjectId()), + firstName: "علی", + lastName: "احمدی", + }, + role, + ); + expect(selected.create).toHaveBeenCalledWith( + expect.objectContaining({ role, email: "person@example.test" }), + ); + expect(other.findOne).not.toHaveBeenCalled(); + }, + ); +}); diff --git a/src/auth/guards/actor-local.guard.spec.ts b/src/auth/guards/actor-local.guard.spec.ts index d1ab88e..9eaff1e 100644 --- a/src/auth/guards/actor-local.guard.spec.ts +++ b/src/auth/guards/actor-local.guard.spec.ts @@ -4,15 +4,17 @@ import { LocalActorAuthGuard } from "./actor-local.guard"; describe("LocalActorAuthGuard", () => { const credentials = { username: "new-account", password: "test-password" }; - let auth: { loginFromCredentials: jest.Mock }; + let auth: { loginFromCredentials: jest.Mock; assertActorActive: jest.Mock }; let jwt: { verifyAsync: jest.Mock }; let guard: LocalActorAuthGuard; const context = (request: Record) => - ({ switchToHttp: () => ({ getRequest: () => request }) }) as ExecutionContext; + ({ + switchToHttp: () => ({ getRequest: () => request }), + }) as ExecutionContext; beforeEach(() => { - auth = { loginFromCredentials: jest.fn() }; + auth = { loginFromCredentials: jest.fn(), assertActorActive: jest.fn() }; jwt = { verifyAsync: jest.fn() }; guard = new LocalActorAuthGuard(auth as any, jwt as any); }); @@ -38,14 +40,19 @@ describe("LocalActorAuthGuard", () => { it("does not let a previous token bypass failed credentials or captcha", async () => { auth.loginFromCredentials.mockRejectedValue(new UnauthorizedException()); - jwt.verifyAsync.mockResolvedValue({ sub: "old-account", role: RoleEnum.EXPERT }); + jwt.verifyAsync.mockResolvedValue({ + sub: "old-account", + role: RoleEnum.EXPERT, + }); await expect( - guard.canActivate(context({ - route: { path: "/actor/login" }, - headers: { authorization: "Bearer previous-session" }, - body: credentials, - })), + guard.canActivate( + context({ + route: { path: "/actor/login" }, + headers: { authorization: "Bearer previous-session" }, + body: credentials, + }), + ), ).rejects.toBeInstanceOf(UnauthorizedException); expect(jwt.verifyAsync).not.toHaveBeenCalled(); }); @@ -58,9 +65,31 @@ describe("LocalActorAuthGuard", () => { headers: { authorization: "Bearer current-session" }, }; await expect(guard.canActivate(context(request))).resolves.toBe(true); - expect(jwt.verifyAsync).toHaveBeenCalledWith("current-session", expect.any(Object)); + expect(jwt.verifyAsync).toHaveBeenCalledWith( + "current-session", + expect.any(Object), + ); expect(auth.loginFromCredentials).not.toHaveBeenCalled(); expect(request["user"]).toBe(payload); + expect(auth.assertActorActive).toHaveBeenCalledWith(payload); + }); + + it("rejects a previously issued token after the account is disabled", async () => { + jwt.verifyAsync.mockResolvedValue({ + sub: "expert-id", + role: RoleEnum.EXPERT, + }); + auth.assertActorActive.mockRejectedValue( + new UnauthorizedException("حساب کاری شما غیرفعال شده است."), + ); + const request = { + url: "/actor/profile", + headers: { authorization: "Bearer old-session" }, + }; + await expect(guard.canActivate(context(request))).rejects.toThrow( + "غیرفعال", + ); + expect(request).not.toHaveProperty("user"); }); it("rejects protected actor routes without a token", async () => { @@ -73,10 +102,12 @@ describe("LocalActorAuthGuard", () => { it("rejects expired tokens on protected routes", async () => { jwt.verifyAsync.mockRejectedValue(new Error("expired")); await expect( - guard.canActivate(context({ - url: "/actor/profile", - headers: { authorization: "Bearer expired-session" }, - })), + guard.canActivate( + context({ + url: "/actor/profile", + headers: { authorization: "Bearer expired-session" }, + }), + ), ).rejects.toBeInstanceOf(UnauthorizedException); }); }); diff --git a/src/auth/guards/actor-local.guard.ts b/src/auth/guards/actor-local.guard.ts index 385a46d..1d8db05 100644 --- a/src/auth/guards/actor-local.guard.ts +++ b/src/auth/guards/actor-local.guard.ts @@ -55,9 +55,11 @@ export class LocalActorAuthGuard implements CanActivate { throw new UnauthorizedException("User role is not authorized"); } + await this.actorAuthService.assertActorActive(payload); request.user = payload; request.identity = request.user; - } catch { + } catch (error) { + if (error instanceof UnauthorizedException) throw error; throw new UnauthorizedException("Invalid token"); } diff --git a/src/auth/guards/claim-access.guard.ts b/src/auth/guards/claim-access.guard.ts index d780a18..31d9d2f 100644 --- a/src/auth/guards/claim-access.guard.ts +++ b/src/auth/guards/claim-access.guard.ts @@ -9,6 +9,7 @@ import { JwtService } from "@nestjs/jwt"; import { RoleEnum } from "src/Types&Enums/role.enum"; import { ClaimRequestManagementDbService } from "src/claim-request-management/entites/db-service/claim-request-management.db.service"; import { Types } from "mongoose"; +import { ActorAuthService } from "src/auth/auth-services/actor.auth.service"; /** * Guard that allows: @@ -20,6 +21,7 @@ export class ClaimAccessGuard implements CanActivate { constructor( private readonly jwtService: JwtService, private readonly claimDbService: ClaimRequestManagementDbService, + private readonly actorAuthService: ActorAuthService, ) {} async canActivate(context: ExecutionContext): Promise { @@ -33,6 +35,7 @@ export class ClaimAccessGuard implements CanActivate { const payload = await this.jwtService.verifyAsync(token, { secret: `${process.env.JWT_SECRET}`, }); + await this.actorAuthService.assertActorActive(payload); // Allow users to pass through (they will be checked by service methods) if (payload.role === RoleEnum.USER) { diff --git a/src/auth/guards/global.guard.ts b/src/auth/guards/global.guard.ts index bed0053..50844d0 100644 --- a/src/auth/guards/global.guard.ts +++ b/src/auth/guards/global.guard.ts @@ -7,18 +7,22 @@ import { import { JwtService } from "@nestjs/jwt"; import { Request } from "express"; import { RoleEnum } from "src/Types&Enums/role.enum"; +import { ActorAuthService } from "src/auth/auth-services/actor.auth.service"; const GLOBAL_GUARD_ROLES = new Set([ RoleEnum.USER, RoleEnum.FIELD_EXPERT, RoleEnum.REGISTRAR, RoleEnum.FILE_MAKER, - RoleEnum.FILE_REVIEWER + RoleEnum.FILE_REVIEWER, ]); @Injectable() export class GlobalGuard implements CanActivate { - constructor(private readonly jwtService: JwtService) {} + constructor( + private readonly jwtService: JwtService, + private readonly actorAuthService: ActorAuthService, + ) {} async canActivate(context: ExecutionContext): Promise { const request = context.switchToHttp().getRequest(); @@ -39,6 +43,7 @@ export class GlobalGuard implements CanActivate { ); } + await this.actorAuthService.assertActorActive(payload); request.user = payload; request.identity = request.user; } catch (error) { diff --git a/src/auth/guards/settings-jwt.guard.ts b/src/auth/guards/settings-jwt.guard.ts index 9bfe482..4cf66b5 100644 --- a/src/auth/guards/settings-jwt.guard.ts +++ b/src/auth/guards/settings-jwt.guard.ts @@ -6,6 +6,7 @@ import { } from "@nestjs/common"; import { JwtService } from "@nestjs/jwt"; import { Request } from "express"; +import { ActorAuthService } from "src/auth/auth-services/actor.auth.service"; /** * Verifies Bearer JWT for platform settings routes. Does not restrict by role; @@ -13,7 +14,10 @@ import { Request } from "express"; */ @Injectable() export class SettingsJwtGuard implements CanActivate { - constructor(private readonly jwtService: JwtService) {} + constructor( + private readonly jwtService: JwtService, + private readonly actorAuthService: ActorAuthService, + ) {} async canActivate(context: ExecutionContext): Promise { const request = context.switchToHttp().getRequest(); @@ -26,10 +30,12 @@ export class SettingsJwtGuard implements CanActivate { const payload = await this.jwtService.verifyAsync(token, { secret: `${process.env.JWT_SECRET}`, }); + await this.actorAuthService.assertActorActive(payload); (request as any).user = payload; (request as any).identity = payload; return true; - } catch { + } catch (error) { + if (error instanceof UnauthorizedException) throw error; throw new UnauthorizedException("Invalid token"); } } diff --git a/src/common/auth/guards/auth.guard.ts b/src/common/auth/guards/auth.guard.ts index 0ac78cd..a1f573b 100644 --- a/src/common/auth/guards/auth.guard.ts +++ b/src/common/auth/guards/auth.guard.ts @@ -7,10 +7,14 @@ import { import { JwtService } from "@nestjs/jwt"; import { Request } from "express"; import { JwtPayload } from "../types/payload.types"; +import { ActorAuthService } from "src/auth/auth-services/actor.auth.service"; @Injectable() export class AuthGuard implements CanActivate { - constructor(private readonly jwtService: JwtService) {} + constructor( + private readonly jwtService: JwtService, + private readonly actorAuthService: ActorAuthService, + ) {} async canActivate(context: ExecutionContext): Promise { const request = context.switchToHttp().getRequest(); @@ -19,12 +23,16 @@ export class AuthGuard implements CanActivate { throw new UnauthorizedException("No token provided"); } try { - const payload: JwtPayload = - await this.jwtService.verifyAsync(token, { + const payload: JwtPayload = await this.jwtService.verifyAsync( + token, + { secret: `${process.env.JWT_SECRET}`, - }); + }, + ); + await this.actorAuthService.assertActorActive(payload); request["user"] = payload; - } catch { + } catch (error) { + if (error instanceof UnauthorizedException) throw error; throw new UnauthorizedException("Invalid or expired token"); } return true; diff --git a/src/expert-insurer/expert-insurer.service.ts b/src/expert-insurer/expert-insurer.service.ts index c8c42d2..3eb9dfa 100644 --- a/src/expert-insurer/expert-insurer.service.ts +++ b/src/expert-insurer/expert-insurer.service.ts @@ -2016,26 +2016,11 @@ export class ExpertInsurerService { ); const email = payload.email.trim().toLowerCase(); - const existingByEmail = await this.expertDbService.findOne({ email }); - const existingDamageByEmail = await this.damageExpertDbService.findOne({ - email, - }); - if (existingByEmail || existingDamageByEmail) { - throw new ConflictException("An expert with this email already exists."); - } - const nationalCode = payload.nationalCode.trim(); - const existingByNational = await this.expertDbService.findOne({ - nationalCode, - }); - const existingDamageByNational = await this.damageExpertDbService.findOne({ - nationalCode, - }); - if (existingByNational || existingDamageByNational) { - throw new ConflictException( - "An expert with this national code already exists.", - ); - } + const repository = role === RoleEnum.EXPERT + ? this.expertDbService : this.damageExpertDbService; + if (await repository.findOne({ $or: [{ email }, { nationalCode }] })) + throw new ConflictException("این ایمیل یا کد ملی قبلاً برای همین نقش ثبت شده است."); const hashedPassword = await this.hashService.hash(payload.password); const locations = this.normalizeExpertLocations(payload.locations); diff --git a/src/management/management.controller.ts b/src/management/management.controller.ts index 593afdb..fcc20c4 100644 --- a/src/management/management.controller.ts +++ b/src/management/management.controller.ts @@ -23,6 +23,7 @@ import { CreateManagedClientDto, CreateManagedStaffDto, ManagedListQueryDto, + SetManagedStaffActiveDto, UpdateManagedAccountDto, UpdateManagedBranchDto, UpdateManagedClientDto, @@ -99,6 +100,14 @@ export class SuperAdminManagementController { @Get("branches") branches(@Query("clientId") client: string) { return this.management.listBranches(client); } + @Patch("staff/:role/:id/status") setStaffActive( + @Query("clientId") client: string, + @Param("role") role: string, + @Param("id") id: string, + @Body() body: SetManagedStaffActiveDto, + ) { + return this.management.setStaffActive(client, role, id, body.isActive); + } @Post("branches") createBranch( @Query("clientId") client: string, @Body() body: CreateBranchDto, diff --git a/src/management/management.dto.ts b/src/management/management.dto.ts index cb722a6..d19ebb9 100644 --- a/src/management/management.dto.ts +++ b/src/management/management.dto.ts @@ -9,6 +9,7 @@ import { Transform, Type } from "class-transformer"; import { ArrayMaxSize, IsArray, + IsBoolean, IsEmail, IsIn, IsInt, @@ -136,6 +137,11 @@ export class CreateManagedStaffDto { export class UpdateManagedStaffDto extends PartialType( OmitType(CreateManagedStaffDto, ["role"] as const), ) {} +export class SetManagedStaffActiveDto { + @ApiProperty({ description: "وضعیت دسترسی کارشناس به سامانه" }) + @IsBoolean({ message: "وضعیت فعالیت باید فعال یا غیرفعال باشد." }) + isActive: boolean; +} export class CreateManagedAccountDto extends PickType(CreateManagedStaffDto, [ "firstName", "lastName", diff --git a/src/management/management.service.spec.ts b/src/management/management.service.spec.ts index 89f7a10..8b257d5 100644 --- a/src/management/management.service.spec.ts +++ b/src/management/management.service.spec.ts @@ -6,7 +6,18 @@ import { } from "@nestjs/common"; import { model, Types } from "mongoose"; import { ManagementService } from "./management.service"; -import { InsurerManagementController } from "./management.controller"; +import { + InsurerManagementController, + SuperAdminManagementController, +} from "./management.controller"; +import { Test } from "@nestjs/testing"; +import { JwtModule, JwtService } from "@nestjs/jwt"; +import * as request from "supertest"; +import { ActorAuthService } from "src/auth/auth-services/actor.auth.service"; +import { ActorAuthController } from "src/auth/auth-controllers/actor/actor.auth.controller"; +import { LocalActorAuthGuard } from "src/auth/guards/actor-local.guard"; +import { CaptchaChallengeService } from "src/captcha/captcha-challenge.service"; +import { SuperAdminGuard } from "src/super-admin/guards/super-admin.guard"; import { STAFF_ROLES, CreateManagedStaffDto, @@ -14,6 +25,7 @@ import { CreateManagedAccountDto, CreateManagedClientDto, UpdateManagedBranchDto, + SetManagedStaffActiveDto, } from "./management.dto"; import { ClientDbSchema } from "src/client/entities/schema/client.schema"; import { BranchSchema } from "src/client/entities/schema/branch.schema"; @@ -146,7 +158,13 @@ describe("management accounts, optional Fanavaran fields and tenant boundaries", expect(stored.branchId).toBeUndefined(); }, ); - it.each(["field_expert", "file_maker", "file_reviewer", "call_center"])( + it.each([ + "damage_expert", + "field_expert", + "file_maker", + "file_reviewer", + "call_center", + ])( "supports seed-style %s identity without email or mobile", async (role) => { const body = staff(role); @@ -158,17 +176,14 @@ describe("management accounts, optional Fanavaran fields and tenant boundaries", expect(stored.username).toBe(body.nationalCode); }, ); - it.each(["expert", "damage_expert"])( - "requires email and mobile for %s", - async (role) => { - await expect( - service.createStaff(tenant, staff(role, { email: null })), - ).rejects.toBeInstanceOf(BadRequestException); - await expect( - service.createStaff(tenant, staff(role, { mobile: null })), - ).rejects.toBeInstanceOf(BadRequestException); - }, - ); + it.each(["expert"])("requires email and mobile for %s", async (role) => { + await expect( + service.createStaff(tenant, staff(role, { email: null })), + ).rejects.toBeInstanceOf(BadRequestException); + await expect( + service.createStaff(tenant, staff(role, { mobile: null })), + ).rejects.toBeInstanceOf(BadRequestException); + }); it.each([ ["file_maker", "ThirdPartyClaimExpertId", "CarBodyClaimExpertId"], ["file_reviewer", "ThirdPartyExpertiseClaim", "CarBodyExpertiseClaim"], @@ -339,10 +354,252 @@ describe("management accounts, optional Fanavaran fields and tenant boundaries", await expect( service.createStaff( foreign, - staff("file_reviewer", { email: "different@example.com" }), + staff("file_maker", { email: "different@example.com" }), ), ).rejects.toBeInstanceOf(ConflictException); }); + it("allows one person's email, national code and password across all six staff roles", async () => { + const rows = []; + for (const role of STAFF_ROLES) + rows.push(await service.createStaff(tenant, staff(role))); + expect(new Set(rows.map((row) => String(row._id))).size).toBe(6); + for (const repo of repos.slice(2, 8)) { + expect(repo.records[0]).toMatchObject({ + nationalCode: "0012345678", + email: "expert@example.com", + password: "hashed:secret123", + }); + } + // Same-role aliases must remain unique even for a different tenant. + for (const role of STAFF_ROLES) + await expect( + service.createStaff(foreign, staff(role)), + ).rejects.toBeInstanceOf(ConflictException); + }); + it("allows editing an alias to match another role without changing either assignment", async () => { + const first = await service.createStaff(tenant, staff("file_maker")); + const second = await service.createStaff( + tenant, + staff("file_reviewer", { + email: "reviewer@example.com", + nationalCode: "0098765432", + }), + ); + const edited = await service.updateStaff( + tenant, + "file_reviewer", + String(second._id), + { + nationalCode: first.nationalCode, + email: first.email, + }, + ); + expect(edited.email).toBe(first.email); + expect(edited.role).toBe("file_reviewer"); + expect(String(edited._id)).not.toBe(String(first._id)); + }); + it.each(STAFF_ROLES)( + "disables and reactivates only the selected %s assignment", + async (role) => { + const row = await service.createStaff(tenant, staff(role)); + const repo = repos[2 + STAFF_ROLES.indexOf(role)]; + delete repo.records[0].isActive; // Production records predate the flag. + expect((await service.listStaff(tenant, { role })).list[0].isActive).toBe( + true, + ); + const before = { ...repo.records[0] }; + const disabled = await service.setStaffActive( + tenant, + role, + String(row._id), + false, + ); + expect(disabled.isActive).toBe(false); + expect(disabled).not.toHaveProperty("password"); + expect(repo.records[0]).toMatchObject({ ...before, isActive: false }); + expect((await service.listStaff(tenant, { role })).list[0].isActive).toBe( + false, + ); + expect( + (await service.setStaffActive(tenant, role, String(row._id), true)) + .isActive, + ).toBe(true); + }, + ); + it("protects status changes against foreign tenants, unsupported roles and malformed values", async () => { + const row = await service.createStaff(tenant, staff("file_maker")); + await expect( + service.setStaffActive(foreign, "file_maker", String(row._id), false), + ).rejects.toBeInstanceOf(NotFoundException); + await expect( + service.setStaffActive(tenant, "super_admin", String(row._id), false), + ).rejects.toBeInstanceOf(BadRequestException); + await expect( + service.setStaffActive(tenant, "file_maker", String(row._id), null), + ).rejects.toBeInstanceOf(BadRequestException); + await expect( + service.updateStaff(tenant, "file_maker", String(row._id), { + isActive: false, + }), + ).rejects.toBeInstanceOf(BadRequestException); + expect(repos[5].records[0].isActive).toBe(true); + }); + it("enforces role-specific login, admin-only status, session revocation and reactivation over HTTP", async () => { + const actorAuth: any = Object.create(ActorAuthService.prototype); + const jwt = new JwtService(); + actorAuth.jwtService = jwt; + actorAuth.hashService = { + compare: async (plain, hashed) => hashed === `hashed:${plain}`, + }; + actorAuth.captchaChallengeService = { + verify: jest.fn().mockResolvedValue(undefined), + }; + for (const [index, name] of [ + "expertDbService", + "damageExpertDbService", + "fieldExpertDbService", + "fileMakerDbService", + "fileReviewerDbService", + "callCenterAgentDbService", + ].entries()) { + const repo = repos[index + 2]; + actorAuth[name] = { + findOne: async (filter) => repo.findOne(filter).lean(), + findByLoginIdentifier: async (identifier) => + repo + .findOne({ + $or: [ + { email: identifier }, + { nationalCode: identifier }, + { username: identifier }, + ], + }) + .lean(), + }; + } + actorAuth.clientDbService = { findOne: async () => repos[0].records[0] }; + const module = await Test.createTestingModule({ + imports: [JwtModule.register({})], + controllers: [ + SuperAdminManagementController, + InsurerManagementController, + ActorAuthController, + ], + providers: [ + SuperAdminGuard, + LocalActorAuthGuard, + { provide: ManagementService, useValue: service }, + { provide: ActorAuthService, useValue: actorAuth }, + { + provide: CaptchaChallengeService, + useValue: actorAuth.captchaChallengeService, + }, + ], + }).compile(); + const app = module.createNestApplication({ logger: false }); + const secretBefore = process.env.JWT_SECRET; + process.env.JWT_SECRET = "expert-access-http-test-only"; + try { + await app.init(); + const adminToken = jwt.sign( + { sub: String(new Types.ObjectId()), role: "super_admin" }, + { secret: process.env.JWT_SECRET }, + ); + const companyToken = jwt.sign( + { + sub: String(new Types.ObjectId()), + role: "company", + clientKey: tenant, + }, + { secret: process.env.JWT_SECRET }, + ); + const staffUrl = `/super-admin/management/staff?clientId=${tenant}`; + const maker = ( + await request(app.getHttpServer()) + .post(staffUrl) + .auth(adminToken, { type: "bearer" }) + .send(staff("file_maker")) + .expect(201) + ).body; + const reviewer = ( + await request(app.getHttpServer()) + .post(staffUrl) + .auth(adminToken, { type: "bearer" }) + .send(staff("file_reviewer")) + .expect(201) + ).body; + const login = ( + role: string, + identifier: Record = { nationalCode: "0012345678" }, + ) => + request(app.getHttpServer()) + .post("/actor/login") + .send({ + role, + ...identifier, + password: "secret123", + captchaId: "test", + captcha: "test", + }); + const makerToken = (await login("file_maker").expect(201)).body + .access_token; + const reviewerToken = ( + await login("file_reviewer", { email: "expert@example.com" }).expect( + 201, + ) + ).body.access_token; + expect(jwt.decode(makerToken).sub).toBe(maker._id); + expect(jwt.decode(reviewerToken).sub).toBe(reviewer._id); + const statusUrl = `/super-admin/management/staff/file_maker/${maker._id}/status?clientId=${tenant}`; + await request(app.getHttpServer()) + .patch(statusUrl) + .auth(companyToken, { type: "bearer" }) + .send({ isActive: false }) + .expect(401); + await request(app.getHttpServer()) + .patch(statusUrl) + .auth(makerToken, { type: "bearer" }) + .send({ isActive: false }) + .expect(401); + await request(app.getHttpServer()) + .patch(`/expert-insurer/management/staff/file_maker/${maker._id}`) + .auth(companyToken, { type: "bearer" }) + .send({ isActive: false }) + .expect(400); + await request(app.getHttpServer()) + .patch(statusUrl) + .auth(adminToken, { type: "bearer" }) + .send({ isActive: "false" }) + .expect(400); + const disabled = await request(app.getHttpServer()) + .patch(statusUrl) + .auth(adminToken, { type: "bearer" }) + .send({ isActive: false }) + .expect(200); + expect(disabled.body.isActive).toBe(false); + expect(disabled.body).not.toHaveProperty("password"); + await login("file_maker").expect(401); + await request(app.getHttpServer()) + .get("/actor/profile") + .auth(makerToken, { type: "bearer" }) + .expect(401); + await request(app.getHttpServer()) + .get("/actor/profile") + .auth(reviewerToken, { type: "bearer" }) + .expect(200); + await login("file_reviewer").expect(201); + await request(app.getHttpServer()) + .patch(statusUrl) + .auth(adminToken, { type: "bearer" }) + .send({ isActive: true }) + .expect(200); + await login("file_maker", { email: "expert@example.com" }).expect(201); + } finally { + await app.close(); + if (secretBefore === undefined) delete process.env.JWT_SECRET; + else process.env.JWT_SECRET = secretBefore; + } + }); it("keeps the password unchanged unless a replacement is supplied", async () => { const row = await service.createStaff(tenant, staff("field_expert")); await service.updateStaff(tenant, "field_expert", String(row._id), { @@ -541,6 +798,23 @@ describe("strict management DTO validation", () => { validate(UpdateManagedStaffDto, { role: "super_admin" }), ).rejects.toBeInstanceOf(BadRequestException); }); + it("accepts only a boolean on the dedicated status endpoint", async () => { + expect( + (await validate(SetManagedStaffActiveDto, { isActive: false })).isActive, + ).toBe(false); + for (const body of [ + {}, + { isActive: null }, + { isActive: "false" }, + { isActive: true, role: "super_admin" }, + ]) + await expect( + validate(SetManagedStaffActiveDto, body), + ).rejects.toBeInstanceOf(BadRequestException); + await expect( + validate(UpdateManagedStaffDto, { isActive: true }), + ).rejects.toBeInstanceOf(BadRequestException); + }); it("limits company-account fields and validates branch booleans and client codes", async () => { await expect( validate(CreateManagedAccountDto, { diff --git a/src/management/management.service.ts b/src/management/management.service.ts index 66e2111..1acd1b4 100644 --- a/src/management/management.service.ts +++ b/src/management/management.service.ts @@ -114,27 +114,24 @@ export class ManagementService { ); } private async uniqueLogin(role: string, values: any, ownId?: string) { - const national = values.nationalCode; - const email = values.email; - for (const otherRole of [...STAFF_ROLES, RoleEnum.COMPANY]) { - const filters: any[] = []; - if (email) filters.push({ email }, { username: email }); - // National-code login has no tenant selector: never introduce an ambiguous identifier. - if (national) filters.push({ nationalCode: national }); - if (!filters.length) continue; - const existing = await this.repository(otherRole) - .findOne({ - $or: filters, - ...(ownId && otherRole === role - ? { _id: { $ne: this.objectId(ownId) } } - : {}), - }) - .lean(); - if (existing) - throw new ConflictException( - "این ایمیل یا شناسه ورود قبلاً برای یک حساب ثبت شده است.", - ); - } + // The selected role already disambiguates cross-role identities. There is + // no tenant selector, so aliases must remain unique within each role. + const filters: any[] = []; + if (values.email) + filters.push({ email: values.email }, { username: values.email }); + if (values.nationalCode) + filters.push({ nationalCode: values.nationalCode }); + if (!filters.length) return; + const existing = await this.repository(role) + .findOne({ + $or: filters, + ...(ownId ? { _id: { $ne: this.objectId(ownId) } } : {}), + }) + .lean(); + if (existing) + throw new ConflictException( + "این ایمیل یا کد ملی قبلاً برای همین نقش ثبت شده است.", + ); } private async staffValues( role: string, @@ -253,16 +250,11 @@ export class ManagementService { "Password must contain at least six characters", ); if ( - [RoleEnum.EXPERT, RoleEnum.DAMAGE_EXPERT, RoleEnum.COMPANY].includes( - role as RoleEnum, - ) && + [RoleEnum.EXPERT, RoleEnum.COMPANY].includes(role as RoleEnum) && !merged.email ) throw new BadRequestException("Email is required for this role"); - if ( - [RoleEnum.EXPERT, RoleEnum.DAMAGE_EXPERT].includes(role as RoleEnum) && - !merged.mobile - ) + if (role === RoleEnum.EXPERT && !merged.mobile) throw new BadRequestException( "Mobile is required for blame and claim experts", ); @@ -363,7 +355,11 @@ export class ManagementService { const groups = await Promise.all( roles.map(async (role) => (await this.repository(role).find(this.scope(key)).lean()).map( - (row) => ({ ...this.pick(row, STAFF_FIELDS), role }), + (row) => ({ + ...this.pick(row, STAFF_FIELDS), + role, + ...(!account ? { isActive: row.isActive !== false } : {}), + }), ), ), ); @@ -500,6 +496,33 @@ export class ManagementService { throw error; } } + + /** Only exposed by the super-admin controller, never by insurer/self edits. */ + async setStaffActive( + clientId: string, + role: string, + id: string, + isActive: boolean, + ) { + if (!STAFF_ROLES.includes(role as StaffRole)) + throw new BadRequestException("نقش کارشناس معتبر نیست."); + if (typeof isActive !== "boolean") + throw new BadRequestException("وضعیت فعالیت باید فعال یا غیرفعال باشد."); + const key = await this.client(clientId); + const saved: any = await this.repository(role) + .findOneAndUpdate( + { _id: this.objectId(id), ...this.scope(key) }, + { $set: { isActive } }, + { new: true, runValidators: true }, + ) + .lean(); + if (!saved) + throw new NotFoundException("حساب کارشناس در این شرکت بیمه یافت نشد."); + return { + ...this.pick(saved, STAFF_FIELDS), + isActive: saved.isActive !== false, + }; + } async listBranches(clientId: string) { const key = await this.client(clientId); return { diff --git a/src/profile/profile.controller.spec.ts b/src/profile/profile.controller.spec.ts index 58046df..d4286a8 100644 --- a/src/profile/profile.controller.spec.ts +++ b/src/profile/profile.controller.spec.ts @@ -2,6 +2,7 @@ import { Test, TestingModule } from "@nestjs/testing"; import { ProfileController } from "./profile.controller"; import { ProfileService } from "./profile.service"; import { JwtService } from "@nestjs/jwt"; +import { ActorAuthService } from "src/auth/auth-services/actor.auth.service"; describe("ProfileController", () => { let controller: ProfileController; @@ -12,6 +13,7 @@ describe("ProfileController", () => { providers: [ { provide: ProfileService, useValue: {} }, { provide: JwtService, useValue: {} }, + { provide: ActorAuthService, useValue: Object.create(ActorAuthService.prototype) }, ], }).compile(); diff --git a/src/request-management/file-maker-blame-v4-workflow.spec.ts b/src/request-management/file-maker-blame-v4-workflow.spec.ts index 3e1285a..0a04dd2 100644 --- a/src/request-management/file-maker-blame-v4-workflow.spec.ts +++ b/src/request-management/file-maker-blame-v4-workflow.spec.ts @@ -10,6 +10,133 @@ import { ClaimCaseStatus } from "src/Types&Enums/claim-request-management/claim- import { ClaimWorkflowStep } from "src/Types&Enums/claim-request-management/claim-workflow-steps.enum"; describe("RequestManagementService V4 FileMaker workflow", () => { + it.each([ + [4, BlameRequestType.CAR_BODY], + [4, BlameRequestType.THIRD_PARTY], + [5, BlameRequestType.CAR_BODY], + [5, BlameRequestType.THIRD_PARTY], + ])( + "completes v%s %s narratives and signatures without voice", + async (flow, type) => { + const actor = { + sub: String(new Types.ObjectId()), + role: RoleEnum.FILE_MAKER, + }; + const request: any = { + _id: new Types.ObjectId(), + type, + expertInitiated: true, + isMadeByFileMaker: true, + requiresFileMakerApproval: flow === 5, + initiatedByFieldExpertId: new Types.ObjectId(actor.sub), + creationMethod: CreationMethod.IN_PERSON, + status: CaseStatus.OPEN, + parties: [ + PartyRole.FIRST, + ...(type === BlameRequestType.THIRD_PARTY ? [PartyRole.SECOND] : []), + ].map((role) => ({ + role, + person: { userId: new Types.ObjectId() }, + evidence: {}, + })), + workflow: { + currentStep: WorkflowStep.FIRST_INITIAL_FORM, + completedSteps: [], + }, + history: [], + save: jest.fn().mockResolvedValue(undefined), + }; + const service: any = new (RequestManagementService as any)(); + service.verifyExpertAccessForBlameV2 = jest + .fn() + .mockResolvedValue(undefined); + service.blameRequestDbService = { + findById: async () => request, + findByIdAndUpdate: async (_id, update) => { + for (const [key, value] of Object.entries(update.$set)) { + const [, index] = key.split("."); + request.parties[Number(index)].confirmation = value; + } + }, + }; + service.userSign = { + create: jest.fn(async () => ({ _id: new Types.ObjectId() })), + }; + service.blameVoiceDbService = { create: jest.fn() }; + for (const party of request.parties) { + service.markPartyInquiriesCompleteOnBlame(request, party.role, actor); + const prefix = party.role === PartyRole.FIRST ? "FIRST" : "SECOND"; + expect(request.workflow.currentStep).toBe(`${prefix}_DESCRIPTION`); + const description = { + desc: "شرح حادثه ".repeat(15), + accidentDate: "2025-01-01", + accidentTime: "10:30", + }; + if (flow === 4) + await service.addPartyDescriptionV4( + String(request._id), + actor, + description, + party.role, + ); + else + await service.addPartyDescriptionV3( + String(request._id), + actor, + description, + party.role, + ); + expect(request.workflow.currentStep).toBe(`${prefix}_SIGN`); + await service.expertUploadPartySignatureV3( + actor, + String(request._id), + party.role, + true, + { filename: "signature.png", path: "files/signature.png" }, + ); + expect(party.confirmation.accepted).toBe(true); + expect(request.workflow.completedSteps).not.toContain( + `${prefix}_VOICE`, + ); + } + expect(service.blameVoiceDbService.create).not.toHaveBeenCalled(); + expect(request.workflow.currentStep).toBe( + type === BlameRequestType.CAR_BODY + ? WorkflowStep.FIRST_COMPLETED + : WorkflowStep.SECOND_COMPLETED, + ); + }, + ); + + it.each([WorkflowStep.FIRST_VOICE, WorkflowStep.SECOND_VOICE])( + "repairs legacy %s resume values without erasing existing recordings or history", + (step) => { + const service: any = new (RequestManagementService as any)(); + const file = { + workflow: { + currentStep: step, + nextStep: step.replace("VOICE", "DESCRIPTION"), + completedSteps: [step], + }, + parties: [{ evidence: { voices: ["existing-recording"] } }], + history: [{ type: "V3_PARTY_VOICE_UPLOADED" }], + }; + const before = JSON.stringify(file); + expect(service.fileMakerWorkflowProjection(file).currentStep).toBe( + step.replace("VOICE", "DESCRIPTION"), + ); + expect(service.fileMakerWorkflowProjection(file).nextStep).toBe(step.replace("VOICE", "SIGN")); + expect(JSON.stringify(file)).toBe(before); + }, + ); + + it("keeps voice in the non-FileMaker in-person inquiry workflow", () => { + const service: any = new (RequestManagementService as any)(); + const request: any = { workflow: { completedSteps: [] }, parties: [] }; + service.markPartyInquiriesCompleteOnBlame(request, PartyRole.FIRST, {}); + expect(request.workflow.currentStep).toBe(WorkflowStep.FIRST_LOCATION); + expect(request.workflow.nextStep).toBe(WorkflowStep.FIRST_VOICE); + }); it("persists FIRST_INITIAL_FORM after the first party OTP is verified", async () => { const fileMakerId = new Types.ObjectId(); const userId = new Types.ObjectId(); @@ -87,7 +214,7 @@ describe("RequestManagementService V4 FileMaker workflow", () => { expect(request.workflow.currentStep).toBe(WorkflowStep.FIRST_INITIAL_FORM); expect(request.workflow.currentStep).not.toBe(WorkflowStep.FIRST_VIDEO); - expect(request.workflow.nextStep).toBe(WorkflowStep.FIRST_VOICE); + expect(request.workflow.nextStep).toBe(WorkflowStep.FIRST_DESCRIPTION); expect(request.workflow.completedSteps).not.toContain( WorkflowStep.FIRST_VIDEO, ); @@ -169,7 +296,7 @@ describe("RequestManagementService V4 FileMaker workflow", () => { ); expect(request.workflow.currentStep).toBe(WorkflowStep.FIRST_INITIAL_FORM); - expect(request.workflow.nextStep).toBe(WorkflowStep.FIRST_VOICE); + expect(request.workflow.nextStep).toBe(WorkflowStep.FIRST_DESCRIPTION); expect(request.workflow.completedSteps).not.toContain( WorkflowStep.FIRST_VIDEO, ); @@ -212,7 +339,7 @@ describe("RequestManagementService V4 FileMaker workflow", () => { expect(reopened.workflow).toEqual( expect.objectContaining({ currentStep: WorkflowStep.FIRST_INITIAL_FORM, - nextStep: WorkflowStep.FIRST_VOICE, + nextStep: WorkflowStep.FIRST_DESCRIPTION, }), ); expect(reopened.workflow.completedSteps).not.toContain( diff --git a/src/request-management/file-maker-blame-v4.controller.ts b/src/request-management/file-maker-blame-v4.controller.ts index 59d30e4..6e4dff8 100644 --- a/src/request-management/file-maker-blame-v4.controller.ts +++ b/src/request-management/file-maker-blame-v4.controller.ts @@ -31,7 +31,10 @@ import { RoleEnum } from "src/Types&Enums/role.enum"; import { CreationMethod } from "./entities/schema/request-management.schema"; import { CreateExpertInitiatedFileDto } from "./dto/expert-initiated.dto"; import { SendPartyOtpDto, VerifyPartyOtpDto } from "./dto/party-otp.dto"; -import { RunInquiriesV3Dto, RunInquiriesVinV3Dto } from "./dto/run-inquiries-v3.dto"; +import { + RunInquiriesV3Dto, + RunInquiriesVinV3Dto, +} from "./dto/run-inquiries-v3.dto"; import { CarBodyFormDto, DescriptionV4Dto, @@ -57,11 +60,11 @@ import { ListQueryV2Dto } from "src/common/dto/list-query-v2.dto"; * THIRD_PARTY sequence: * create → send-party-otp (guilty) → verify-party-otp (guilty) * → [car-body-form if CAR_BODY] → run-inquiries (guilty + auto claim) - * → add-detail-location / add-detail-description / upload-voice (guilty) + * → add-detail-description (voice optional) (guilty) * → sign (guilty) * → send-party-otp (damaged) → verify-party-otp (damaged) * → run-inquiries (damaged) - * → add-detail-location / add-detail-description / upload-voice (damaged) + * → add-detail-description (voice optional) (damaged) * → sign (damaged) ← FileMaker job done here * * CAR_BODY sequence: same but single party — omit second-party steps. @@ -91,14 +94,19 @@ export class FileMakerBlameV4Controller { fileMaker, // requiresFileMakerApproval is V5-only; explicitly exclude it from V4 so // a client that accidentally sends the field cannot poison the blame record. - { ...dto, creationMethod: CreationMethod.IN_PERSON, requiresFileMakerApproval: false }, + { + ...dto, + creationMethod: CreationMethod.IN_PERSON, + requiresFileMakerApproval: false, + }, ); } @Get("my-files") @ApiOperation({ summary: "List all blame files created by this FileMaker", - description: "Returns V4 FileMaker blame files using the shared search, sort, filter, and pagination query contract.", + description: + "Returns V4 FileMaker blame files using the shared search, sort, filter, and pagination query contract.", }) async getMyFiles( @CurrentUser() fileMaker: any, @@ -111,13 +119,17 @@ export class FileMakerBlameV4Controller { @ApiParam({ name: "requestId", description: "Blame request ID" }) @ApiOperation({ summary: "Get a single blame file created by this FileMaker", - description: "Returns full detail — parties, workflow, linked claim ID — for one V4 FileMaker blame file.", + description: + "Returns full detail — parties, workflow, linked claim ID — for one V4 FileMaker blame file.", }) async getMyFileDetail( @Param("requestId") requestId: string, @CurrentUser() fileMaker: any, ) { - return this.requestManagementService.getMyFileMakerFileDetail(fileMaker, requestId); + return this.requestManagementService.getMyFileMakerFileDetail( + fileMaker, + requestId, + ); } @Get("claim-id/:requestId") @@ -312,7 +324,7 @@ export class FileMakerBlameV4Controller { ) @Post("upload-voice/:requestId") @ApiParam({ name: "requestId" }) - @ApiOperation({ summary: "Upload voice for current party" }) + @ApiOperation({ summary: "Upload optional voice for current party" }) async uploadVoice( @Param("requestId") requestId: string, @CurrentUser() fileMaker: any, diff --git a/src/request-management/file-maker-blame-v5.controller.ts b/src/request-management/file-maker-blame-v5.controller.ts index d2c0dbf..b059ab1 100644 --- a/src/request-management/file-maker-blame-v5.controller.ts +++ b/src/request-management/file-maker-blame-v5.controller.ts @@ -31,7 +31,10 @@ import { RoleEnum } from "src/Types&Enums/role.enum"; import { CreationMethod } from "./entities/schema/request-management.schema"; import { CreateExpertInitiatedFileDto } from "./dto/expert-initiated.dto"; import { SendPartyOtpDto, VerifyPartyOtpDto } from "./dto/party-otp.dto"; -import { RunInquiriesV3Dto, RunInquiriesVinV3Dto } from "./dto/run-inquiries-v3.dto"; +import { + RunInquiriesV3Dto, + RunInquiriesVinV3Dto, +} from "./dto/run-inquiries-v3.dto"; import { CarBodyFormDto, DescriptionDto, @@ -60,11 +63,11 @@ import { ListQueryV2Dto } from "src/common/dto/list-query-v2.dto"; * THIRD_PARTY sequence: * create → send-party-otp (guilty) → verify-party-otp (guilty) * → [car-body-form if CAR_BODY] → run-inquiries (guilty + auto claim) - * → add-detail-location / add-detail-description / upload-voice (guilty) + * → add-detail-description (voice optional) (guilty) * → sign (guilty) * → send-party-otp (damaged) → verify-party-otp (damaged) * → run-inquiries (damaged) - * → add-detail-location / add-detail-description / upload-voice (damaged) + * → add-detail-description (voice optional) (damaged) * → sign (damaged) ← FileMaker job done here */ @ApiTags("v5 FileMaker — blame file creation (with FinancialExpert approval)") @@ -90,14 +93,19 @@ export class FileMakerBlameV5Controller { ) { return this.requestManagementService.createExpertInitiatedBlameV2( fileMaker, - { ...dto, creationMethod: CreationMethod.IN_PERSON, requiresFileMakerApproval: true }, + { + ...dto, + creationMethod: CreationMethod.IN_PERSON, + requiresFileMakerApproval: true, + }, ); } @Get("my-files") @ApiOperation({ summary: "List all blame files created by this FileMaker", - description: "Returns V5 FileMaker blame files using the shared search, sort, filter, and pagination query contract.", + description: + "Returns V5 FileMaker blame files using the shared search, sort, filter, and pagination query contract.", }) async getMyFiles( @CurrentUser() fileMaker: any, @@ -110,13 +118,17 @@ export class FileMakerBlameV5Controller { @ApiParam({ name: "requestId", description: "Blame request ID" }) @ApiOperation({ summary: "Get a single blame file created by this FileMaker", - description: "Returns full detail — parties, workflow, linked claim ID — for one V5 FileMaker blame file.", + description: + "Returns full detail — parties, workflow, linked claim ID — for one V5 FileMaker blame file.", }) async getMyFileDetail( @Param("requestId") requestId: string, @CurrentUser() fileMaker: any, ) { - return this.requestManagementService.getMyFileMakerFileDetail(fileMaker, requestId); + return this.requestManagementService.getMyFileMakerFileDetail( + fileMaker, + requestId, + ); } @Get("claim-id/:requestId") @@ -306,7 +318,7 @@ export class FileMakerBlameV5Controller { ) @Post("upload-voice/:requestId") @ApiParam({ name: "requestId" }) - @ApiOperation({ summary: "Upload voice for current party" }) + @ApiOperation({ summary: "Upload optional voice for current party" }) async uploadVoice( @Param("requestId") requestId: string, @CurrentUser() fileMaker: any, diff --git a/src/request-management/request-management.service.ts b/src/request-management/request-management.service.ts index 1073543..81edb90 100644 --- a/src/request-management/request-management.service.ts +++ b/src/request-management/request-management.service.ts @@ -4261,7 +4261,7 @@ export class RequestManagementService { if (isFileMakerFlow) { advancedTo = WorkflowStep.FIRST_INITIAL_FORM; req.workflow.currentStep = advancedTo; - req.workflow.nextStep = WorkflowStep.FIRST_VOICE; + req.workflow.nextStep = WorkflowStep.FIRST_DESCRIPTION; } else { const step3 = await this.getWorkflowStep({ stepNumber: 3 }); // FIRST_VIDEO advancedTo = step3.stepKey as WorkflowStep; @@ -7089,10 +7089,10 @@ export class RequestManagementService { : [WorkflowStep.CREATED, WorkflowStep.FIRST_INITIAL_FORM]; this.pushWorkflowSteps(req, completedSteps); req.workflow.currentStep = skipLocation - ? WorkflowStep.FIRST_VOICE + ? WorkflowStep.FIRST_DESCRIPTION : WorkflowStep.FIRST_LOCATION; req.workflow.nextStep = skipLocation - ? WorkflowStep.FIRST_DESCRIPTION + ? WorkflowStep.FIRST_SIGN : WorkflowStep.FIRST_VOICE; const firstIdx = this.getPartyIndex(req, PartyRole.FIRST); @@ -7113,14 +7113,28 @@ export class RequestManagementService { : [WorkflowStep.SECOND_INITIAL_FORM]; this.pushWorkflowSteps(req, completedSteps); req.workflow.currentStep = skipLocation - ? WorkflowStep.SECOND_VOICE + ? WorkflowStep.SECOND_DESCRIPTION : WorkflowStep.SECOND_LOCATION; req.workflow.nextStep = skipLocation - ? WorkflowStep.SECOND_DESCRIPTION + ? WorkflowStep.SECOND_SIGN : WorkflowStep.SECOND_VOICE; } } + private completeFileMakerPartyDescription(req: any, role: PartyRole): void { + if (!req.isMadeByFileMaker) return; + const firstParty = role === PartyRole.FIRST; + this.pushWorkflowSteps(req, [ + firstParty ? WorkflowStep.FIRST_DESCRIPTION : WorkflowStep.SECOND_DESCRIPTION, + ]); + req.workflow.currentStep = firstParty + ? WorkflowStep.FIRST_SIGN + : WorkflowStep.SECOND_SIGN; + req.workflow.nextStep = firstParty + ? WorkflowStep.FIRST_COMPLETED + : WorkflowStep.SECOND_COMPLETED; + } + private async createV3ClaimFromBlame( req: any, actor: any, @@ -8109,7 +8123,7 @@ export class RequestManagementService { if (partyRole === PartyRole.FIRST) { this.pushWorkflowSteps(fresh, [ WorkflowStep.FIRST_LOCATION, - WorkflowStep.FIRST_VOICE, + ...(isFileMakerActor ? [] : [WorkflowStep.FIRST_VOICE]), WorkflowStep.FIRST_DESCRIPTION, WorkflowStep.FIRST_SIGN, WorkflowStep.FIRST_COMPLETED, @@ -8127,7 +8141,7 @@ export class RequestManagementService { } else { this.pushWorkflowSteps(fresh, [ WorkflowStep.SECOND_LOCATION, - WorkflowStep.SECOND_VOICE, + ...(isFileMakerActor ? [] : [WorkflowStep.SECOND_VOICE]), WorkflowStep.SECOND_DESCRIPTION, WorkflowStep.SECOND_SIGN, WorkflowStep.SECOND_COMPLETED, @@ -8559,6 +8573,8 @@ export class RequestManagementService { metadata: { partyRole: role }, } as any); + this.completeFileMakerPartyDescription(req, role); + await (req as any).save(); return { requestId: req._id, publicId: req.publicId, partyRole: role }; } @@ -8630,6 +8646,8 @@ export class RequestManagementService { }, } as any); + this.completeFileMakerPartyDescription(req, role); + await (req as any).save(); return { requestId: req._id, publicId: req.publicId, partyRole: role }; } @@ -8670,7 +8688,7 @@ export class RequestManagementService { this.pushWorkflowSteps(req, [WorkflowStep.CAR_BODY_ACCIDENT_TYPE]); if ((req as any).isMadeByFileMaker) { req.workflow.currentStep = WorkflowStep.FIRST_INITIAL_FORM; - req.workflow.nextStep = WorkflowStep.FIRST_VOICE; + req.workflow.nextStep = WorkflowStep.FIRST_DESCRIPTION; } else { req.workflow.currentStep = WorkflowStep.CAR_BODY_ACCIDENT_TYPE; req.workflow.nextStep = WorkflowStep.FIRST_INITIAL_FORM; @@ -9678,7 +9696,7 @@ export class RequestManagementService { return { ...workflow, currentStep: WorkflowStep.FIRST_INITIAL_FORM, - nextStep: WorkflowStep.FIRST_VOICE, + nextStep: WorkflowStep.FIRST_DESCRIPTION, completedSteps, }; } @@ -9695,7 +9713,18 @@ export class RequestManagementService { }; } - return { ...workflow, completedSteps }; + const withoutVoice = (step: WorkflowStep) => { + if (step === WorkflowStep.FIRST_VOICE) return WorkflowStep.FIRST_DESCRIPTION; + if (step === WorkflowStep.SECOND_VOICE) return WorkflowStep.SECOND_DESCRIPTION; + return step; + }; + const currentStep = withoutVoice(workflow.currentStep); + let nextStep = withoutVoice(workflow.nextStep); + if (currentStep === WorkflowStep.FIRST_DESCRIPTION && nextStep === currentStep) + nextStep = WorkflowStep.FIRST_SIGN; + if (currentStep === WorkflowStep.SECOND_DESCRIPTION && nextStep === currentStep) + nextStep = WorkflowStep.SECOND_SIGN; + return { ...workflow, currentStep, nextStep, completedSteps }; } /** diff --git a/src/users/entities/db-service/call-center-agent.db.service.ts b/src/users/entities/db-service/call-center-agent.db.service.ts index 6f8d856..28eb439 100644 --- a/src/users/entities/db-service/call-center-agent.db.service.ts +++ b/src/users/entities/db-service/call-center-agent.db.service.ts @@ -29,7 +29,9 @@ export class CallCenterAgentDbService { async findByLoginIdentifier( identifier: string, ): Promise { - const id = identifier.trim(); + const id = identifier.includes("@") + ? identifier.trim().toLowerCase() + : identifier.trim(); const or: FilterQuery[] = [ { email: id }, { username: id }, diff --git a/src/users/entities/db-service/field-expert.db.service.ts b/src/users/entities/db-service/field-expert.db.service.ts index f6fe200..237ff3a 100644 --- a/src/users/entities/db-service/field-expert.db.service.ts +++ b/src/users/entities/db-service/field-expert.db.service.ts @@ -25,7 +25,9 @@ export class FieldExpertDbService { async findByLoginIdentifier( identifier: string, ): Promise { - const id = identifier.trim(); + const id = identifier.includes("@") + ? identifier.trim().toLowerCase() + : identifier.trim(); const or: FilterQuery[] = [ { email: id }, { username: id }, diff --git a/src/users/entities/db-service/file-maker.db.service.ts b/src/users/entities/db-service/file-maker.db.service.ts index 39c1dc6..fb20291 100644 --- a/src/users/entities/db-service/file-maker.db.service.ts +++ b/src/users/entities/db-service/file-maker.db.service.ts @@ -25,7 +25,9 @@ export class FileMakerDbService { async findByLoginIdentifier( identifier: string, ): Promise { - const id = identifier.trim(); + const id = identifier.includes("@") + ? identifier.trim().toLowerCase() + : identifier.trim(); const or: FilterQuery[] = [{ email: id }, { username: id }]; if (/^\d{10}$/.test(id)) { or.push({ nationalCode: id }); diff --git a/src/users/entities/db-service/file-reviewer.db.service.ts b/src/users/entities/db-service/file-reviewer.db.service.ts index b51debc..5cd1f59 100644 --- a/src/users/entities/db-service/file-reviewer.db.service.ts +++ b/src/users/entities/db-service/file-reviewer.db.service.ts @@ -25,7 +25,9 @@ export class FileReviewerDbService { async findByLoginIdentifier( identifier: string, ): Promise { - const id = identifier.trim(); + const id = identifier.includes("@") + ? identifier.trim().toLowerCase() + : identifier.trim(); const or: FilterQuery[] = [ { email: id }, { username: id }, diff --git a/src/users/entities/schema/call-center-agent.schema.ts b/src/users/entities/schema/call-center-agent.schema.ts index 7b234f1..cb43ba6 100644 --- a/src/users/entities/schema/call-center-agent.schema.ts +++ b/src/users/entities/schema/call-center-agent.schema.ts @@ -14,6 +14,9 @@ import { RoleEnum } from "src/Types&Enums/role.enum"; export class CallCenterAgentModel { _id?: Types.ObjectId; + @Prop({ type: Boolean, default: true }) + isActive?: boolean; + @Prop({ required: true }) firstName: string; diff --git a/src/users/entities/schema/damage-expert.schema.ts b/src/users/entities/schema/damage-expert.schema.ts index 8b27bf9..99cebe8 100644 --- a/src/users/entities/schema/damage-expert.schema.ts +++ b/src/users/entities/schema/damage-expert.schema.ts @@ -8,7 +8,6 @@ import { import { RoleEnum } from "src/Types&Enums/role.enum"; import { UserType } from "src/Types&Enums/userType.enum"; - @Schema({ _id: false, versionKey: false }) export class DamageExpertLocationModel { @Prop({ type: String, required: true }) @@ -100,6 +99,9 @@ const FinancialInfoSchema = SchemaFactory.createForClass(FinancialInfo); @Schema({ collection: "damage-expert", versionKey: false, timestamps: true }) export class DamageExpertModel { + @Prop({ type: Boolean, default: true }) + isActive?: boolean; + @Prop({ required: true }) userType: UserType; @@ -115,8 +117,8 @@ export class DamageExpertModel { @Prop({ unique: true }) nationalCode: string; - @Prop({ type: "string", unique: true }) - email: string; + @Prop({ type: String, unique: true, sparse: true }) + email?: string; @Prop({ type: "string" }) username: string; @@ -124,8 +126,8 @@ export class DamageExpertModel { @Prop({ required: true }) password: string; - @Prop({ required: true }) - mobile: string; + @Prop({ required: false }) + mobile?: string; @Prop({ required: false }) phone?: string; @@ -175,7 +177,7 @@ export class DamageExpertModel { @Prop({ type: "string" }) city: string; - @Prop({type: "string", required: false}) + @Prop({ type: "string", required: false }) expertCode?: string; @Prop({ type: String, required: false }) @@ -198,7 +200,7 @@ export const DamageExpertDbSchema = DamageExpertDbSchema.pre("save", function (next) { if (!this.username) { - this.username = this.email; + this.username = this.email || this.nationalCode; } next(); -}); \ No newline at end of file +}); diff --git a/src/users/entities/schema/expert.schema.ts b/src/users/entities/schema/expert.schema.ts index 1b69934..e90b5ff 100644 --- a/src/users/entities/schema/expert.schema.ts +++ b/src/users/entities/schema/expert.schema.ts @@ -18,6 +18,9 @@ export const ExpertLocationDbSchema = @Schema({ collection: "expert", versionKey: false, timestamps: true }) export class ExpertModel { + @Prop({ type: Boolean, default: true }) + isActive?: boolean; + @Prop({}) firstName: string; @@ -87,7 +90,7 @@ export class ExpertModel { @Prop({ type: "string" }) otp: string; - @Prop({type: "string", required: false}) + @Prop({ type: "string", required: false }) expertCode?: string; @Prop({ type: String, required: false }) diff --git a/src/users/entities/schema/field-expert.schema.ts b/src/users/entities/schema/field-expert.schema.ts index a3f7a2d..5876c0d 100644 --- a/src/users/entities/schema/field-expert.schema.ts +++ b/src/users/entities/schema/field-expert.schema.ts @@ -23,6 +23,9 @@ export const FieldExpertLocationDbSchema = SchemaFactory.createForClass( export class FieldExpertModel { _id?: Types.ObjectId; + @Prop({ type: Boolean, default: true }) + isActive?: boolean; + @Prop({ required: true }) firstName: string; @@ -71,7 +74,7 @@ export class FieldExpertModel { @Prop({ type: "string", default: "" }) otp: string; - @Prop({type: "string", required: false}) + @Prop({ type: "string", required: false }) expertCode?: string; @Prop({ type: String, required: false }) diff --git a/src/users/entities/schema/file-maker.schema.ts b/src/users/entities/schema/file-maker.schema.ts index bead9cc..8cf2dff 100644 --- a/src/users/entities/schema/file-maker.schema.ts +++ b/src/users/entities/schema/file-maker.schema.ts @@ -23,6 +23,9 @@ export const FileMakerLocationDbSchema = SchemaFactory.createForClass( export class FileMakerModel { _id?: Types.ObjectId; + @Prop({ type: Boolean, default: true }) + isActive?: boolean; + @Prop({ required: true }) firstName: string; diff --git a/src/users/entities/schema/file-reviewer.schema.ts b/src/users/entities/schema/file-reviewer.schema.ts index 2bf6a44..75dcffd 100644 --- a/src/users/entities/schema/file-reviewer.schema.ts +++ b/src/users/entities/schema/file-reviewer.schema.ts @@ -23,6 +23,9 @@ export const FileReviewerLocationDbSchema = SchemaFactory.createForClass( export class FileReviewerModel { _id?: Types.ObjectId; + @Prop({ type: Boolean, default: true }) + isActive?: boolean; + @Prop({ required: true }) firstName: string; diff --git a/test/claim-branch-flows.e2e-spec.ts b/test/claim-branch-flows.e2e-spec.ts index 0cfc463..d7f2111 100644 --- a/test/claim-branch-flows.e2e-spec.ts +++ b/test/claim-branch-flows.e2e-spec.ts @@ -8,6 +8,7 @@ import * as request from "supertest"; import { unlink } from "node:fs/promises"; import { Types } from "mongoose"; import { GlobalGuard } from "src/auth/guards/global.guard"; +import { ActorAuthService } from "src/auth/auth-services/actor.auth.service"; import { RolesGuard } from "src/auth/guards/role.guard"; import { PersianErrorFilter } from "src/common/errors/persian-error.filter"; import { MediaPolicyService } from "src/media-policy/media-policy.service"; @@ -174,6 +175,12 @@ describe("v1/v6 branch routing through HTTP", () => { ], providers: [ GlobalGuard, + { + provide: ActorAuthService, + useValue: Object.assign(Object.create(ActorAuthService.prototype), { + fieldExpertDbService: { findOne: async () => ({ isActive: true }) }, + }), + }, RolesGuard, { provide: RequestManagementService, useValue: userService }, { provide: ClaimRequestManagementService, useValue: claimService }, diff --git a/test/contracts/api-routes.json b/test/contracts/api-routes.json index 72df88c..18865c3 100644 --- a/test/contracts/api-routes.json +++ b/test/contracts/api-routes.json @@ -2081,6 +2081,15 @@ ], "roles": [] }, + { + "controller": "SuperAdminManagementController", + "method": "PATCH", + "path": "/super-admin/management/staff/:role/:id/status", + "guards": [ + "SuperAdminGuard" + ], + "roles": [] + }, { "controller": "SuperAdminController", "method": "PATCH",