fix: support manual accident addresses and expose final Fanavaran completion

Accept and persist address-only locations across user and expert flows, preserve workflow authorization, and include addresses in reports and Fanavaran review. Expose persisted final submission completion so the expert panel can prevent repeat sends.
This commit is contained in:
SepehrYahyaee
2026-11-21 09:45:13 +03:30
parent b63525c863
commit c6022a1646
15 changed files with 244 additions and 25 deletions
@@ -14,6 +14,14 @@ describe("buildInsurerFileReport", () => {
return field?.value;
};
it("shows an address-only accident location in the exported report", () => {
const address = "تهران، خیابان آزادی، مقابل دانشگاه";
const report = buildInsurerFileReport({
blame: { type: "CAR_BODY", parties: [{ role: "FIRST", location: { address } }] },
});
expect(getFieldValue(report, PR.accidentSection, PR.location)).toBe(address);
});
it("separates insurance blocks and exposes Fanavaran/timeline/evaluation data", () => {
const fileCreatedAt = new Date("2026-08-10T09:53:23.588Z");
const evaluationSubmittedAt = new Date("2026-08-10T12:30:45.000Z");
@@ -37,7 +37,7 @@ type ReportParty = ReportRecord & {
insurance?: ReportRecord & { carBodyInsurance?: ReportRecord };
vehicle?: ReportRecord;
statement?: ReportRecord;
location?: { lat?: number; lon?: number };
location?: { lat?: number; lon?: number; address?: string };
participants?: ReportRecord[];
participantRoles?: ReportRecord;
};
@@ -1016,9 +1016,9 @@ function buildAccidentReportSection(
{
label: PR.location,
value:
location?.lat != null && location?.lon != null
asString(location?.address) ?? (location?.lat != null && location?.lon != null
? `${location.lat}، ${location.lon}`
: undefined,
: undefined),
},
{
label: PR.weather,
@@ -1887,7 +1887,7 @@ export class ClaimRequestManagementService {
private async buildFanavaranSubmitPayload(input: {
accidentReason?: { id?: string | number | null; fanavaran?: number | null };
createdAt?: Date | string;
location?: { lat?: number; lon?: number };
location?: { lat?: number; lon?: number; address?: string };
damageParts?: any[];
resolvePolicyId: () => Promise<number | null>;
logPrefix: string;
@@ -1929,7 +1929,7 @@ export class ClaimRequestManagementService {
result.AccidentTime = this.getTime24Hour(input.createdAt);
}
result.AccidentLocationAddress = FANAVARAN_ACCIDENT_LOCATION_ADDRESS;
result.AccidentLocationAddress = input.location?.address?.trim() || FANAVARAN_ACCIDENT_LOCATION_ADDRESS;
result.EstimateAmount = this.normalizeFanavaranEstimateAmount(
input.damageParts ? this.calculateEstimateAmount(input.damageParts) : 0,
@@ -5891,7 +5891,7 @@ export class ClaimRequestManagementService {
}),
);
const initial: FanavaranFieldValues = {
AccidentLocationAddress: FANAVARAN_ACCIDENT_LOCATION_ADDRESS,
AccidentLocationAddress: blame.parties?.find((party: any) => party.role === 'FIRST')?.location?.address?.trim() || blame.parties?.find((party: any) => party.location?.address?.trim())?.location.address.trim() || FANAVARAN_ACCIDENT_LOCATION_ADDRESS,
AccidentCityId: defaults.AccidentCityId,
AccidentReportTypeId: defaults.AccidentReportTypeId,
DmgHistoryStatus: defaults.DmgHistoryStatus,
@@ -12,6 +12,7 @@ describe("fanavaranClaimReferences", () => {
expertiseId: 22,
}),
).toEqual({
submissionCompleted: true,
claimId: 987654,
claimNo: 123456,
dmgCaseId: 11,
@@ -40,6 +41,7 @@ describe("fanavaranClaimReferences", () => {
},
}),
).toEqual({
submissionCompleted: true,
claimId: 100,
claimNo: 101,
dmgCaseId: 102,
@@ -64,11 +66,30 @@ describe("fanavaranClaimReferences", () => {
expertiseId: 22,
}),
).toEqual({
submissionCompleted: true,
claimId: 987654,
expertiseId: 22,
});
});
it("keeps partial stage codes retryable", () => {
expect(fanavaranClaimReferences({ status: ClaimCaseStatus.COMPLETED, claimId: 1, dmgCaseId: 2 }))
.not.toHaveProperty("submissionCompleted");
});
it("exposes final acceptance independently of local workflow status", () => {
expect(fanavaranClaimReferences({ status: ClaimCaseStatus.EXPERT_REVIEWING, expertiseId: 22 }))
.toEqual({ submissionCompleted: true });
expect(fanavaranClaimReferences({
status: ClaimCaseStatus.COMPLETED,
fanavaranSync: { expertise: { status: "success" } },
})).toEqual({ submissionCompleted: true });
expect(fanavaranClaimReferences({
status: ClaimCaseStatus.COMPLETED,
fanavaranSync: { expertise: { status: "failed" } },
})).toBeUndefined();
});
it("returns undefined before the claim is completed", () => {
expect(
fanavaranClaimReferences({
@@ -5,6 +5,8 @@ import {
} from "./fanavaran-attachment-status";
export type FanavaranClaimReferences = {
/** Final expertise has been accepted; earlier stage codes alone are insufficient. */
submissionCompleted?: boolean;
claimId?: number;
claimNo?: number;
dmgCaseId?: number;
@@ -21,7 +23,8 @@ export type FanavaranClaimReferences = {
};
/**
* Claim reference codes appear on COMPLETED. Upload receipts/status are visible earlier.
* Claim reference codes appear on COMPLETED. Upload receipts and final-submission
* acceptance are visible independently of local workflow status.
*/
export function fanavaranClaimReferences(claim: {
status?: string;
@@ -33,9 +36,16 @@ export function fanavaranClaimReferences(claim: {
baseClaim?: FanavaranReferenceStage | null;
damageCase?: FanavaranReferenceStage | null;
attachments?: FanavaranAttachmentStage | null;
expertise?: { status?: string; expertiseId?: number | null } | null;
} | null;
}): FanavaranClaimReferences | undefined {
const refs: FanavaranClaimReferences = {};
if (
claim.expertiseId != null ||
claim.fanavaranSync?.expertise?.status === "success"
) {
refs.submissionCompleted = true;
}
const attachments = fanavaranAttachmentStatus(
claim.fanavaranSync?.attachments,
);
@@ -44,7 +54,7 @@ export function fanavaranClaimReferences(claim: {
refs.attachments = attachments;
}
if (claim.status !== ClaimCaseStatus.COMPLETED) {
return attachments ? refs : undefined;
return Object.keys(refs).length ? refs : undefined;
}
if (claim.claimId != null) refs.claimId = claim.claimId;
if (claim.claimNo != null) refs.claimNo = claim.claimNo;
+2 -1
View File
@@ -208,7 +208,7 @@ export class ClaimDetailV2ResponseDto {
@ApiPropertyOptional({
description:
"Fanavaran claim reference. Returned only after the local claim reaches COMPLETED. Each of claimId, claimNo, dmgCaseId, and expertiseId is included when Fanavaran has supplied it.",
"Fanavaran claim references are returned after local completion. submissionCompleted is true once final expertise is accepted, independently of local status; earlier stage codes do not imply final submission.",
example: {
claimId: 987654,
claimNo: 123456,
@@ -217,6 +217,7 @@ export class ClaimDetailV2ResponseDto {
},
})
fanavaran?: {
submissionCompleted?: boolean;
claimId?: number;
claimNo?: number;
dmgCaseId?: number;
@@ -65,6 +65,7 @@ describe("insurer expert file summaries", () => {
);
expect(detail.fanavaran).toEqual({
submissionCompleted: true,
claimId: 101,
claimNo: 102,
dmgCaseId: 103,
+1 -1
View File
@@ -51,7 +51,7 @@ type BlamePartyRow = {
statement?: { admitsGuilt?: boolean; claimsDamage?: boolean };
insurance?: Record<string, unknown>;
vehicle?: Record<string, unknown>;
location?: { lat?: number; lon?: number };
location?: { lat?: number; lon?: number; address?: string };
};
/** Full party row for the damaged vehicle (owner / beneficiary side). */
@@ -0,0 +1,91 @@
import { BadRequestException } from "@nestjs/common";
import { Types, model } from "mongoose";
import { normalizeAccidentLocation } from "./accident-location";
import { LocationSchema } from "./entities/schema/accidentInformation.type";
import { ClaimRequestManagementService } from "src/claim-request-management/claim-request-management.service";
import { RequestManagementService } from "./request-management.service";
const address = "تهران، خیابان آزادی، روبه‌روی دانشگاه";
describe("accident location fallback", () => {
it("accepts an address without fabricating coordinates", () => {
expect(normalizeAccidentLocation({ address: ` ${address} `, ignored: true })).toEqual({ address });
expect(normalizeAccidentLocation({ lat: 35, lon: 51 })).toEqual({ lat: 35, lon: 51 });
expect(normalizeAccidentLocation({ lat: 0, lon: 0 })).toEqual({ lat: 0, lon: 0 });
expect(normalizeAccidentLocation({ lat: 35, lon: 51, address })).toEqual({ lat: 35, lon: 51, address });
});
it.each([undefined, {}, { address: " " }, { address: "تهران" }, { address: "ا".repeat(1001) }, { address: 55 }, { lat: 35 }, { lat: 91, lon: 51 }, { lat: 35, lon: Infinity }, { lat: "35", lon: "51" }])("rejects invalid input in Persian: %j", value => {
expect(() => normalizeAccidentLocation(value)).toThrow(BadRequestException);
try { normalizeAccidentLocation(value); } catch (error) { expect((error as Error).message).toMatch(/[آ-ی]/); }
});
it("persists address-only locations through the actual schema", async () => {
const Location = model("ManualAccidentLocationTest", LocationSchema);
const record = new Location({ address, lat: undefined, lon: undefined });
await record.validate();
expect(record.toObject()).toEqual({ address });
});
for (const type of ["THIRD_PARTY", "CAR_BODY"]) {
for (const role of ["FIRST", "SECOND"]) {
it(`advances the ${type} ${role} location step using an address`, async () => {
const req: any = {
_id: new Types.ObjectId(), type,
workflow: { currentStep: `${role}_LOCATION`, completedSteps: [] },
parties: [{ role, person: { userId: new Types.ObjectId() } }],
save: jest.fn().mockResolvedValue(undefined),
};
const service: any = new (RequestManagementService as any)();
service.blameRequestDbService = { findById: async () => req };
service.assertPartyOwner = jest.fn();
service.assertExpectedPartyRole = jest.fn();
service.isBlameOnBehalfActor = () => false;
service.advanceWorkflowToNext = jest.fn(async (_req, step) => {
req.workflow.completedSteps.push(step);
req.workflow.currentStep = `${role}_VOICE`;
});
const response = await service.addDetailLocationV2(String(req._id), { address }, { sub: String(req.parties[0].person.userId) });
expect(req.parties[0].location).toEqual({ address });
expect(response.workflow.currentStep).toBe(`${role}_VOICE`);
expect(req.save).toHaveBeenCalledTimes(1);
expect(service.assertPartyOwner).toHaveBeenCalledTimes(1);
expect(req.history[0].metadata.location).toEqual({ address });
req.save.mockClear(); service.advanceWorkflowToNext.mockClear();
req.workflow.currentStep = `${role}_LOCATION`;
await expect(service.addDetailLocationV2(String(req._id), { address: " " }, {})).rejects.toThrow(BadRequestException);
expect(req.save).not.toHaveBeenCalled();
expect(service.advanceWorkflowToNext).not.toHaveBeenCalled();
});
}
}
it("suggests the recorded address for Fanavaran and preserves expert/sent overrides", async () => {
const previous = process.env.FANAVARAN_CLIENT;
process.env.FANAVARAN_CLIENT = "parsian";
try {
const service: any = Object.create(ClaimRequestManagementService.prototype);
service.getFanavaranLookupRows = jest.fn().mockResolvedValue([]);
const blame = { type: "THIRD_PARTY", parties: [{ role: "FIRST", location: { address } }] };
for (const [claim, expected] of [
[{}, address],
[{ fanavaranFieldReview: { values: { AccidentLocationAddress: "نشانی اصلاح‌شده کارشناس" } } }, "نشانی اصلاح‌شده کارشناس"],
[{ claimId: 1, fanavaranSync: { baseClaim: { status: "success", lastPayload: { AccidentLocationAddress: "نشانی ارسال‌شده" } } } }, "نشانی ارسال‌شده"],
] as const) {
const context = await service.getFanavaranStageFieldsContext(claim, blame);
expect(context.fields.find((field: any) => field.key === "AccidentLocationAddress").value).toBe(expected);
}
} finally { if (previous === undefined) delete process.env.FANAVARAN_CLIENT; else process.env.FANAVARAN_CLIENT = previous; }
});
it.each([false, true])("stores expert-mirror manual addresses (file maker: %s)", async isMadeByFileMaker => {
const req: any = { _id: new Types.ObjectId(), isMadeByFileMaker, parties: [{ role: "FIRST" }], save: jest.fn(), history: [] };
const service: any = new (RequestManagementService as any)();
service.blameRequestDbService = { findById: async () => req };
service.verifyExpertAccessForBlameV2 = jest.fn();
service.resolvePartyRoleV3 = () => "FIRST";
service.assertBlameV3PartyDetailPhase = jest.fn();
service.resolveBlameHistoryActorType = () => "field_expert";
await service.addPartyLocationV3(String(req._id), { sub: String(new Types.ObjectId()) }, { address }, "FIRST");
expect(req.parties[0].location).toEqual({ address });
expect(service.verifyExpertAccessForBlameV2).toHaveBeenCalled();
});
});
@@ -0,0 +1,36 @@
import { BadRequestException } from "@nestjs/common";
export type AccidentLocation = { lat?: number; lon?: number; address?: string };
/** Accept real coordinates or a written address, never a default map centre. */
export function normalizeAccidentLocation(value: unknown): AccidentLocation {
if (!value || typeof value !== "object" || Array.isArray(value)) {
throw new BadRequestException("موقعیت حادثه را روی نقشه مشخص کنید یا نشانی آن را بنویسید.");
}
const input = value as Record<string, unknown>;
const result: AccidentLocation = {};
if (input.lat != null || input.lon != null) {
if (
typeof input.lat !== "number" || !Number.isFinite(input.lat) || Math.abs(input.lat) > 90 ||
typeof input.lon !== "number" || !Number.isFinite(input.lon) || Math.abs(input.lon) > 180
) {
throw new BadRequestException("مختصات محل حادثه معتبر نیست. موقعیت را دوباره انتخاب کنید یا نشانی را بنویسید.");
}
result.lat = input.lat;
result.lon = input.lon;
}
if (input.address != null) {
if (typeof input.address !== "string") {
throw new BadRequestException("نشانی محل حادثه باید به صورت متن باشد.");
}
const address = input.address.trim();
if (address && (address.length < 10 || address.length > 1000)) {
throw new BadRequestException("نشانی محل حادثه باید بین ۱۰ تا ۱۰۰۰ نویسه باشد.");
}
if (address) result.address = address;
}
if (result.lat == null && !result.address) {
throw new BadRequestException("موقعیت حادثه را روی نقشه مشخص کنید یا نشانی کامل آن را بنویسید (حداقل ۱۰ نویسه).");
}
return result;
}
@@ -223,7 +223,9 @@ describe("V6 call-center workflow", () => {
expect(req.workflow.nextStep).toBe(Step.FIRST_LOCATION);
await service.uploadFirstPartyVideoV2(id, media, first);
expect(req.workflow.currentStep).toBe(Step.FIRST_LOCATION);
await service.addDetailLocationV2(id, { lat: 35, lng: 51 } as any, first);
const location = mode === "vin" ? { address: "تهران، خیابان آزادی، محل حادثه" } : { lat: 35, lon: 51 };
await service.addDetailLocationV2(id, location, first);
expect(req.parties[0].location).toEqual(location);
expect(req.workflow.currentStep).toBe(Step.FIRST_VOICE);
await service.uploadVoiceV2(id, media, first);
expect(req.workflow.currentStep).toBe(Step.FIRST_DESCRIPTION);
@@ -258,7 +260,7 @@ describe("V6 call-center workflow", () => {
req.workflow.nextStep = Step.SECOND_VOICE;
await service.addDetailLocationV2(
id,
{ lat: 35, lng: 51 } as any,
{ address: "نشانی اعلام‌شده توسط طرف دوم حادثه" },
second,
);
await service.uploadVoiceV2(id, media, second);
@@ -196,11 +196,14 @@ export class SecondPartyDetail {
}
export class LocationDto {
@ApiProperty({ type: Number, required: true })
lat: number;
@ApiPropertyOptional({ type: Number, description: "Provide both coordinates or a written accident address." })
lat?: number;
@ApiProperty({ type: Number, required: true })
lon: number;
@ApiPropertyOptional({ type: Number })
lon?: number;
@ApiPropertyOptional({ minLength: 10, maxLength: 1000, description: "Required when coordinates are unavailable." })
address?: string;
}
// export class CreateRequestDto {
@@ -31,8 +31,9 @@ export const AccidentClassificationSchema =
@Schema({ _id: false })
export class Location {
@Prop() lat: number;
@Prop() lon: number;
@Prop() lat?: number;
@Prop() lon?: number;
@Prop({ trim: true, maxlength: 1000 }) address?: string;
}
export const LocationSchema = SchemaFactory.createForClass(Location);
@@ -56,4 +57,4 @@ export class AccidentInfo {
@Prop() roadCondition?: string;
@Prop() lightCondition?: string;
}
export const AccidentInfoSchema = SchemaFactory.createForClass(AccidentInfo);
export const AccidentInfoSchema = SchemaFactory.createForClass(AccidentInfo);
@@ -1,4 +1,5 @@
import { UserClaimBranchService, userClaimBranchContext, usesUserClaimBranch } from "src/client/user-claim-branch.service";
import { normalizeAccidentLocation } from "./accident-location";
import {
BadRequestException,
ConflictException,
@@ -2659,7 +2660,8 @@ export class RequestManagementService {
: undefined;
}
party.location = body as any;
const location = normalizeAccidentLocation(body);
party.location = location;
await this.advanceWorkflowToNext(req, stepKey);
@@ -2673,7 +2675,7 @@ export class RequestManagementService {
actorName: user?.fullName,
actorType: "user",
},
metadata: { location: body, role },
metadata: { location, role },
} as any);
await (req as any).save();
@@ -5584,7 +5586,7 @@ export class RequestManagementService {
if (!dto?.location) {
throw new BadRequestException("location is required");
}
req.parties[firstIdx].location = dto.location as any;
req.parties[firstIdx].location = normalizeAccidentLocation(dto.location);
const completed = Array.isArray(req.workflow?.completedSteps)
? req.workflow.completedSteps
@@ -8505,7 +8507,7 @@ export class RequestManagementService {
if ((req as any).isMadeByFileMaker) {
const role = this.resolvePartyRoleV3(req, partyRole);
const idx = this.getPartyIndex(req, role);
if (idx !== -1 && body) req.parties[idx].location = body as any;
if (idx !== -1 && body) req.parties[idx].location = normalizeAccidentLocation(body);
await (req as any).save();
return { requestId: req._id, publicId: req.publicId, partyRole: role };
}
@@ -8516,7 +8518,8 @@ export class RequestManagementService {
const idx = this.getPartyIndex(req, role);
if (idx === -1) throw new BadRequestException(`${role} party not found`);
req.parties[idx].location = body as any;
const location = normalizeAccidentLocation(body);
req.parties[idx].location = location;
if (!Array.isArray(req.history)) req.history = [];
req.history.push({
@@ -8526,7 +8529,7 @@ export class RequestManagementService {
actorName: `${actor.firstName || ""} ${actor.lastName || ""}`.trim(),
actorType: this.resolveBlameHistoryActorType(actor),
},
metadata: { partyRole: role, location: body },
metadata: { partyRole: role, location },
} as any);
await (req as any).save();