import { BadRequestException, ForbiddenException, Injectable, Logger, } from "@nestjs/common"; import { FanavaranClientKey, 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 }; /** * 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 { private readonly logger = new Logger(FanavaranLocationService.name); 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 { return (clientKey ?? resolveFanavaranClientKey()) === "parsian"; } extractLocationIds(locations?: LocationEntry[] | null): string[] { if (!Array.isArray(locations) || locations.length === 0) return []; const ids: string[] = []; for (const entry of locations) { const id = String(entry?.id ?? "").trim(); if (id && !ids.includes(id)) ids.push(id); } return ids; } /** * First staff candidate with a stored `locations[].id` wins. * Tenant auth.location is allowed only when requireStaffLocation is false. */ async resolveBusinessLocation(input: { clientKey: FanavaranClientKey; staffCandidateIds?: Array; /** 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; fileReviewerId?: string | null; }): Promise { const defaultLocation = getFanavaranClientProfile(input.clientKey).auth .location; const candidateIds = [ ...(input.staffCandidateIds ?? []), input.fileMakerId, input.fileReviewerId, ]; const seen = new Set(); 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; } } 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; } /** * When both maker and reviewer have locations, they must share at least one id. * No-op for non-parsian deployments or when either side has no locations. */ async assertMakerReviewerLocationCompatible(input: { fileMakerId?: string | null; fileReviewerId?: string | null; clientKey?: FanavaranClientKey; }): Promise { if (!this.isParsianClient(input.clientKey)) { return; } const makerIds = await this.loadLocationIds(input.fileMakerId, "maker"); const reviewerIds = await this.loadLocationIds( input.fileReviewerId, "reviewer", ); if (makerIds.length === 0 || reviewerIds.length === 0) { return; } const shared = makerIds.some((id) => reviewerIds.includes(id)); if (!shared) { throw new ForbiddenException( "FileReviewer location must match the FileMaker location for this case.", ); } } async fileMakerBranchId( fileMakerId: string | null | undefined, ): Promise { if (!fileMakerId) return undefined; const doc = await this.fileMakerDbService.findById(String(fileMakerId)); const branchId = (doc as any)?.branchId; return branchId ? String(branchId) : undefined; } async fileReviewerBranchId( fileReviewerId: string | null | undefined, ): Promise { if (!fileReviewerId) return undefined; const doc = await this.fileReviewerDbService.findById( String(fileReviewerId), ); const branchId = (doc as any)?.branchId; return branchId ? String(branchId) : undefined; } /** * V4/V5 case visibility is branch-scoped by the FileMaker who created it. * Missing branch assignments are denied instead of widening visibility. */ async assertMakerReviewerBranchCompatible(input: { fileMakerId?: string | null; fileReviewerId?: string | null; caseBranchId?: string | null; }): Promise { const reviewerBranchId = await this.fileReviewerBranchId( input.fileReviewerId, ); const caseBranchId = (input.caseBranchId ? String(input.caseBranchId) : undefined) ?? (await this.fileMakerBranchId(input.fileMakerId)); if (!reviewerBranchId) { throw new ForbiddenException( "FileReviewer account is not assigned to a branch.", ); } if (!caseBranchId || caseBranchId !== reviewerBranchId) { throw new ForbiddenException("This file belongs to another branch."); } } private async loadPrimaryLocationIdFromAnyStaff( userId: string, ): Promise { const ids = await this.loadLocationIdsFromAnyStaff(userId); return ids[0]; } private async loadLocationIdsFromAnyStaff(userId: string): Promise { 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", ): Promise { if (!userId) return []; try { const doc = kind === "maker" ? await this.fileMakerDbService.findById(String(userId)) : await this.fileReviewerDbService.findById(String(userId)); return this.extractLocationIds((doc as any)?.locations); } catch { return []; } } }