dynamic locations

This commit is contained in:
2026-11-11 14:10:01 +03:30
parent 5e3bd02243
commit 658a8a74cc
18 changed files with 454 additions and 111 deletions
@@ -3365,17 +3365,15 @@ export class ClaimRequestManagementService {
}
/**
* Parsian + V4/V5 FileMaker flows: Location from file-maker.locations[].id,
* else file-reviewer.locations[].id, else tenant auth.location.
* 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.
*/
private async resolveFanavaranLocationForClaim(
claimCaseId: string,
clientKey: FanavaranClientKey,
): Promise<string> {
const defaultLocation = getFanavaranClientProfile(clientKey).auth.location;
if (clientKey !== "parsian") {
return defaultLocation;
}
try {
const claimCase = await this.claimCaseDbService.findById(claimCaseId);
@@ -3386,19 +3384,21 @@ export class ClaimRequestManagementService {
const blame = await this.blameRequestDbService.findById(
String(claimCase.blameRequestId),
);
if (!(blame as any)?.isMadeByFileMaker) {
if (!blame) {
return defaultLocation;
}
return this.fanavaranLocationService.resolveBusinessLocation({
clientKey,
isMadeByFileMaker: true,
fileMakerId: (blame as any)?.initiatedByFieldExpertId
? String((blame as any).initiatedByFieldExpertId)
: null,
fileReviewerId: (blame as any)?.assignedFileReviewerId
? String((blame as any).assignedFileReviewerId)
: null,
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(
+3 -1
View File
@@ -117,7 +117,8 @@ const SHARED_FANAVARAN_DEFAULTS: FanavaranPayloadDefaults = {
/**
* Seed / code fallback profiles. On app boot these are inserted into
* `fanavaranClientConfigs` only when a key is missing (never overwrite DB edits).
* `fanavaranClientConfigs` only when a key is missing. The config service also
* migrates known legacy defaults on existing documents.
* Runtime reads prefer the in-memory cache loaded from Mongo.
*/
export const SEED_FANAVARAN_CLIENT_PROFILES: Record<
@@ -182,6 +183,7 @@ export const SEED_FANAVARAN_CLIENT_PROFILES: Record<
// GEN.03 financial case owner / GEN.08 third-party financial assessor.
ClaimExpertId: 5347,
ExpertiseClaimExpertId: 5350,
ClaimFileTypeId: 17,
},
},
};
@@ -120,6 +120,17 @@ export class CreateInsurerExpertDto {
@IsOptional()
@IsString()
address?: string;
@ApiPropertyOptional({
type: [ExpertLocationDto],
description:
"Fanavaran Location entries (id = OpBUId). Sent as the HTTP Location header on Fanavaran business calls for this expert.",
})
@IsOptional()
@IsArray()
@ValidateNested({ each: true })
@Type(() => ExpertLocationDto)
locations?: ExpertLocationDto[];
}
export class CreateBlameExpertByInsurerDto extends CreateInsurerExpertDto {
@@ -147,17 +158,6 @@ export class CreateFileMakerByInsurerDto extends OmitType(
default: RoleEnum.FILE_MAKER,
})
role?: RoleEnum.FILE_MAKER;
@ApiPropertyOptional({
type: [ExpertLocationDto],
description:
"Fanavaran Location entries (id = OpBUId). Used for Parsian V4/V5 submits.",
})
@IsOptional()
@IsArray()
@ValidateNested({ each: true })
@Type(() => ExpertLocationDto)
locations?: ExpertLocationDto[];
}
export class CreateFileReviewerByInsurerDto extends OmitType(
@@ -169,15 +169,4 @@ export class CreateFileReviewerByInsurerDto extends OmitType(
default: RoleEnum.FILE_REVIEWER,
})
role?: RoleEnum.FILE_REVIEWER;
@ApiPropertyOptional({
type: [ExpertLocationDto],
description:
"Fanavaran Location entries. Must overlap FileMaker locations on Parsian V4/V5 cases.",
})
@IsOptional()
@IsArray()
@ValidateNested({ each: true })
@Type(() => ExpertLocationDto)
locations?: ExpertLocationDto[];
}
@@ -2038,6 +2038,7 @@ export class ExpertInsurerService {
}
const hashedPassword = await this.hashService.hash(payload.password);
const locations = this.normalizeExpertLocations(payload.locations);
const basePayload: any = {
...payload,
email,
@@ -2049,6 +2050,7 @@ export class ExpertInsurerService {
role === RoleEnum.EXPERT ? String(clientObjectId) : clientObjectId,
branchId: new Types.ObjectId(payload.branchId),
insuActivityCo: String(clientObjectId),
...(locations ? { locations } : {}),
};
const created =
@@ -0,0 +1,38 @@
import { SEED_FANAVARAN_CLIENT_PROFILES } from "src/core/config/fanavaran-client.config";
import { FanavaranClientConfigService } from "./fanavaran-client-config.service";
describe("Moallem attachment file type", () => {
it("seeds file type 17 for Moallem and retains the other tenant file types", () => {
expect(
SEED_FANAVARAN_CLIENT_PROFILES.moallem.defaults.ClaimFileTypeId,
).toBe(17);
expect(
SEED_FANAVARAN_CLIENT_PROFILES.parsian.defaults.ClaimFileTypeId,
).toBe(63);
expect(
SEED_FANAVARAN_CLIENT_PROFILES.tejaratno.defaults.ClaimFileTypeId,
).toBe(23);
});
it("migrates only Moallem's old shared default on existing installations", async () => {
const service = Object.create(
FanavaranClientConfigService.prototype,
) as any;
service.configModel = {
updateOne: jest.fn().mockResolvedValue({ modifiedCount: 1 }),
findOne: jest.fn().mockReturnValue({
select: () => ({
lean: () => ({ exec: async () => ({ _id: "existing" }) }),
}),
}),
create: jest.fn(),
};
await service.seedMissingProfiles();
expect(service.configModel.updateOne).toHaveBeenCalledTimes(1);
expect(service.configModel.updateOne).toHaveBeenCalledWith(
{ key: "moallem", "defaults.ClaimFileTypeId": 23 },
{ $set: { "defaults.ClaimFileTypeId": 17 } },
);
expect(service.configModel.create).not.toHaveBeenCalled();
});
});
@@ -20,7 +20,7 @@ import {
* through the sync helpers in fanavaran-client.config.ts.
*
* Boot behaviour: for each known client key, if no document exists, insert the
* seed profile. Existing documents are never overwritten (ops can edit Mongo).
* seed profile. Existing documents retain ops edits except known legacy defaults.
*/
@Injectable()
export class FanavaranClientConfigService implements OnModuleInit {
@@ -38,6 +38,12 @@ export class FanavaranClientConfigService implements OnModuleInit {
}
async seedMissingProfiles(): Promise<void> {
// Moallem previously inherited the shared file type 23. Correct that legacy
// default on existing deployments while preserving other configured ids.
await this.configModel.updateOne(
{ key: "moallem", "defaults.ClaimFileTypeId": 23 },
{ $set: { "defaults.ClaimFileTypeId": 17 } },
);
for (const key of FANAVARAN_CLIENT_KEYS) {
const seed = SEED_FANAVARAN_CLIENT_PROFILES[key];
const existing = await this.configModel
+115 -34
View File
@@ -1,55 +1,136 @@
import { ForbiddenException } from "@nestjs/common";
import { FanavaranLocationService } from "./fanavaran-location.service";
describe("FanavaranLocationService branch scope", () => {
describe("FanavaranLocationService", () => {
const makerId = "maker-1";
const reviewerId = "reviewer-1";
const fieldExpertId = "field-1";
const createService = (makerBranch?: string, reviewerBranch?: string) =>
const emptyFind = () => jest.fn().mockResolvedValue(null);
const createService = (opts?: {
maker?: Record<string, unknown> | null;
reviewer?: Record<string, unknown> | null;
expert?: Record<string, unknown> | null;
damage?: Record<string, unknown> | null;
field?: Record<string, unknown> | null;
}) =>
new FanavaranLocationService(
{
findById: jest.fn().mockResolvedValue(
makerBranch ? { branchId: makerBranch } : {},
),
findById: jest.fn().mockImplementation(async (id: string) => {
if (opts?.maker && String(id) === makerId) return opts.maker;
return null;
}),
} as any,
{
findById: jest.fn().mockResolvedValue(
reviewerBranch ? { branchId: reviewerBranch } : {},
),
findById: jest.fn().mockImplementation(async (id: string) => {
if (opts?.reviewer && String(id) === reviewerId) return opts.reviewer;
return null;
}),
} as any,
{
findById: opts?.expert
? jest.fn().mockResolvedValue(opts.expert)
: emptyFind(),
} as any,
{
findById: opts?.damage
? jest.fn().mockResolvedValue(opts.damage)
: emptyFind(),
} as any,
{
findById: jest.fn().mockImplementation(async (id: string) => {
if (opts?.field && String(id) === fieldExpertId) return opts.field;
return null;
}),
} as any,
);
it("allows a reviewer to view a file from the same branch", async () => {
const service = createService("branch-1", "branch-1");
describe("branch scope", () => {
it("allows a reviewer to view a file from the same branch", async () => {
const service = createService({
maker: { branchId: "branch-1" },
reviewer: { branchId: "branch-1" },
});
await expect(
service.assertMakerReviewerBranchCompatible({
fileMakerId: makerId,
fileReviewerId: reviewerId,
}),
).resolves.toBeUndefined();
await expect(
service.assertMakerReviewerBranchCompatible({
fileMakerId: makerId,
fileReviewerId: reviewerId,
}),
).resolves.toBeUndefined();
});
it("rejects a reviewer from another branch", async () => {
const service = createService({
maker: { branchId: "branch-1" },
reviewer: { branchId: "branch-2" },
});
await expect(
service.assertMakerReviewerBranchCompatible({
fileMakerId: makerId,
fileReviewerId: reviewerId,
}),
).rejects.toBeInstanceOf(ForbiddenException);
});
it("prefers the immutable case branch snapshot", async () => {
const service = createService({
maker: { branchId: "old-branch" },
reviewer: { branchId: "branch-2" },
});
await expect(
service.assertMakerReviewerBranchCompatible({
fileMakerId: makerId,
fileReviewerId: reviewerId,
caseBranchId: "branch-2",
}),
).resolves.toBeUndefined();
});
});
it("rejects a reviewer from another branch", async () => {
const service = createService("branch-1", "branch-2");
describe("resolveBusinessLocation", () => {
it("uses the first staff candidate location for any tenant", async () => {
const service = createService({
field: { locations: [{ id: "210050", name: "غرب" }] },
reviewer: { locations: [{ id: "100100", name: "دیگر" }] },
});
await expect(
service.assertMakerReviewerBranchCompatible({
fileMakerId: makerId,
fileReviewerId: reviewerId,
}),
).rejects.toBeInstanceOf(ForbiddenException);
});
await expect(
service.resolveBusinessLocation({
clientKey: "tejaratno",
staffCandidateIds: [fieldExpertId, reviewerId],
}),
).resolves.toBe("210050");
});
it("prefers the immutable case branch snapshot", async () => {
const service = createService("old-branch", "branch-2");
it("falls through to a later candidate when earlier staff has no location", async () => {
const service = createService({
field: { locations: [] },
reviewer: { locations: [{ id: "100100", name: "مرکزی" }] },
});
await expect(
service.assertMakerReviewerBranchCompatible({
fileMakerId: makerId,
fileReviewerId: reviewerId,
caseBranchId: "branch-2",
}),
).resolves.toBeUndefined();
await expect(
service.resolveBusinessLocation({
clientKey: "parsian",
staffCandidateIds: [fieldExpertId, reviewerId],
}),
).resolves.toBe("100100");
});
it("falls back to the tenant auth.location when no staff location exists", async () => {
const service = createService({
field: { locations: [] },
});
await expect(
service.resolveBusinessLocation({
clientKey: "moallem",
staffCandidateIds: [fieldExpertId],
}),
).resolves.toBe("1");
});
});
});
+54 -30
View File
@@ -4,14 +4,18 @@ import {
getFanavaranClientProfile,
resolveFanavaranClientKey,
} from "src/core/config/fanavaran-client.config";
import { DamageExpertDbService } from "src/users/entities/db-service/damage-expert.db.service";
import { ExpertDbService } from "src/users/entities/db-service/expert.db.service";
import { FieldExpertDbService } from "src/users/entities/db-service/field-expert.db.service";
import { FileMakerDbService } from "src/users/entities/db-service/file-maker.db.service";
import { FileReviewerDbService } from "src/users/entities/db-service/file-reviewer.db.service";
type LocationEntry = { id?: string; name?: string };
/**
* Parsian V4/V5 FileMaker flows: resolve Fanavaran HTTP `Location` from
* file-maker / file-reviewer `locations[].id`, and enforce maker/reviewer match.
* Resolve Fanavaran HTTP `Location` (OpBUId) from assigned staff
* `locations[].id` for every tenant, and enforce maker/reviewer match on
* Parsian FileMaker flows.
*/
@Injectable()
export class FanavaranLocationService {
@@ -20,6 +24,9 @@ export class FanavaranLocationService {
constructor(
private readonly fileMakerDbService: FileMakerDbService,
private readonly fileReviewerDbService: FileReviewerDbService,
private readonly expertDbService: ExpertDbService,
private readonly damageExpertDbService: DamageExpertDbService,
private readonly fieldExpertDbService: FieldExpertDbService,
) {}
isParsianClient(clientKey?: FanavaranClientKey): boolean {
@@ -37,11 +44,13 @@ export class FanavaranLocationService {
}
/**
* Maker primary location → reviewer primary → tenant auth.location.
* Non-parsian or non-FileMaker flows always use the tenant default.
* First staff candidate with a stored `locations[].id` wins.
* Fallback: tenant auth.location (lookups / cases with no staff locations).
*/
async resolveBusinessLocation(input: {
clientKey: FanavaranClientKey;
staffCandidateIds?: Array<string | null | undefined>;
/** @deprecated Prefer staffCandidateIds — kept for older call sites. */
isMadeByFileMaker?: boolean;
fileMakerId?: string | null;
fileReviewerId?: string | null;
@@ -49,30 +58,25 @@ export class FanavaranLocationService {
const defaultLocation = getFanavaranClientProfile(input.clientKey).auth
.location;
if (input.clientKey !== "parsian" || input.isMadeByFileMaker !== true) {
return defaultLocation;
}
const makerLocation = await this.loadPrimaryLocationId(
const candidateIds = [
...(input.staffCandidateIds ?? []),
input.fileMakerId,
"maker",
);
if (makerLocation) {
this.logger.debug(
`Fanavaran Location from file-maker id=${input.fileMakerId} → ${makerLocation}`,
);
return makerLocation;
}
const reviewerLocation = await this.loadPrimaryLocationId(
input.fileReviewerId,
"reviewer",
);
if (reviewerLocation) {
this.logger.debug(
`Fanavaran Location from file-reviewer id=${input.fileReviewerId} → ${reviewerLocation}`,
);
return reviewerLocation;
];
const seen = new Set<string>();
for (const rawId of candidateIds) {
const staffId = rawId != null ? String(rawId).trim() : "";
if (!staffId || seen.has(staffId)) continue;
seen.add(staffId);
const location = await this.loadPrimaryLocationIdFromAnyStaff(staffId);
if (location) {
this.logger.debug(
`Fanavaran Location from staff id=${staffId} → ${location}`,
);
return location;
}
}
this.logger.debug(
@@ -158,14 +162,34 @@ export class FanavaranLocationService {
}
}
private async loadPrimaryLocationId(
userId: string | null | undefined,
kind: "maker" | "reviewer",
private async loadPrimaryLocationIdFromAnyStaff(
userId: string,
): Promise<string | undefined> {
const ids = await this.loadLocationIds(userId, kind);
const ids = await this.loadLocationIdsFromAnyStaff(userId);
return ids[0];
}
private async loadLocationIdsFromAnyStaff(userId: string): Promise<string[]> {
const loaders = [
() => this.fileMakerDbService.findById(userId),
() => this.fileReviewerDbService.findById(userId),
() => this.expertDbService.findById(userId),
() => this.damageExpertDbService.findById(userId),
() => this.fieldExpertDbService.findById(userId),
];
for (const load of loaders) {
try {
const doc = await load();
if (doc) {
return this.extractLocationIds((doc as any)?.locations);
}
} catch {
// invalid ObjectId / cast errors — try next collection
}
}
return [];
}
private async loadLocationIds(
userId: string | null | undefined,
kind: "maker" | "reviewer",
@@ -172,6 +172,9 @@ describe("management accounts, optional Fanavaran fields and tenant boundaries",
it.each([
["file_maker", "ThirdPartyClaimExpertId", "CarBodyClaimExpertId"],
["file_reviewer", "ThirdPartyExpertiseClaim", "CarBodyExpertiseClaim"],
["expert", "ThirdPartyClaimExpertId", "CarBodyClaimExpertId"],
["damage_expert", "ThirdPartyClaimExpertId", "CarBodyClaimExpertId"],
["field_expert", "ThirdPartyClaimExpertId", "CarBodyClaimExpertId"],
])(
"persists and edits %s Fanavaran IDs and locations using the real schemas",
async (role, first, second) => {
@@ -187,6 +190,7 @@ describe("management accounts, optional Fanavaran fields and tenant boundaries",
);
expect(row[first]).toBe("100");
expect(row[second]).toBe("200");
expect(row.locations).toMatchObject([{ id: "1", name: "تهران" }]);
const edited = await service.updateStaff(tenant, role, String(row._id), {
[first]: "300",
[second]: null,
+8 -4
View File
@@ -199,12 +199,16 @@ export class ManagementService {
}
if (field === "locations") {
if (
![RoleEnum.FILE_MAKER, RoleEnum.FILE_REVIEWER].includes(
role as RoleEnum,
)
![
RoleEnum.EXPERT,
RoleEnum.DAMAGE_EXPERT,
RoleEnum.FIELD_EXPERT,
RoleEnum.FILE_MAKER,
RoleEnum.FILE_REVIEWER,
].includes(role as RoleEnum)
)
throw new BadRequestException(
"Locations apply only to file makers and reviewers",
"Locations apply only to expert staff roles",
);
if (!Array.isArray(value))
throw new BadRequestException("Locations must be an array");
@@ -9,6 +9,19 @@ 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 })
id: string;
@Prop({ type: String, required: true })
name: string;
}
export const DamageExpertLocationDbSchema = SchemaFactory.createForClass(
DamageExpertLocationModel,
);
@Schema({ _id: false })
export class PersonalInfo {
@Prop({ type: "string" })
@@ -126,6 +139,9 @@ export class DamageExpertModel {
@Prop({ type: Types.ObjectId, index: true })
branchId?: Types.ObjectId;
@Prop({ type: [DamageExpertLocationDbSchema], default: [] })
locations?: DamageExpertLocationModel[];
@Prop({ type: PersonalInfoSchema })
personalInfo?: PersonalInfo;
@@ -4,6 +4,18 @@ import { Degrees } from "src/Types&Enums/degrees.enum";
import { RoleEnum } from "src/Types&Enums/role.enum";
import { UserType } from "src/Types&Enums/userType.enum";
@Schema({ _id: false, versionKey: false })
export class ExpertLocationModel {
@Prop({ type: String, required: true })
id: string;
@Prop({ type: String, required: true })
name: string;
}
export const ExpertLocationDbSchema =
SchemaFactory.createForClass(ExpertLocationModel);
@Schema({ collection: "expert", versionKey: false, timestamps: true })
export class ExpertModel {
@Prop({})
@@ -69,6 +81,9 @@ export class ExpertModel {
@Prop({ type: Types.ObjectId, index: true })
branchId?: Types.ObjectId;
@Prop({ type: [ExpertLocationDbSchema], default: [] })
locations?: ExpertLocationModel[];
@Prop({ type: "string" })
otp: string;
@@ -2,6 +2,19 @@ import { Prop, Schema, SchemaFactory } from "@nestjs/mongoose";
import { Types } from "mongoose";
import { RoleEnum } from "src/Types&Enums/role.enum";
@Schema({ _id: false, versionKey: false })
export class FieldExpertLocationModel {
@Prop({ type: String, required: true })
id: string;
@Prop({ type: String, required: true })
name: string;
}
export const FieldExpertLocationDbSchema = SchemaFactory.createForClass(
FieldExpertLocationModel,
);
@Schema({
collection: "field-expert",
versionKey: false,
@@ -31,6 +44,9 @@ export class FieldExpertModel {
@Prop({ type: Types.ObjectId, index: true })
branchId?: Types.ObjectId;
@Prop({ type: [FieldExpertLocationDbSchema], default: [] })
locations?: FieldExpertLocationModel[];
@Prop({ required: true })
password: string;