fanavaran locations getting from branches

This commit is contained in:
2026-11-11 15:29:37 +03:30
parent d469cce463
commit 54459877a2
7 changed files with 163 additions and 22 deletions
+5 -2
View File
@@ -23,14 +23,17 @@ Secrets are **not** printed here — read from Mongo `fanavaranClientConfigs` or
| `password` | *(config)* | Login | Password | ✅ |
| `corpId` | `543` | All business calls | Corp scope | ✅ |
| `contractId` | `28` | All business calls | Contract | ✅ |
| `location` | `210050` | General calls without claim context | Tenant default OpBUId | ✅ (claim submissions require staff `locations[].id`) |
| `location` | `210050` | General calls without claim context | Tenant default OpBUId | ✅ (claim submissions require a staff location or branch code) |
Seed: `SEED_FANAVARAN_CLIENT_PROFILES` · Runtime: `getFanavaranClientProfile(key)`.
Claim submissions resolve `Location` from staff profiles in the `file-maker`,
`file-reviewer`, `expert`, `damage-expert`, and `field-expert` collections. Each
profile stores `locations: [{ id, name }]`; the first non-empty `id` is its primary
Fanavaran OpBUId. `branchId` is a local branch reference, not the HTTP Location.
Fanavaran OpBUId. When staff locations are missing, null, or empty, resolve that
staff member's `branchId` in the `branches` collection and use the branch's `code`
as the OpBUId. This branch fallback is checked before moving to another staff
candidate. The branch document's `_id` is never sent as the HTTP Location.
Resolution priority: claim initiator → blame initiator → active damage reply actor
→ assigned damage reviewer → assigned FileReviewer → assigned blame expert → blame
+1 -1
View File
@@ -53,7 +53,7 @@ Common optional properties are `branchId`, `phone`, `mobile`, `email`, `city`, `
All four codes are optional, editable and clearable for blame, claim and field experts. FileMaker accounts accept only the first two, FileReviewer accounts accept only the last two, and call-center accounts reject all four through the API. The panel presents these four named fields rather than the legacy generic `expertCode` input; existing `expertCode` values are preserved.
`locations` is an editable array of `{id, name}`. Both properties must be nonempty, and IDs must be unique within the array. These are Fanavaran OpBUId / HTTP `Location` values, rather than branch codes. On every Fanavaran business call for a claim, the integration prefers the assigned staff member's primary `locations[].id` (file-maker, file-reviewer, field, blame, or damage expert) for all tenants; the tenant auth `location` is only a fallback. Shared locations still participate in Parsian FileMaker/FileReviewer matching; management does not alter that matching logic.
`locations` is an editable array of `{id, name}`. Both properties must be nonempty, and IDs must be unique within the array. These are Fanavaran OpBUId / HTTP `Location` values. Claim submissions prefer the responsible staff member's primary `locations[].id` (file-maker, file-reviewer, field, blame, or damage expert) for all tenants. When that array is missing, null, or empty, the integration loads the staff member's branch using `branchId` and uses `branches.code`. It checks this branch fallback before moving to another staff candidate. If no candidate supplies a staff location or branch code, submission reports `FANAVARAN_STAFF_LOCATION_MISSING` instead of sending the tenant default. Shared staff locations still participate in Parsian FileMaker/FileReviewer matching; management does not alter that matching logic.
Branches require `code`, `name`, `city`, `state`, and `address`. `fullName`, `phoneNumber`, `isActive` (default true) and `activityStartDate` are optional and editable. Branch codes remain unique within an insurer. Insurer login accounts support name, email, password and optional contact/address fields; their role and tenant are assigned by the server.
@@ -46,6 +46,7 @@ function createHarness(blame: object, claim: object, role: number) {
findOneAndUpdate: () => ({ exec: async () => null }),
};
const management = Object.create(ClaimRequestManagementService.prototype);
const branches = { findById: jest.fn().mockResolvedValue(null) };
Object.assign(management, {
logger: new Logger("LocationHeaderTest"),
httpService: http,
@@ -61,6 +62,7 @@ function createHarness(blame: object, claim: object, role: number) {
},
fanavaranLocationService: new FanavaranLocationService(
...(staff as [any, any, any, any, any]),
branches as any,
),
fanavaranAuthService: new FanavaranAuthService(
http as any,
@@ -68,10 +70,41 @@ function createHarness(blame: object, claim: object, role: number) {
tokenModel as any,
),
});
return { management, http, audit, staff };
return { management, http, audit, staff, branches };
}
describe("Fanavaran outgoing Location headers", () => {
it.each([{ locations: null }, { locations: [] }, { locations: undefined }])(
"uses the creator's branch code when staff locations are %j",
async ({ locations }) => {
const { management, http, staff, branches } = createHarness(
{ expert: { assignedExpertId: "blame-expert" } },
{ initiatedByFieldExpertId: "damage-creator" },
-1,
);
staff[3].findById.mockImplementation(async (id: string) =>
id === "damage-creator" ? { locations, branchId: "branch-1" } : null,
);
staff[2].findById.mockImplementation(async (id: string) =>
id === "blame-expert"
? { locations: [{ id: "210050", name: "Other" }] }
: null,
);
branches.findById.mockResolvedValue({ code: "110011" });
await management.postFanavaranJson(
"https://example.test/claims",
{},
"parsian",
undefined,
"claim-1",
);
expect(http.post.mock.calls.at(-1)?.[2].headers).toMatchObject({
Location: "110011",
});
expect(branches.findById).toHaveBeenCalledWith("branch-1");
},
);
it("uses the damage expert handling a user-created claim before the previous blame expert", async () => {
const { management, http, staff } = createHarness(
{ expert: { assignedExpertId: "blame-expert" } },
@@ -90,7 +123,9 @@ describe("Fanavaran outgoing Location headers", () => {
);
management.assertFanavaranVehicleReviewApproved = jest.fn();
management.previewFanavaranSubmitV2 = jest.fn().mockResolvedValue({
PolicyId: 1, AccidentCauseId: 6, CulpritLicenceNo: "1234567890",
PolicyId: 1,
AccidentCauseId: 6,
CulpritLicenceNo: "1234567890",
});
await management.executeFanavaranV2Submit("claim-1", "parsian");
expect(http.post.mock.calls.at(-1)?.[2].headers).toMatchObject({
@@ -216,20 +251,43 @@ describe("Fanavaran outgoing Location headers", () => {
it("keeps concurrent claims' staff locations separate while sharing a login token", async () => {
const { management, http, staff } = createHarness({}, {}, -1);
management.claimCaseDbService.findById.mockImplementation(async (id: string) => ({
blameRequestId: "blame-1", initiatedByFieldExpertId: id,
}));
management.claimCaseDbService.findById.mockImplementation(
async (id: string) => ({
blameRequestId: "blame-1",
initiatedByFieldExpertId: id,
}),
);
staff[3].findById.mockImplementation(async (id: string) => ({
locations: [{ id: id === "claim-a" ? "110011" : "210050", name: "Branch" }],
locations: [
{ id: id === "claim-a" ? "110011" : "210050", name: "Branch" },
],
}));
await Promise.all(["claim-a", "claim-b"].map((id) => management.postFanavaranJson(
`https://example.test/${id}`, {}, "parsian", undefined, id,
)));
const calls = http.post.mock.calls.filter(([url]) => url.startsWith("https://example.test/"));
const headersByUrl = Object.fromEntries(calls.map(([url, , options]) => [url, options.headers]));
await Promise.all(
["claim-a", "claim-b"].map((id) =>
management.postFanavaranJson(
`https://example.test/${id}`,
{},
"parsian",
undefined,
id,
),
),
);
const calls = http.post.mock.calls.filter(([url]) =>
url.startsWith("https://example.test/"),
);
const headersByUrl = Object.fromEntries(
calls.map(([url, , options]) => [url, options.headers]),
);
expect(headersByUrl).toEqual({
"https://example.test/claim-a": expect.objectContaining({ Location: "110011", authenticationToken: "auth-test" }),
"https://example.test/claim-b": expect.objectContaining({ Location: "210050", authenticationToken: "auth-test" }),
"https://example.test/claim-a": expect.objectContaining({
Location: "110011",
authenticationToken: "auth-test",
}),
"https://example.test/claim-b": expect.objectContaining({
Location: "210050",
authenticationToken: "auth-test",
}),
});
expect(http.post).toHaveBeenCalledTimes(4);
});
@@ -124,7 +124,7 @@ export class CreateInsurerExpertDto {
@ApiPropertyOptional({
type: [ExpertLocationDto],
description:
'Fanavaran Location entries (id = OpBUId), stored on the staff profile. The first id is the primary location used as the HTTP Location header for claims created or handled by this expert. Claim submissions require a configured staff location.',
'Fanavaran Location entries (id = OpBUId), stored on the staff profile. The first id is used as the HTTP Location header. When empty, the code of the branch referenced by branchId is used. Claim submissions require a staff location or branch code.',
})
@IsOptional()
@IsArray()
@@ -14,6 +14,7 @@ describe("FanavaranLocationService", () => {
expert?: Record<string, unknown> | null;
damage?: Record<string, unknown> | null;
field?: Record<string, unknown> | null;
branch?: Record<string, unknown> | null;
}) =>
new FanavaranLocationService(
{
@@ -44,6 +45,7 @@ describe("FanavaranLocationService", () => {
return null;
}),
} as any,
{ findById: jest.fn().mockResolvedValue(opts?.branch ?? null) } as any,
);
describe("branch scope", () => {
@@ -92,6 +94,66 @@ describe("FanavaranLocationService", () => {
});
describe("resolveBusinessLocation", () => {
it.each(["maker", "reviewer", "expert", "damage", "field"])(
"uses the branch code for %s staff without their own locations",
async (role) => {
const service = createService({
[role]: { branchId: "branch-1", locations: null },
branch: { code: " 110011 " },
});
const staffId =
role === "maker"
? makerId
: role === "reviewer"
? reviewerId
: role === "field"
? fieldExpertId
: "expert-1";
await expect(
service.resolveBusinessLocation({
clientKey: "parsian",
staffCandidateIds: [staffId],
requireStaffLocation: true,
}),
).resolves.toBe("110011");
},
);
it("prefers staff locations over the branch code", async () => {
const service = createService({
field: { branchId: "branch-1", locations: [{ id: "110011" }] },
branch: { code: "210050" },
});
await expect(
service.resolveBusinessLocation({
clientKey: "parsian",
staffCandidateIds: [fieldExpertId],
requireStaffLocation: true,
}),
).resolves.toBe("110011");
});
it.each([null, { code: "" }, { code: " " }])(
"reports missing configuration when neither staff nor branch supplies a location: %j",
async (branch) => {
const service = createService({
field: { branchId: "branch-1", locations: null },
branch,
});
await expect(
service.resolveBusinessLocation({
clientKey: "parsian",
staffCandidateIds: [fieldExpertId],
requireStaffLocation: true,
}),
).rejects.toMatchObject({
response: expect.objectContaining({
code: "FANAVARAN_STAFF_LOCATION_MISSING",
}),
});
},
);
it("uses the first staff candidate location for any tenant", async () => {
const service = createService({
field: { locations: [{ id: "210050", name: "غرب" }] },
+16 -5
View File
@@ -4,6 +4,7 @@ import {
Injectable,
Logger,
} from "@nestjs/common";
import { BranchDbService } from "src/client/entities/db-service/branch.db.service";
import {
FanavaranClientKey,
getFanavaranClientProfile,
@@ -19,7 +20,7 @@ type LocationEntry = { id?: string; name?: string };
/**
* Resolve Fanavaran HTTP `Location` (OpBUId) from assigned staff
* `locations[].id` for every tenant, and enforce maker/reviewer match on
* `locations[].id` or their branch code for every tenant, and enforce maker/reviewer match on
* Parsian FileMaker flows.
*/
@Injectable()
@@ -32,6 +33,7 @@ export class FanavaranLocationService {
private readonly expertDbService: ExpertDbService,
private readonly damageExpertDbService: DamageExpertDbService,
private readonly fieldExpertDbService: FieldExpertDbService,
private readonly branchDbService: BranchDbService,
) {}
isParsianClient(clientKey?: FanavaranClientKey): boolean {
@@ -49,7 +51,8 @@ export class FanavaranLocationService {
}
/**
* First staff candidate with a stored `locations[].id` wins.
* First staff candidate with a stored `locations[].id` or branch code wins.
* A staff member's own locations take priority over their branch's code.
* Tenant auth.location is allowed only when requireStaffLocation is false.
*/
async resolveBusinessLocation(input: {
@@ -90,13 +93,13 @@ export class FanavaranLocationService {
throw new BadRequestException({
code: "FANAVARAN_STAFF_LOCATION_MISSING",
message:
"Cannot submit this claim to Fanavaran: no attached expert has a configured locations[].id (OpBUId). Configure the responsible staff member's location and retry.",
"Cannot submit this claim to Fanavaran: no attached expert has a configured locations[].id or branch code (OpBUId). Configure the responsible staff member's location or branch and retry.",
staffCandidateIds: [...seen],
});
}
this.logger.warn(
`[${input.clientKey}] Fanavaran Location fallback to tenant default=${defaultLocation}; no stored locations[].id found for staff candidates=${[...seen].join(",") || "none"}`,
`[${input.clientKey}] Fanavaran Location fallback to tenant default=${defaultLocation}; no staff location or branch code found for staff candidates=${[...seen].join(",") || "none"}`,
);
return defaultLocation;
}
@@ -197,7 +200,15 @@ export class FanavaranLocationService {
try {
const doc = await load();
if (doc) {
return this.extractLocationIds((doc as any)?.locations);
const locationIds = this.extractLocationIds(doc.locations);
if (locationIds.length > 0) return locationIds;
if (!doc.branchId) return [];
const branch = await this.branchDbService.findById(
String(doc.branchId),
);
const branchCode = String(branch?.code ?? "").trim();
return branchCode ? [branchCode] : [];
}
} catch {
// invalid ObjectId / cast errors — try next collection
+7
View File
@@ -2,6 +2,11 @@ import { Module } from "@nestjs/common";
import { HttpModule } from "@nestjs/axios";
import { ConfigModule, ConfigService } from "@nestjs/config";
import { MongooseModule } from "@nestjs/mongoose";
import { BranchDbService } from "src/client/entities/db-service/branch.db.service";
import {
BranchModel,
BranchSchema,
} from "src/client/entities/schema/branch.schema";
import { createHttpModuleOptions } from "src/core/config/http-proxy.factory";
import {
LookupModel,
@@ -36,11 +41,13 @@ import {
schema: FanavaranClientConfigSchema,
},
{ name: LookupModel.name, schema: LookupSchema },
{ name: BranchModel.name, schema: BranchSchema },
]),
FanavaranAuditModule,
UsersModule,
],
providers: [
BranchDbService,
FanavaranClientConfigService,
FanavaranAuthService,
FanavaranLookupService,