automatiacally previous stages submitted

This commit is contained in:
2026-11-11 18:36:10 +03:30
parent 84b92eb55a
commit 8b9dabc9f2
8 changed files with 437 additions and 23 deletions
@@ -68,3 +68,37 @@ To verify remote receipts directly, use
`GET /v2/fanavaran/parsian/claim-cases/{claimCaseId}/hull/files`.
Retrieve one image and its Base64 content using `/hull/files/{fileId}`.
See [hull retrieval](hull-retrieval.md) for all supported read routes.
## Expertise submit completes missing prerequisites
The frontend can call
`POST /v2/fanavaran/{client}/claim-cases/{claimCaseId}/expertise/submit`
without separately retrying earlier stages. The backend completes them in order:
- Third-party: base claim → damage case → pending attachments → expertise.
- Hull: base claim → pending attachments → expertise. Hull has no damage-case stage.
Existing claim/damage IDs and successful image receipts are reused. A previously
skipped attachment stage is retried. Completion is checked against a fresh read
of the saved receipts for all current local image candidates, not just the
attachment stage's status or an upload response saying success. Missing local
files, rejected uploads, and unconfirmed receipts stop expertise submission.
If there are no local attachment candidates, there is nothing to upload.
Errors identify `stage` (`baseClaim`, `damageCase`, or `attachments`) and preserve
vendor details. An attachment failure includes:
```json
{
"statusCode": 400,
"code": "FANAVARAN_ATTACHMENTS_INCOMPLETE",
"stage": "attachments",
"pendingFiles": [
{ "fileName": "image.jpg", "error": "Upload failure reason", "skipped": false }
]
}
```
Retrying resumes pending work. Even when expertise already exists, this API first
repairs missing prerequisites, then returns the existing expertise response/Id
without posting another expertise. Automatic final writes also check attachments.
+16
View File
@@ -25,6 +25,22 @@ expertise on this same claim, supply `?expertiseId=44237`. A missing saved
expertise ID without an explicit override returns 400. File and expertise IDs
must be positive safe integers.
Local validation errors return a stable `code`, a specific Persian message, and
the relevant field/product metadata. They do not collapse to the generic form
validation message:
| Code | Meaning |
|---|---|
| `FANAVARAN_LOCAL_CLAIM_ID_INVALID` | `claimCaseId` must be a local MongoDB ObjectId, not the numeric external claim ID |
| `FANAVARAN_HULL_CLAIM_REQUIRED` | The linked claim resolves to third-party; `actualProduct` and `expectedProduct` identify the mismatch |
| `FANAVARAN_HULL_CLAIM_NOT_SUBMITTED` | No external `claimId` is saved for the local claim |
| `FANAVARAN_HULL_EXPERTISE_ID_MISSING` | No expertise ID is saved and no override was supplied |
| `FANAVARAN_HULL_FILE_ID_INVALID` / `FANAVARAN_HULL_EXPERTISE_ID_INVALID` | The selected external ID is not a positive safe integer |
| `FANAVARAN_CLIENT_INVALID` | The requested tenant is unsupported |
Selecting `parsian` chooses the insurer; it does not change a third-party claim
into a hull claim. These VHUD routes intentionally reject third-party claims.
Every response wraps the unmodified vendor body in `data`, with `clientKey`,
`claimCaseId`, `claimId`, and the selected `fileId` or `expertiseId` when relevant:
@@ -3382,7 +3382,12 @@ export class ClaimRequestManagementService {
actor: { sub: string; role?: string; clientKey?: string; username?: string },
) {
if (!Types.ObjectId.isValid(claimCaseId)) {
throw new BadRequestException('Invalid claim case ID');
throw new BadRequestException({
statusCode: 400,
code: 'FANAVARAN_LOCAL_CLAIM_ID_INVALID',
field: 'claimCaseId',
message: 'شناسه پرونده باید شناسه داخلی ۲۴ کاراکتری باشد؛ کد عددی پرونده فناوران را در این بخش وارد نکنید.',
});
}
const claim = await this.claimCaseDbService.findById(claimCaseId);
if (!claim) throw new NotFoundException('Claim case not found');
@@ -3398,14 +3403,23 @@ export class ClaimRequestManagementService {
} else if (actor.role !== RoleEnum.SUPER_ADMIN) {
assertClaimCaseForTenant(claim, actor);
}
if ((await this.resolveFanavaranClaimProduct(claimCaseId)) !== 'car-body') {
throw new BadRequestException('This endpoint only retrieves vehicle-hull claims');
const product = await this.resolveFanavaranClaimProduct(claimCaseId);
if (product !== 'car-body') {
throw new BadRequestException({
statusCode: 400, code: 'FANAVARAN_HULL_CLAIM_REQUIRED',
actualProduct: product, expectedProduct: 'car-body', claimCaseId,
message: 'این پرونده به‌عنوان بیمه شخص ثالث شناسایی شده است؛ مسیر بازیابی انتخاب‌شده فقط برای پرونده‌های بیمه بدنه است.',
});
}
const claimId = parseFanavaranId(
claim.claimId ?? claim.fanavaranSync?.baseClaim?.claimId,
);
if (claimId == null) {
throw new BadRequestException('No submitted Fanavaran claimId is stored for this claim');
throw new BadRequestException({
statusCode: 400, code: 'FANAVARAN_HULL_CLAIM_NOT_SUBMITTED',
field: 'claimId',
message: 'کد پرونده فناوران در این پرونده ثبت نشده است؛ ابتدا ارسال اولیه پرونده را تکمیل کنید.',
});
}
return {
claimId,
@@ -6107,19 +6121,103 @@ export class ClaimRequestManagementService {
};
}
/** Complete applicable stages in order; do not treat skipped images as done. */
private async completeFanavaranExpertisePrerequisites(
claimCaseId: string,
clientKey: FanavaranClientKey,
auditSource: FanavaranAuditSource,
): Promise<void> {
let stage: 'baseClaim' | 'damageCase' | 'attachments' = 'baseClaim';
try {
await this.ensureFanavaranBaseClaim(claimCaseId, clientKey, auditSource);
const product = await this.resolveFanavaranClaimProduct(claimCaseId);
if (fanavaranHasDamageCaseStage(product)) {
stage = 'damageCase';
await this.ensureFanavaranDamageCase(claimCaseId, clientKey, auditSource);
}
stage = 'attachments';
await this.ensureFanavaranAttachmentsComplete(claimCaseId, clientKey);
} catch (error) {
const exception = toFanavaranHttpException(error);
const body = exception.getResponse();
const details = typeof body === 'object'
? body as Record<string, unknown>
: {};
const messages = {
baseClaim: 'ارسال پرونده اولیه به فناوران تکمیل نشد؛ ارسال کارشناسی متوقف شد.',
damageCase: 'ارسال مرحله خسارت به فناوران تکمیل نشد؛ ارسال کارشناسی متوقف شد.',
attachments: 'ارسال همه تصاویر به فناوران تکمیل نشده است؛ پس از رفع خطای تصاویر، ارسال کارشناسی را دوباره انجام دهید.',
};
throw new HttpException(
{
...details,
statusCode: exception.getStatus(),
code: details.code ?? 'FANAVARAN_PREVIOUS_STAGE_FAILED',
stage,
message: messages[stage],
upstreamMessage: this.extractFanavaranErrorMessage(error),
},
exception.getStatus(),
);
}
}
private async ensureFanavaranAttachmentsComplete(
claimCaseId: string,
clientKey: FanavaranClientKey,
): Promise<void> {
const initial = await this.collectFanavaranAttachmentCandidates(
claimCaseId, clientKey,
);
if (initial.candidates.every(candidate => candidate.alreadySubmitted)) return;
const upload = await this.submitFanavaranAttachmentsV2(
claimCaseId, clientKey,
);
// Re-read saved receipts: a success response or a stage-level status alone is insufficient.
const refreshed = await this.collectFanavaranAttachmentCandidates(
claimCaseId, clientKey,
);
const pending = refreshed.candidates.filter(candidate => !candidate.alreadySubmitted);
if (!pending.length) return;
const results = Array.isArray(upload) ? upload : upload?.results ?? [];
const attempts = fanavaranAttachmentStatus(
refreshed.claimCase.fanavaranSync?.attachments,
)?.attempts ?? [];
throw new BadRequestException({
statusCode: 400,
code: 'FANAVARAN_ATTACHMENTS_INCOMPLETE',
stage: 'attachments',
message: 'ارسال تصاویر به فناوران کامل نشده است.',
pendingFiles: pending.map(candidate => {
const result = results.find((item: { fileName?: string }) => item.fileName === candidate.fileName);
const attempt = attempts.filter(item => item.fileName === candidate.fileName).at(-1);
return {
fileName: candidate.fileName, source: candidate.source,
error: result?.warning ?? result?.skipReason ?? attempt?.error ?? upload?.warning ?? 'No confirmed Fanavaran file ID is stored.',
skipped: result?.skipped ?? (attempt?.status === 'skipped'),
};
}),
});
}
async submitFanavaranExpertiseV2(
claimCaseId: string,
clientKey: FanavaranClientKey,
bodyOverride?: Record<string, unknown>,
): Promise<any> {
try {
await this.ensureFanavaranDamageCase(
await this.completeFanavaranExpertisePrerequisites(
claimCaseId,
clientKey,
FanavaranAuditSource.SUBMIT,
);
const claimCase = await this.claimCaseDbService.findById(claimCaseId);
if (!claimCase) throw new NotFoundException('Claim case not found');
if (claimCase.expertiseId != null) {
return claimCase.fanavaranSync?.expertise?.response ?? { Id: claimCase.expertiseId };
}
const product = await this.resolveFanavaranClaimProduct(claimCaseId);
const built = await this.buildFanavaranExpertisePayload({
claimCase,
@@ -6173,6 +6271,8 @@ export class ClaimRequestManagementService {
'Fanavaran claimId is required before submitting expertise',
);
}
// The automatic path also uses this method; keep the same attachment prerequisite.
await this.ensureFanavaranAttachmentsComplete(claimCaseId, clientKey);
if (claimCase.expertiseId != null) {
this.logger.log(
`[executeFanavaranExpertiseSubmit] Already have expertiseId=${claimCase.expertiseId}; skipping Fanavaran POST`,
@@ -0,0 +1,197 @@
import { ClaimRequestManagementService } from "./claim-request-management.service";
function setup(product = "third-party") {
const service = Object.create(ClaimRequestManagementService.prototype) as any;
const claim: any = {
_id: "claim-1",
fanavaranSync: { attachments: { files: [] } },
};
const events: string[] = [];
service.logger = { log: jest.fn(), warn: jest.fn(), error: jest.fn() };
service.resolveFanavaranClaimProduct = jest.fn().mockResolvedValue(product);
service.claimCaseDbService = {
findById: jest.fn().mockImplementation(async () => claim),
};
service.executeFanavaranV2Submit = jest.fn().mockImplementation(async () => {
events.push("baseClaim");
claim.claimId = 100;
});
service.executeFanavaranDamageCaseSubmit = jest
.fn()
.mockImplementation(async () => {
events.push("damageCase");
claim.dmgCaseId = 200;
});
service.collectFanavaranAttachmentCandidates = jest
.fn()
.mockImplementation(async () => ({
claimCase: claim,
candidates: [
{
fileName: "image.jpg",
source: "capture:angle:front",
path: "/tmp/image.jpg",
alreadySubmitted: claim.fanavaranSync.attachments.files.length > 0,
},
],
}));
service.submitFanavaranAttachmentsV2 = jest
.fn()
.mockImplementation(async () => {
events.push("attachments");
claim.fanavaranSync.attachments.files.push({
fileName: "image.jpg",
fileId: 71,
});
return [{ submitted: true, fileId: 71, fileName: "image.jpg" }];
});
service.buildFanavaranExpertisePayload = jest
.fn()
.mockImplementation(async () => ({
payload: { DmgCaseId: claim.dmgCaseId },
warnings: [],
}));
service.assertFanavaranExpertisePayloadReady = jest.fn();
service.executeFanavaranExpertiseSubmit = jest
.fn()
.mockImplementation(async () => {
events.push("expertise");
claim.expertiseId = 300;
return { Id: 300 };
});
return { service, claim, events };
}
describe("expertise submit completes earlier Fanavaran stages", () => {
it("runs base, damage, attachments, expertise in order for third-party", async () => {
const { service, events } = setup();
await service.submitFanavaranExpertiseV2("claim-1", "parsian");
expect(events).toEqual([
"baseClaim",
"damageCase",
"attachments",
"expertise",
]);
});
it("runs base, attachments, expertise for hull without creating a damage case", async () => {
const { service, events } = setup("car-body");
await service.submitFanavaranExpertiseV2("claim-1", "parsian");
expect(events).toEqual(["baseClaim", "attachments", "expertise"]);
expect(service.executeFanavaranDamageCaseSubmit).not.toHaveBeenCalled();
});
it("retries previously skipped images while reusing existing base/damage IDs", async () => {
const { service, claim, events } = setup();
Object.assign(claim, { claimId: 100, dmgCaseId: 200 });
claim.fanavaranSync.attachments.status = "skipped";
await service.submitFanavaranExpertiseV2("claim-1", "parsian");
expect(events).toEqual(["attachments", "expertise"]);
});
it.each(["failed", "skipped"])(
"does not submit expertise if an image remains %s",
async (status) => {
const { service } = setup();
service.submitFanavaranAttachmentsV2.mockResolvedValue([
{
fileName: "image.jpg",
submitted: false,
skipped: status === "skipped",
warning: "Image unavailable",
},
]);
await expect(
service.submitFanavaranExpertiseV2("claim-1", "parsian"),
).rejects.toMatchObject({
response: expect.objectContaining({
stage: "attachments",
pendingFiles: [expect.objectContaining({ fileName: "image.jpg" })],
}),
});
expect(service.executeFanavaranExpertiseSubmit).not.toHaveBeenCalled();
},
);
it("stops immediately if the base stage fails", async () => {
const { service } = setup();
service.executeFanavaranV2Submit.mockRejectedValue(
new Error("Base unavailable"),
);
await expect(
service.submitFanavaranExpertiseV2("claim-1", "parsian"),
).rejects.toMatchObject({
response: expect.objectContaining({ stage: "baseClaim" }),
});
expect(service.executeFanavaranDamageCaseSubmit).not.toHaveBeenCalled();
expect(service.submitFanavaranAttachmentsV2).not.toHaveBeenCalled();
expect(service.executeFanavaranExpertiseSubmit).not.toHaveBeenCalled();
});
it("stops before images and expertise if the damage stage fails", async () => {
const { service } = setup();
service.executeFanavaranDamageCaseSubmit.mockRejectedValue(
new Error("Damage unavailable"),
);
await expect(
service.submitFanavaranExpertiseV2("claim-1", "parsian"),
).rejects.toMatchObject({
response: expect.objectContaining({ stage: "damageCase" }),
});
expect(service.submitFanavaranAttachmentsV2).not.toHaveBeenCalled();
expect(service.executeFanavaranExpertiseSubmit).not.toHaveBeenCalled();
});
it("requires saved image receipts even if the upload call reports success", async () => {
const { service } = setup();
service.submitFanavaranAttachmentsV2.mockResolvedValue([
{ submitted: true, fileId: 71 },
]);
await expect(
service.submitFanavaranExpertiseV2("claim-1", "parsian"),
).rejects.toMatchObject({
response: expect.objectContaining({ stage: "attachments" }),
});
expect(service.executeFanavaranExpertiseSubmit).not.toHaveBeenCalled();
});
it("also enforces attachments on the shared final write used by automatic submission", async () => {
const { service, claim } = setup("car-body");
claim.claimId = 100;
service.assertFanavaranVehicleReviewApproved = jest.fn();
service.postFanavaranJson = jest.fn();
service.submitFanavaranAttachmentsV2.mockResolvedValue([
{ submitted: false, warning: "Image unavailable" },
]);
const execute = (ClaimRequestManagementService.prototype as any)
.executeFanavaranExpertiseSubmit;
await expect(
execute.call(service, "claim-1", "parsian", {}, "AUTO_SUBMIT"),
).rejects.toMatchObject({
response: expect.objectContaining({ stage: "attachments" }),
});
expect(service.postFanavaranJson).not.toHaveBeenCalled();
});
it("repairs missing attachments even if expertise already exists, without resubmitting expertise", async () => {
const { service, claim, events } = setup();
Object.assign(claim, { claimId: 100, dmgCaseId: 200, expertiseId: 300 });
expect(
await service.submitFanavaranExpertiseV2("claim-1", "parsian"),
).toMatchObject({ Id: 300 });
expect(events).toEqual(["attachments"]);
expect(service.executeFanavaranExpertiseSubmit).not.toHaveBeenCalled();
});
it("does not repeat any completed stage on the next submit call", async () => {
const { service, events } = setup();
await service.submitFanavaranExpertiseV2("claim-1", "parsian");
await service.submitFanavaranExpertiseV2("claim-1", "parsian");
expect(events).toEqual([
"baseClaim",
"damageCase",
"attachments",
"expertise",
]);
});
});
@@ -98,7 +98,13 @@ export class FanavaranHullReadController {
private clientKey(client: string) {
if (!isFanavaranClientKey(client))
throw new BadRequestException("Invalid Fanavaran client");
throw new BadRequestException({
statusCode: 400,
code: "FANAVARAN_CLIENT_INVALID",
field: "client",
allowedClients: FANAVARAN_CLIENT_SWAGGER_ENUM,
message: "شرکت بیمه انتخاب‌شده برای سرویس فناوران معتبر نیست.",
});
return normalizeFanavaranClientKey(client);
}
}
@@ -2,6 +2,7 @@ import { ForbiddenException } from "@nestjs/common";
import { of, throwError } from "rxjs";
import { FanavaranHullReadService } from "./fanavaran-hull-read.service";
import { ClaimRequestManagementService } from "src/claim-request-management/claim-request-management.service";
import { localizeErrorPayload } from "src/common/errors/persian-errors";
const actor = { sub: "staff-1", role: "damage_expert", clientKey: "tenant-1" };
const localId = "6af4594a32d485128a55742d";
@@ -108,7 +109,11 @@ describe("Fanavaran hull retrieval", () => {
});
await expect(
service.damageSections("parsian", localId, actor),
).rejects.toThrow("expertiseId");
).rejects.toMatchObject({
response: expect.objectContaining({
code: "FANAVARAN_HULL_EXPERTISE_ID_MISSING",
}),
});
expect(http.get).not.toHaveBeenCalled();
});
@@ -166,9 +171,7 @@ describe("hull read context", () => {
ClaimRequestManagementService.prototype,
) as any;
service.claimCaseDbService = {
findById: jest
.fn()
.mockResolvedValue({
findById: jest.fn().mockResolvedValue({
claimId: 5190845,
claimNo: 123,
expertiseId: 44237,
@@ -195,6 +198,27 @@ describe("hull read context", () => {
);
});
it("keeps the local/external claim ID distinction visible after the global error filter", async () => {
const service = context();
let error: any;
try {
await service.getFanavaranHullReadContext("5190845", "parsian", actor);
} catch (caught) {
error = caught;
}
expect(error).toBeDefined();
const response = localizeErrorPayload(
error.getResponse(),
error.getStatus(),
);
expect(response).toMatchObject({
code: "FANAVARAN_LOCAL_CLAIM_ID_INVALID",
field: "claimCaseId",
});
expect(response.message).toContain("شناسه داخلی");
expect(service.claimCaseDbService.findById).not.toHaveBeenCalled();
});
it("rejects another organization's claim before retrieving credentials", async () => {
const service = context({ owner: { clientId: "other-tenant" } });
await expect(
@@ -206,9 +230,27 @@ describe("hull read context", () => {
it("rejects third-party claims and claims that only have a claimNo", async () => {
const service = context();
service.resolveFanavaranClaimProduct.mockResolvedValue("third-party");
let wrongProduct: any;
try {
await service.getFanavaranHullReadContext(localId, "parsian", actor);
} catch (error) {
wrongProduct = error;
}
const localized = localizeErrorPayload(wrongProduct.getResponse(), 400);
expect(localized).toMatchObject({
code: "FANAVARAN_HULL_CLAIM_REQUIRED",
actualProduct: "third-party",
expectedProduct: "car-body",
});
expect(localized.message).toContain("شخص ثالث");
await expect(
service.getFanavaranHullReadContext(localId, "parsian", actor),
).rejects.toThrow("vehicle-hull");
).rejects.toMatchObject({
response: expect.objectContaining({
code: "FANAVARAN_HULL_CLAIM_REQUIRED",
actualProduct: "third-party",
}),
});
service.resolveFanavaranClaimProduct.mockResolvedValue("car-body");
service.claimCaseDbService.findById.mockResolvedValue({
claimNo: 123,
@@ -216,6 +258,10 @@ describe("hull read context", () => {
});
await expect(
service.getFanavaranHullReadContext(localId, "parsian", actor),
).rejects.toThrow("claimId");
).rejects.toMatchObject({
response: expect.objectContaining({
code: "FANAVARAN_HULL_CLAIM_NOT_SUBMITTED",
}),
});
});
});
+19 -4
View File
@@ -85,9 +85,13 @@ export class FanavaranHullReadService {
);
const id = selectedId ?? context.expertiseId;
if (id == null)
throw new BadRequestException(
"No submitted expertiseId is stored; provide expertiseId for a previously submitted expertise",
);
throw new BadRequestException({
statusCode: 400,
code: "FANAVARAN_HULL_EXPERTISE_ID_MISSING",
field: "expertiseId",
message:
"کد کارشناسی فناوران در این پرونده ثبت نشده است؛ کد کارشناسی قبلی را در پارامتر مربوط وارد کنید یا ابتدا کارشناسی را ارسال کنید.",
});
const url = `${getFanavaranLookupBaseUrl(clientKey)}/car/vehicle-hull-claims/${context.claimId}/expertise/${id}/dmg-sections`;
return {
clientKey,
@@ -101,7 +105,18 @@ export class FanavaranHullReadService {
private positiveId(value: string, field: string): number {
const id = Number(value);
if (!/^\d+$/.test(value) || !Number.isSafeInteger(id) || id <= 0) {
throw new BadRequestException(`${field} must be a positive integer`);
throw new BadRequestException({
statusCode: 400,
code:
field === "fileId"
? "FANAVARAN_HULL_FILE_ID_INVALID"
: "FANAVARAN_HULL_EXPERTISE_ID_INVALID",
field,
message:
field === "fileId"
? "کد فایل فناوران باید یک عدد صحیح مثبت باشد."
: "کد کارشناسی فناوران باید یک عدد صحیح مثبت باشد.",
});
}
return id;
}
+1 -1
View File
@@ -283,7 +283,7 @@ export class FanavaranController {
@ApiOperation({
summary: "Submit Fanavaran expertise request",
description:
"Swagger JSON body is optional. Always rebuilds GEN.08 from the local expert reply and lookups, then POSTs that rebuilt payload. Pasting a previous preview JSON does not skip rebuild. Only money/date fields are taken from the body. DmgCaseId, ClaimExpertId, and DmgSections in pasted JSON are ignored.",
"Completes missing prerequisite stages in order before expertise: base claim, third-party damage case when applicable, then all pending attachments. Skipped images are retried; any image without a saved Fanavaran file ID blocks expertise with stage and pendingFiles details. Existing IDs/receipts are reused; existing expertise is not duplicated. Optional JSON overrides only allowed money/date fields; the GEN.08 third-party or GEN.06 hull payload is rebuilt from the expert reply and live lookups.",
})
@ApiParam({
name: "client",