forked from Yara724/api
location dynamicallllllly finally or not ?
This commit is contained in:
@@ -3367,46 +3367,35 @@ export class ClaimRequestManagementService {
|
||||
/**
|
||||
* Fanavaran HTTP Location from assigned staff `locations[].id`
|
||||
* (file-maker / file-reviewer / field / blame / damage expert), for every
|
||||
* tenant. Falls back to tenant auth.location only when no staff location is set.
|
||||
* tenant. Prefer the claim creator, then the originating file's staff.
|
||||
* Missing staff configuration must not submit a claim to a default branch.
|
||||
*/
|
||||
private async resolveFanavaranLocationForClaim(
|
||||
claimCaseId: string,
|
||||
clientKey: FanavaranClientKey,
|
||||
): Promise<string> {
|
||||
const defaultLocation = getFanavaranClientProfile(clientKey).auth.location;
|
||||
|
||||
try {
|
||||
const claimCase = await this.claimCaseDbService.findById(claimCaseId);
|
||||
if (!claimCase?.blameRequestId) {
|
||||
return defaultLocation;
|
||||
}
|
||||
|
||||
const blame = await this.blameRequestDbService.findById(
|
||||
String(claimCase.blameRequestId),
|
||||
);
|
||||
if (!blame) {
|
||||
return defaultLocation;
|
||||
}
|
||||
|
||||
return this.fanavaranLocationService.resolveBusinessLocation({
|
||||
clientKey,
|
||||
staffCandidateIds: [
|
||||
(blame as any)?.initiatedByFieldExpertId,
|
||||
(blame as any)?.expert?.assignedExpertId,
|
||||
(blame as any)?.expert?.decision?.decidedByExpertId,
|
||||
(claimCase as any)?.initiatedByFieldExpertId,
|
||||
this.fanavaranDamageReplyActorId(claimCase),
|
||||
(claimCase as any)?.workflow?.assignedForReviewBy?.actorId,
|
||||
(blame as any)?.assignedFileReviewerId,
|
||||
],
|
||||
});
|
||||
} catch (error) {
|
||||
this.logger.warn(
|
||||
`[Fanavaran Location] Failed to resolve for claimCaseId=${claimCaseId}; using tenant default`,
|
||||
error,
|
||||
);
|
||||
return defaultLocation;
|
||||
const claimCase = await this.claimCaseDbService.findById(claimCaseId);
|
||||
if (!claimCase) {
|
||||
throw new NotFoundException('Claim case not found');
|
||||
}
|
||||
|
||||
const blame = claimCase.blameRequestId
|
||||
? await this.blameRequestDbService.findById(String(claimCase.blameRequestId))
|
||||
: null;
|
||||
|
||||
return this.fanavaranLocationService.resolveBusinessLocation({
|
||||
clientKey,
|
||||
requireStaffLocation: true,
|
||||
staffCandidateIds: [
|
||||
claimCase.initiatedByFieldExpertId,
|
||||
blame?.initiatedByFieldExpertId,
|
||||
this.fanavaranDamageReplyActorId(claimCase),
|
||||
claimCase.workflow?.assignedForReviewBy?.actorId,
|
||||
blame?.assignedFileReviewerId,
|
||||
blame?.expert?.assignedExpertId,
|
||||
blame?.expert?.decision?.decidedByExpertId,
|
||||
].map((id) => (id == null ? undefined : String(id))),
|
||||
});
|
||||
}
|
||||
|
||||
private fanavaranPayloadDefaultsWithoutExpertIds(
|
||||
@@ -3839,17 +3828,6 @@ export class ClaimRequestManagementService {
|
||||
InsuranceLineId: insuranceLineId,
|
||||
};
|
||||
|
||||
if (auditSession) {
|
||||
await this.fanavaranAuditService.recordStep({
|
||||
session: auditSession,
|
||||
step: FanavaranAuditStep.POLICY_INQUIRY,
|
||||
status: FanavaranAuditStatus.STARTED,
|
||||
requestUrl: policyInquiryUrl,
|
||||
requestMethod: 'GET',
|
||||
requestMeta,
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
this.fanavaranAuthService.assertNotInBackoff(clientKey);
|
||||
const headers = await this.getFanavaranAuthHeaders(
|
||||
@@ -3861,6 +3839,19 @@ export class ClaimRequestManagementService {
|
||||
...headers,
|
||||
'Content-Type': 'application/json',
|
||||
};
|
||||
requestMeta.location = headers.Location;
|
||||
|
||||
if (auditSession) {
|
||||
await this.fanavaranAuditService.recordStep({
|
||||
session: auditSession,
|
||||
step: FanavaranAuditStep.POLICY_INQUIRY,
|
||||
status: FanavaranAuditStatus.STARTED,
|
||||
requestUrl: policyInquiryUrl,
|
||||
requestMethod: 'GET',
|
||||
requestHeaders,
|
||||
requestMeta,
|
||||
});
|
||||
}
|
||||
|
||||
this.logger.log(
|
||||
`${logPrefix} Calling policy inquiry API for nationalCode: ${nationalCodeOfInsurer}`,
|
||||
@@ -4220,10 +4211,14 @@ export class ClaimRequestManagementService {
|
||||
});
|
||||
|
||||
try {
|
||||
const created = await this.fanavaranLookupService.createOtherPerson(
|
||||
input.clientKey,
|
||||
const response = await this.postFanavaranJson(
|
||||
url,
|
||||
payload,
|
||||
input.clientKey,
|
||||
auditSession,
|
||||
input.claimCaseId,
|
||||
);
|
||||
const created = response.data;
|
||||
const personId = pickFanavaranRecordId(created);
|
||||
await this.fanavaranAuditService.recordStep({
|
||||
session: auditSession,
|
||||
|
||||
@@ -0,0 +1,284 @@
|
||||
import { Logger } from "@nestjs/common";
|
||||
import { of } from "rxjs";
|
||||
import { getFanavaranClientProfile } from "src/core/config/fanavaran-client.config";
|
||||
import { FanavaranAuthService } from "src/fanavaran/fanavaran-auth.service";
|
||||
import { FanavaranLocationService } from "src/fanavaran/fanavaran-location.service";
|
||||
import { ClaimRequestManagementService } from "./claim-request-management.service";
|
||||
|
||||
function createHarness(blame: object, claim: object, role: number) {
|
||||
const staff = Array.from({ length: 5 }, (_, index) => ({
|
||||
findById: jest
|
||||
.fn()
|
||||
.mockResolvedValue(
|
||||
index === role
|
||||
? { locations: [{ id: "987654", name: "Test branch" }] }
|
||||
: null,
|
||||
),
|
||||
}));
|
||||
const http = {
|
||||
post: jest.fn((url: string, _body: unknown, _config: { headers: object }) =>
|
||||
of({
|
||||
status: 200,
|
||||
headers: url.includes("GetAppToken")
|
||||
? { apptoken: "app-test" }
|
||||
: { authenticationtoken: "auth-test" },
|
||||
data: {},
|
||||
}),
|
||||
),
|
||||
get: jest.fn().mockReturnValue(
|
||||
of({
|
||||
status: 200,
|
||||
headers: {},
|
||||
data: [{ PolicyId: 1, EndDate: "1499/01/01" }],
|
||||
}),
|
||||
),
|
||||
};
|
||||
const audit = {
|
||||
generateTrackingCode: () => "location-header-test",
|
||||
recordStep: jest.fn().mockResolvedValue(undefined),
|
||||
maskNationalCode: () => "masked",
|
||||
captureAxiosExchange: (_response: unknown, headers: unknown) => ({
|
||||
requestHeaders: headers,
|
||||
}),
|
||||
};
|
||||
const tokenModel = {
|
||||
findOne: () => ({ lean: () => ({ exec: async () => null }) }),
|
||||
findOneAndUpdate: () => ({ exec: async () => null }),
|
||||
};
|
||||
const management = Object.create(ClaimRequestManagementService.prototype);
|
||||
Object.assign(management, {
|
||||
logger: new Logger("LocationHeaderTest"),
|
||||
httpService: http,
|
||||
fanavaranAuditService: audit,
|
||||
claimCaseDbService: {
|
||||
findById: jest
|
||||
.fn()
|
||||
.mockResolvedValue({ blameRequestId: "blame-1", ...claim }),
|
||||
findByIdAndUpdate: jest.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
blameRequestDbService: {
|
||||
findById: jest.fn().mockResolvedValue({ type: "THIRD_PARTY", ...blame }),
|
||||
},
|
||||
fanavaranLocationService: new FanavaranLocationService(
|
||||
...(staff as [any, any, any, any, any]),
|
||||
),
|
||||
fanavaranAuthService: new FanavaranAuthService(
|
||||
http as any,
|
||||
audit as any,
|
||||
tokenModel as any,
|
||||
),
|
||||
});
|
||||
return { management, http, audit, staff };
|
||||
}
|
||||
|
||||
describe("Fanavaran outgoing Location headers", () => {
|
||||
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" } },
|
||||
{ workflow: { assignedForReviewBy: { actorId: "damage-expert" } } },
|
||||
-1,
|
||||
);
|
||||
staff[2].findById.mockImplementation(async (id: string) =>
|
||||
id === "blame-expert"
|
||||
? { locations: [{ id: "210050", name: "Blame branch" }] }
|
||||
: null,
|
||||
);
|
||||
staff[3].findById.mockImplementation(async (id: string) =>
|
||||
id === "damage-expert"
|
||||
? { locations: [{ id: "110011", name: "Claim branch" }] }
|
||||
: null,
|
||||
);
|
||||
management.assertFanavaranVehicleReviewApproved = jest.fn();
|
||||
management.previewFanavaranSubmitV2 = jest.fn().mockResolvedValue({
|
||||
PolicyId: 1, AccidentCauseId: 6, CulpritLicenceNo: "1234567890",
|
||||
});
|
||||
await management.executeFanavaranV2Submit("claim-1", "parsian");
|
||||
expect(http.post.mock.calls.at(-1)?.[2].headers).toMatchObject({
|
||||
Location: "110011",
|
||||
});
|
||||
});
|
||||
|
||||
it("prefers the claim creator over the linked blame creator", async () => {
|
||||
const { management, http, staff } = createHarness(
|
||||
{ initiatedByFieldExpertId: "blame-creator" },
|
||||
{ initiatedByFieldExpertId: "claim-creator" },
|
||||
-1,
|
||||
);
|
||||
staff[0].findById.mockImplementation(async (id: string) =>
|
||||
id === "blame-creator"
|
||||
? { locations: [{ id: "210050", name: "Blame branch" }] }
|
||||
: null,
|
||||
);
|
||||
staff[1].findById.mockImplementation(async (id: string) =>
|
||||
id === "claim-creator"
|
||||
? { locations: [{ id: "110011", name: "Claim branch" }] }
|
||||
: null,
|
||||
);
|
||||
await management.postFanavaranJson(
|
||||
"https://example.test/claims",
|
||||
{},
|
||||
"parsian",
|
||||
undefined,
|
||||
"claim-1",
|
||||
);
|
||||
expect(http.post.mock.calls.at(-1)?.[2].headers).toMatchObject({
|
||||
Location: "110011",
|
||||
});
|
||||
});
|
||||
|
||||
it.each(["unlinked", "deleted"])(
|
||||
"uses the assigned damage expert when the blame case is %s",
|
||||
async (kind) => {
|
||||
const { management, http } = createHarness(
|
||||
{},
|
||||
{
|
||||
...(kind === "unlinked" ? { blameRequestId: undefined } : {}),
|
||||
workflow: { assignedForReviewBy: { actorId: "damage-1" } },
|
||||
},
|
||||
3,
|
||||
);
|
||||
if (kind === "deleted")
|
||||
management.blameRequestDbService.findById.mockResolvedValue(null);
|
||||
await management.postFanavaranJson(
|
||||
"https://example.test/claims",
|
||||
{},
|
||||
"parsian",
|
||||
undefined,
|
||||
"claim-1",
|
||||
);
|
||||
expect(http.post.mock.calls.at(-1)?.[2].headers).toMatchObject({
|
||||
Location: "987654",
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it.each([{}, { initiatedByFieldExpertId: "unconfigured-staff" }])(
|
||||
"does not submit a claim using the tenant default when no staff location can be resolved: %j",
|
||||
async (claim) => {
|
||||
const { management, http } = createHarness({}, claim, -1);
|
||||
await expect(
|
||||
management.postFanavaranJson(
|
||||
"https://example.test/claims",
|
||||
{},
|
||||
"parsian",
|
||||
undefined,
|
||||
"claim-1",
|
||||
),
|
||||
).rejects.toMatchObject({
|
||||
response: expect.objectContaining({
|
||||
code: "FANAVARAN_STAFF_LOCATION_MISSING",
|
||||
}),
|
||||
});
|
||||
expect(http.post).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
[
|
||||
"file maker",
|
||||
{ initiatedByFieldExpertId: "staff-1", isMadeByFileMaker: true },
|
||||
{},
|
||||
0,
|
||||
],
|
||||
["file reviewer", { assignedFileReviewerId: "staff-1" }, {}, 1],
|
||||
["blame expert", { expert: { assignedExpertId: "staff-1" } }, {}, 2],
|
||||
[
|
||||
"damage expert",
|
||||
{},
|
||||
{ workflow: { assignedForReviewBy: { actorId: "staff-1" } } },
|
||||
3,
|
||||
],
|
||||
["field expert", { initiatedByFieldExpertId: "staff-1" }, {}, 4],
|
||||
])(
|
||||
"sends the %s location on claim POSTs",
|
||||
async (_name, blame, claim, role) => {
|
||||
const { management, http } = createHarness(
|
||||
blame as object,
|
||||
claim as object,
|
||||
role as number,
|
||||
);
|
||||
await management.postFanavaranJson(
|
||||
"https://example.test/claims",
|
||||
{},
|
||||
"tejaratno",
|
||||
undefined,
|
||||
"claim-1",
|
||||
);
|
||||
expect(http.post).toHaveBeenLastCalledWith(
|
||||
"https://example.test/claims",
|
||||
{},
|
||||
{
|
||||
headers: expect.objectContaining({ Location: "987654" }),
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
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,
|
||||
}));
|
||||
staff[3].findById.mockImplementation(async (id: string) => ({
|
||||
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]));
|
||||
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" }),
|
||||
});
|
||||
expect(http.post).toHaveBeenCalledTimes(4);
|
||||
});
|
||||
|
||||
it("changes Location while reusing the same login token", async () => {
|
||||
const { management, http } = createHarness({}, {}, -1);
|
||||
const auth = management.fanavaranAuthService as FanavaranAuthService;
|
||||
const first = await auth.getRequestHeaders("tejaratno", {
|
||||
locationOverride: "987654",
|
||||
});
|
||||
const second = await auth.getRequestHeaders("tejaratno", {
|
||||
locationOverride: "123456",
|
||||
});
|
||||
expect(first.Location).toBe("987654");
|
||||
expect(second.Location).toBe("123456");
|
||||
expect(first.authenticationToken).toBe(second.authenticationToken);
|
||||
expect(http.post).toHaveBeenCalledTimes(2);
|
||||
for (const [, , config] of http.post.mock.calls) {
|
||||
expect(config.headers).not.toHaveProperty("Location");
|
||||
}
|
||||
});
|
||||
|
||||
it("records the outgoing staff location in policy inquiry audit metadata", async () => {
|
||||
const { management, http, audit } = createHarness(
|
||||
{ initiatedByFieldExpertId: "staff-1" },
|
||||
{},
|
||||
4,
|
||||
);
|
||||
await management.getPolicyIdFromNationalCode(
|
||||
"1234567890",
|
||||
getFanavaranClientProfile("tejaratno").auth,
|
||||
"test",
|
||||
{ claimCaseId: "claim-1", clientKey: "tejaratno" },
|
||||
{ claimCaseId: "claim-1", clientKey: "tejaratno" },
|
||||
);
|
||||
expect(http.get).toHaveBeenCalledWith(
|
||||
expect.any(String),
|
||||
expect.objectContaining({
|
||||
headers: expect.objectContaining({ Location: "987654" }),
|
||||
}),
|
||||
);
|
||||
const inquiryMetadata = audit.recordStep.mock.calls
|
||||
.map(([entry]) => entry)
|
||||
.filter((entry) => entry.requestMethod === "GET")
|
||||
.map((entry) => entry.requestMeta);
|
||||
expect(inquiryMetadata).toHaveLength(2);
|
||||
expect(inquiryMetadata).toEqual([
|
||||
expect.objectContaining({ location: "987654" }),
|
||||
expect.objectContaining({ location: "987654" }),
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -124,7 +124,7 @@ export class CreateInsurerExpertDto {
|
||||
@ApiPropertyOptional({
|
||||
type: [ExpertLocationDto],
|
||||
description:
|
||||
'Fanavaran Location entries (id = OpBUId). Sent as the HTTP Location header on Fanavaran business calls for this expert.',
|
||||
'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.',
|
||||
})
|
||||
@IsOptional()
|
||||
@IsArray()
|
||||
|
||||
@@ -1,4 +1,9 @@
|
||||
import { ForbiddenException, Injectable, Logger } from "@nestjs/common";
|
||||
import {
|
||||
BadRequestException,
|
||||
ForbiddenException,
|
||||
Injectable,
|
||||
Logger,
|
||||
} from "@nestjs/common";
|
||||
import {
|
||||
FanavaranClientKey,
|
||||
getFanavaranClientProfile,
|
||||
@@ -45,11 +50,13 @@ export class FanavaranLocationService {
|
||||
|
||||
/**
|
||||
* First staff candidate with a stored `locations[].id` wins.
|
||||
* Fallback: tenant auth.location (lookups / cases with no staff locations).
|
||||
* Tenant auth.location is allowed only when requireStaffLocation is false.
|
||||
*/
|
||||
async resolveBusinessLocation(input: {
|
||||
clientKey: FanavaranClientKey;
|
||||
staffCandidateIds?: Array<string | null | undefined>;
|
||||
/** Claim submissions must never silently use a tenant-wide branch. */
|
||||
requireStaffLocation?: boolean;
|
||||
/** @deprecated Prefer staffCandidateIds — kept for older call sites. */
|
||||
isMadeByFileMaker?: boolean;
|
||||
fileMakerId?: string | null;
|
||||
@@ -79,8 +86,17 @@ export class FanavaranLocationService {
|
||||
}
|
||||
}
|
||||
|
||||
this.logger.debug(
|
||||
`Fanavaran Location fallback to tenant default → ${defaultLocation}`,
|
||||
if (input.requireStaffLocation) {
|
||||
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.",
|
||||
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"}`,
|
||||
);
|
||||
return defaultLocation;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user