forked from Yara724/api
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:
@@ -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();
|
||||
|
||||
Reference in New Issue
Block a user