From f29461fa67b376700c6ee1f8b5944a1e4a407469 Mon Sep 17 00:00:00 2001 From: SepehrYahyaee <7heycallmegray@gmail.com> Date: Tue, 24 Nov 2026 12:18:39 +0330 Subject: [PATCH] feat(claims): enforce insurer working hours --- docs/insurer-staff-management.md | 9 + src/app.module.ts | 2 + .../claim-request-management.v2.controller.ts | 2 + ...xpert-initiated-claim.mirror.controller.ts | 2 + .../registrar-claim.mirror.controller.ts | 2 + src/client/client.module.ts | 3 + .../entities/db-service/client.db.service.ts | 8 + src/client/entities/schema/client.schema.ts | 4 + .../case-working-hours.interceptor.ts | 120 ++++++++ .../client-working-hours.service.ts | 112 ++++++++ .../working-hours/working-hours.spec.ts | 263 ++++++++++++++++++ src/client/working-hours/working-hours.ts | 151 ++++++++++ src/expert-blame/expert-blame.controller.ts | 2 + src/expert-blame/expert-blame.service.ts | 6 + .../expert-blame.v2.controller.ts | 2 + .../expert-claim.v2.controller.ts | 2 + src/fanavaran/fanavaran.controller.ts | 2 + src/management/management.controller.ts | 29 +- src/management/management.module.ts | 2 + src/management/management.service.spec.ts | 59 +++- .../call-center-blame-v6.controller.ts | 2 + .../entities/schema/blame-cases.schema.ts | 4 + ...rt-initiated-blame-v3.mirror.controller.ts | 2 + ...xpert-initiated-blame.mirror.controller.ts | 2 + .../expert-initiated.controller.ts | 2 + .../expert-initiated.v2.controller.ts | 2 + .../file-maker-blame-v4.controller.ts | 2 + .../file-maker-blame-v5.controller.ts | 2 + ...file-maker-claim-approval-v5.controller.ts | 2 + .../file-reviewer-blame-v4.controller.ts | 2 + .../file-reviewer-blame-v5.controller.ts | 2 + .../registrar-blame.mirror.controller.ts | 2 + .../request-management.service.ts | 30 ++ .../request-management.v2.controller.ts | 2 + test/contracts/api-routes.json | 42 +++ 35 files changed, 879 insertions(+), 3 deletions(-) create mode 100644 src/client/working-hours/case-working-hours.interceptor.ts create mode 100644 src/client/working-hours/client-working-hours.service.ts create mode 100644 src/client/working-hours/working-hours.spec.ts create mode 100644 src/client/working-hours/working-hours.ts diff --git a/docs/insurer-staff-management.md b/docs/insurer-staff-management.md index 5ef31a8..d8abb86 100644 --- a/docs/insurer-staff-management.md +++ b/docs/insurer-staff-management.md @@ -20,6 +20,7 @@ All endpoints require bearer authentication and strictly validate their DTOs. Sw | --- | --- | --- | | List/create insurers | `GET/POST /super-admin/management/clients` | Unavailable | | Edit insurer metadata | `PATCH /super-admin/management/clients/:id` | Unavailable | +| Read or update case working hours | `GET/PATCH /super-admin/management/working-hours?clientId=...` | `GET/PATCH /expert-insurer/management/working-hours` | | List/create insurer login accounts | `GET/POST /super-admin/management/clients/:clientId/accounts` | Unavailable | | Edit insurer login account | `PATCH /super-admin/management/clients/:clientId/accounts/:id` | Unavailable | | List/create staff | `GET/POST /super-admin/management/staff?clientId=...` | `GET/POST /expert-insurer/management/staff` | @@ -30,6 +31,14 @@ All endpoints require bearer authentication and strictly validate their DTOs. Sw Staff list queries accept `search`, `role`, `page` and `limit` (default 20, capped at 100). Responses contain `list`, `total`, `page` and `limit`. Branch responses contain `list`; clients contain `clients`. Account lists share the staff pagination contract. +## Case working hours + +Insurers edit their own hours in **تنظیمات شرکت بیمه** (`/settings`). Super-admins use **ساعات کاری** on the relevant company in `/insurers`. Existing companies default to 24/7. Saving a change applies it immediately to new case submissions, including submissions for existing cases. + +Schedules use Tehran time and allow one opening window per weekday. Omitted days are closed. For an overnight shift, enter an end time earlier than the start. The API numbers weekdays from Sunday (`0`) through Saturday (`6`) and accepts `24:00` as the end of a day. For example, `{"alwaysOpen":false,"windows":[{"weekday":6,"opensAt":"08:00","closesAt":"16:00"}]}` opens Saturday from 08:00 inclusive to 16:00 exclusive. Enable `alwaysOpen` to allow access around the clock. + +Case creation and updates use the liable insurer's hours once it is identified. At intake, staff use their own insurer's hours. For public intake before the case insurer is known, set the API's existing `CLIENT_ID` to the deployment insurer's numeric client code. If an intake has no known insurer and the deployment has no configured insurer, the schedule applies once the insurer is identified. Case reads, login and schedule settings are available outside those hours. Blocked case updates return HTTP 403 with `OUTSIDE_WORKING_HOURS` and the next opening. + ## Fields `role` is one of `expert`, `damage_expert`, `field_expert`, `file_maker`, `file_reviewer`, or `call_center`, and is selected only during creation. These use the existing collections and actor login mechanism. diff --git a/src/app.module.ts b/src/app.module.ts index 9d958b9..f79acab 100644 --- a/src/app.module.ts +++ b/src/app.module.ts @@ -1,3 +1,4 @@ +import { CaseWorkingHoursInterceptor } from "./client/working-hours/case-working-hours.interceptor"; import { EvidenceAccessModule } from "./evidence-access/evidence-access.module"; import { PersianErrorFilter } from "./common/errors/persian-error.filter"; import { PersianErrorInterceptor } from "./common/errors/persian-error.interceptor"; @@ -68,6 +69,7 @@ import { createHttpModuleOptions } from "./core/config/http-proxy.factory"; providers: [ { provide: APP_FILTER, useClass: PersianErrorFilter }, { provide: APP_INTERCEPTOR, useClass: PersianErrorInterceptor }, + { provide: APP_INTERCEPTOR, useClass: CaseWorkingHoursInterceptor }, { provide: APP_INTERCEPTOR, useClass: UnicodeDigitsNormalizeInterceptor, diff --git a/src/claim-request-management/claim-request-management.v2.controller.ts b/src/claim-request-management/claim-request-management.v2.controller.ts index 72e3383..7bf810e 100644 --- a/src/claim-request-management/claim-request-management.v2.controller.ts +++ b/src/claim-request-management/claim-request-management.v2.controller.ts @@ -1,3 +1,4 @@ +import { EnforceCaseWorkingHours } from "src/client/working-hours/case-working-hours.interceptor"; import { randomUUID } from "node:crypto"; import { Controller, @@ -64,6 +65,7 @@ import { UserObjectionV2Dto } from "./dto/user-objection-v2.dto"; import { UserRatingDto } from "./dto/user-rating.dto"; @ApiTags("claim-request-management (v2)") +@EnforceCaseWorkingHours() @Controller("v2/claim-request-management") @ApiBearerAuth() @UseGuards(GlobalGuard, RolesGuard) diff --git a/src/claim-request-management/expert-initiated-claim.mirror.controller.ts b/src/claim-request-management/expert-initiated-claim.mirror.controller.ts index bb39ad2..704250c 100644 --- a/src/claim-request-management/expert-initiated-claim.mirror.controller.ts +++ b/src/claim-request-management/expert-initiated-claim.mirror.controller.ts @@ -1,3 +1,4 @@ +import { EnforceCaseWorkingHours } from "src/client/working-hours/case-working-hours.interceptor"; import { randomUUID } from "node:crypto"; import { readFile } from "node:fs/promises"; import { extname } from "node:path"; @@ -68,6 +69,7 @@ import { Role } from "src/common/auth/enums"; * from their own account through the normal user endpoints. */ @ApiTags("expert-initiated claim (mirror v2)") +@EnforceCaseWorkingHours() @Controller("v2/expert-initiated/claim-request-management") @ApiBearerAuth() @UseGuards(LocalActorAuthGuard, RolesGuard) diff --git a/src/claim-request-management/registrar-claim.mirror.controller.ts b/src/claim-request-management/registrar-claim.mirror.controller.ts index 2b87120..f4c3581 100644 --- a/src/claim-request-management/registrar-claim.mirror.controller.ts +++ b/src/claim-request-management/registrar-claim.mirror.controller.ts @@ -1,3 +1,4 @@ +import { EnforceCaseWorkingHours } from "src/client/working-hours/case-working-hours.interceptor"; import { readFile } from "node:fs/promises"; import { extname } from "node:path"; import { @@ -63,6 +64,7 @@ import { GetCaptureRequirementsV2ResponseDto } from "./dto/capture-requirements- * The registrar's job ends here — no reviewing panel is needed. */ @ApiTags("registrar claim (mirror v2)") +@EnforceCaseWorkingHours() @Controller("v2/registrar/claim-request-management") @ApiBearerAuth() @UseGuards(LocalActorAuthGuard, RolesGuard) diff --git a/src/client/client.module.ts b/src/client/client.module.ts index 5a974aa..5de8c4a 100644 --- a/src/client/client.module.ts +++ b/src/client/client.module.ts @@ -1,3 +1,4 @@ +import { ClientWorkingHoursService } from "./working-hours/client-working-hours.service"; import { UserClaimBranchService } from "./user-claim-branch.service"; import { Module } from "@nestjs/common"; import { MongooseModule } from "@nestjs/mongoose"; @@ -34,6 +35,7 @@ import { ClientDbSchema, ClientModel } from "./entities/schema/client.schema"; ClientDbService, BranchDbService, ExternalInquirySettingsService, + ClientWorkingHoursService, ], exports: [ UserClaimBranchService, @@ -41,6 +43,7 @@ import { ClientDbSchema, ClientModel } from "./entities/schema/client.schema"; ClientDbService, BranchDbService, ExternalInquirySettingsService, + ClientWorkingHoursService, ], }) export class ClientModule {} diff --git a/src/client/entities/db-service/client.db.service.ts b/src/client/entities/db-service/client.db.service.ts index 5276d7a..dbcf599 100644 --- a/src/client/entities/db-service/client.db.service.ts +++ b/src/client/entities/db-service/client.db.service.ts @@ -56,6 +56,14 @@ export class ClientDbService implements OnModuleInit { return this.clientModel.findOne(client); } + async findWorkingHours(filter: FilterQuery) { + return this.clientModel + .findOne(filter) + .select("settings.workingHours") + .lean() + .exec(); + } + async findAll(): Promise { return await this.clientModel.find(); } diff --git a/src/client/entities/schema/client.schema.ts b/src/client/entities/schema/client.schema.ts index ec79296..99df83c 100644 --- a/src/client/entities/schema/client.schema.ts +++ b/src/client/entities/schema/client.schema.ts @@ -1,4 +1,5 @@ import { Prop, Schema, SchemaFactory } from "@nestjs/mongoose"; +import type { WorkingHours } from "src/client/working-hours/working-hours"; import type { ExternalInquiryFlags } from "src/common/types/external-inquiry.types"; export type ClientDocument = ClientModel & Document; @@ -68,6 +69,9 @@ export class ClientExternalInquirySettings implements Partial + SetMetadata(CASE_WRITES, options); +const WRITE_METHODS = new Set(["POST", "PUT", "PATCH", "DELETE"]); +const caseScheduleScope = new AsyncLocalStorage< + (clientId: string) => Promise +>(); + +// An intake inquiry can identify a different insurer before the case is saved. +export async function checkDiscoveredCaseInsurer(value: unknown) { + const clientId = workingHoursClientId(value); + if (clientId) await caseScheduleScope.getStore()?.(clientId); +} + +export function checkDiscoveredBlameInsurer( + blame: Parameters[0], +) { + return checkDiscoveredCaseInsurer(responsibleBlameInsurer(blame)); +} + +@Injectable() +export class CaseWorkingHoursInterceptor implements NestInterceptor { + constructor( + private readonly reflector: Reflector, + private readonly hours: ClientWorkingHoursService, + private readonly claims: ClaimCaseDbService, + private readonly blames: BlameRequestDbService, + ) {} + + async intercept(context: ExecutionContext, next: CallHandler) { + const rule = this.reflector.getAllAndOverride( + CASE_WRITES, + [context.getHandler(), context.getClass()], + ); + const req = context.switchToHttp().getRequest(); + if (!rule || !req.user?.sub || !WRITE_METHODS.has(req.method)) + return next.handle(); + + const now = new Date(); + const scope = await this.resolveScope(req.params ?? {}, rule); + if (!scope) return next.handle(); // Keep existing invalid/missing case responses. + const checked = new Set(); + const check = async (clientId?: string) => { + if (checked.has(clientId)) return; + await this.hours.assertOpen(clientId, now); + checked.add(clientId); + }; + await check(scope.clientId ?? actorWorkingHoursClientId(req.user)); + + // Subscribe inside the scope so asynchronous handlers and multipart processing inherit it. + return new Observable((subscriber) => + caseScheduleScope.run(check, () => next.handle().subscribe(subscriber)), + ); + } + + private async resolveScope( + params: Record, + rule: CaseWriteOptions, + ) { + const claimId = params.claimRequestId ?? params.claimCaseId; + let blameId = + params.blameRequestId ?? + params.requestId ?? + (rule.genericId === "blame" ? params.id : undefined); + if (claimId) { + if (!workingHoursClientId(claimId)) return null; + const [claim] = (await this.claims.find( + { _id: new Types.ObjectId(claimId) }, + { + lean: true, + select: "owner.clientId owner.userClientKey blameRequestId", + }, + )) as Record[]; + if (!claim) return null; + const tenant = + workingHoursClientId(claim.owner?.clientId) ?? + workingHoursClientId(claim.owner?.userClientKey); + if (tenant) return { clientId: tenant }; + blameId = claim.blameRequestId ? String(claim.blameRequestId) : undefined; + } + + if (!blameId) return {}; + if (!workingHoursClientId(blameId)) return null; + const [blame] = await this.blames.find( + { _id: new Types.ObjectId(blameId) }, + { + lean: true, + select: + "type blameStatus parties.role parties.person.clientId parties.person.userId parties.statement expert.decision.guiltyPartyId callCenterInitiated workingHoursIntakeClientId", + }, + ); + if (!blame) return claimId ? {} : null; + return { + clientId: + responsibleBlameInsurer(blame) ?? + workingHoursClientId(blame.workingHoursIntakeClientId), + }; + } +} diff --git a/src/client/working-hours/client-working-hours.service.ts b/src/client/working-hours/client-working-hours.service.ts new file mode 100644 index 0000000..1ea5aee --- /dev/null +++ b/src/client/working-hours/client-working-hours.service.ts @@ -0,0 +1,112 @@ +import { + BadRequestException, + ForbiddenException, + Injectable, + NotFoundException, +} from "@nestjs/common"; +import { RoleEnum } from "src/Types&Enums/role.enum"; +import { resolveGuiltyPartyClientId } from "src/helpers/tenant-scope"; +import { ClientDbService } from "../entities/db-service/client.db.service"; +import { + defaultWorkingHours, + getNextOpening, + parseWorkingHours, + workingHoursMessage, +} from "./working-hours"; + +export function workingHoursClientId(value: unknown): string | undefined { + const id = String(value ?? ""); + return /^[a-f\d]{24}$/i.test(id) ? id.toLowerCase() : undefined; +} + +export function actorWorkingHoursClientId(actor: { + role?: string; + clientKey?: unknown; +}) { + // The public user's JWT clientKey is not their insurer. + return actor?.role && actor.role !== RoleEnum.USER + ? workingHoursClientId(actor.clientKey) + : undefined; +} + +type CaseParties = { + type?: unknown; + blameStatus?: unknown; + expert?: { decision?: { guiltyPartyId?: unknown } }; + callCenterInitiated?: unknown; + parties?: Array<{ + role?: string; + person?: { clientId?: unknown; userId?: unknown }; + statement?: { admitsGuilt?: boolean; claimsDamage?: boolean }; + }>; +}; + +export function responsibleBlameInsurer(blame: CaseParties | null | undefined) { + if (!blame) return undefined; + const first = blame.parties?.find((party) => party.role === "FIRST"); + if (blame.type === "CAR_BODY") + return workingHoursClientId(first?.person?.clientId); + if ( + blame.expert?.decision?.guiltyPartyId || + blame.parties?.some((party) => party.statement?.admitsGuilt) + ) { + return workingHoursClientId(resolveGuiltyPartyClientId(blame)); + } + // AGREED can mean that the first party reported being the injured party. + if (blame.blameStatus === "AGREED" && first?.statement?.claimsDamage) { + const second = blame.parties?.find((party) => party.role === "SECOND"); + return workingHoursClientId(second?.person?.clientId); + } + return blame.blameStatus === "AGREED" || blame.callCenterInitiated + ? workingHoursClientId(first?.person?.clientId) + : undefined; +} + +@Injectable() +export class ClientWorkingHoursService { + constructor(private readonly clients: ClientDbService) {} + + async read(clientId: string) { + const id = this.requireClientId(clientId); + const client = await this.clients.findWorkingHours({ _id: id }); + if (!client) throw new NotFoundException("شرکت بیمه یافت نشد."); + return client.settings?.workingHours ?? defaultWorkingHours(); + } + + async update(clientId: string, body: unknown) { + const id = this.requireClientId(clientId); + const schedule = parseWorkingHours(body); + const updated = await this.clients.findByIdAndUpdate(id, { + $set: { "settings.workingHours": schedule }, + }); + if (!updated) throw new NotFoundException("شرکت بیمه یافت نشد."); + return schedule; + } + + async assertOpen(clientId: string | undefined, now: Date) { + const deploymentCode = process.env.CLIENT_ID?.trim(); + const filter = clientId + ? { _id: clientId } + : deploymentCode && /^\d+$/.test(deploymentCode) + ? { clientCode: Number(deploymentCode) } + : null; + if (!filter) return; + + const client = await this.clients.findWorkingHours(filter); + const policy = client?.settings?.workingHours; + if (!policy) return; + const nextOpening = getNextOpening(policy, now); + if (nextOpening === null) return; + throw new ForbiddenException({ + code: "OUTSIDE_WORKING_HOURS", + message: workingHoursMessage(nextOpening), + ...(nextOpening ? { nextOpening } : {}), + }); + } + + private requireClientId(value: unknown) { + const id = workingHoursClientId(value); + if (!id) throw new BadRequestException("شرکت بیمه معتبر نیست."); + return id; + } +} diff --git a/src/client/working-hours/working-hours.spec.ts b/src/client/working-hours/working-hours.spec.ts new file mode 100644 index 0000000..5995c28 --- /dev/null +++ b/src/client/working-hours/working-hours.spec.ts @@ -0,0 +1,263 @@ +import { ForbiddenException } from "@nestjs/common"; +import { Reflector } from "@nestjs/core"; +import { ExecutionContextHost } from "@nestjs/core/helpers/execution-context-host"; +import { lastValueFrom, defer, of } from "rxjs"; +import { RoleEnum } from "src/Types&Enums/role.enum"; +import { + CaseWorkingHoursInterceptor, + checkDiscoveredBlameInsurer, + EnforceCaseWorkingHours, +} from "./case-working-hours.interceptor"; +import { + ClientWorkingHoursService, + responsibleBlameInsurer, +} from "./client-working-hours.service"; +import { getNextOpening, parseWorkingHours } from "./working-hours"; + +const open = { alwaysOpen: true, windows: [] }; +const saturday = { weekday: 6, opensAt: "08:00", closesAt: "16:00" }; +const schedule = { alwaysOpen: false, windows: [saturday] }; +const afterClosing = new Date("2026-11-21T12:30:00Z"); + +describe("Tehran working hours", () => { + it("includes the opening minute, excludes closing, and reports the next open day", () => { + expect(getNextOpening(open, afterClosing)).toBeNull(); + expect(getNextOpening(schedule, new Date("2026-11-21T04:29:59Z"))).toEqual({ + weekday: 6, + time: "08:00", + }); + expect( + getNextOpening(schedule, new Date("2026-11-21T04:30:00Z")), + ).toBeNull(); + expect( + getNextOpening(schedule, new Date("2026-11-21T12:29:59Z")), + ).toBeNull(); + expect(getNextOpening(schedule, afterClosing)).toEqual({ + weekday: 6, + time: "08:00", + }); + }); + + it("handles the overnight week boundary and a day ending at midnight", () => { + const overnight = { + alwaysOpen: false, + windows: [{ weekday: 6, opensAt: "23:00", closesAt: "02:00" }], + }; + expect(getNextOpening(overnight, new Date("2026-11-21T19:29:59Z"))).toEqual( + { weekday: 6, time: "23:00" }, + ); + expect( + getNextOpening(overnight, new Date("2026-11-21T21:30:00Z")), + ).toBeNull(); + expect(getNextOpening(overnight, new Date("2026-11-21T22:30:00Z"))).toEqual( + { weekday: 6, time: "23:00" }, + ); + const allSaturday = parseWorkingHours({ + alwaysOpen: false, + windows: [{ weekday: 6, opensAt: "00:00", closesAt: "24:00" }], + }); + expect( + getNextOpening(allSaturday, new Date("2026-11-21T20:29:59Z")), + ).toBeNull(); + expect( + getNextOpening(allSaturday, new Date("2026-11-21T20:30:00Z")), + ).toEqual({ weekday: 6, time: "00:00" }); + }); + + it("rejects duplicate, invalid, and empty restricted schedules", () => { + for (const value of [ + { alwaysOpen: false, windows: [] }, + { ...schedule, windows: [saturday, saturday] }, + { ...schedule, windows: [{ ...saturday, weekday: 7 }] }, + { ...schedule, windows: [{ ...saturday, opensAt: "24:00" }] }, + { ...schedule, windows: [{ ...saturday, closesAt: "08:00" }] }, + { ...schedule, windows: [{ ...saturday, closesAt: "25:00" }] }, + { ...schedule, clientId: "another insurer" }, + ]) { + expect(() => parseWorkingHours(value)).toThrow(); + } + }); +}); + +@EnforceCaseWorkingHours() +class CaseController { + write() {} +} + +const first = "aaaaaaaaaaaaaaaaaaaaaaaa"; +const second = "bbbbbbbbbbbbbbbbbbbbbbbb"; +const caseId = "cccccccccccccccccccccccc"; + +function context( + params: Record = {}, + role = RoleEnum.USER, + method = "POST", +) { + const req = { method, params, user: { sub: "user", role, clientKey: first } }; + return new ExecutionContextHost( + [req], + CaseController, + CaseController.prototype.write, + ); +} + +describe("case working-hours enforcement", () => { + const findWorkingHours = jest.fn(); + const findByIdAndUpdate = jest.fn(); + const hours = new ClientWorkingHoursService({ + findWorkingHours, + findByIdAndUpdate, + } as any); + const assertOpen = jest.spyOn(hours, "assertOpen"); + const claims = { find: jest.fn() }; + const blames = { find: jest.fn() }; + const interceptor = new CaseWorkingHoursInterceptor( + new Reflector(), + hours, + claims as any, + blames as any, + ); + let deployment: string | undefined; + + beforeEach(() => { + jest.clearAllMocks(); + deployment = process.env.CLIENT_ID; + jest.useFakeTimers({ now: afterClosing }); + findWorkingHours.mockImplementation(async (filter) => + filter._id === first + ? { settings: {} } + : { settings: { workingHours: schedule } }, + ); + }); + + afterEach(() => { + if (deployment === undefined) delete process.env.CLIENT_ID; + else process.env.CLIENT_ID = deployment; + jest.useRealTimers(); + }); + + it("uses the second party's insurer when the first party reports being injured", () => { + const injured = { + role: "FIRST", + person: { clientId: first }, + statement: { claimsDamage: true }, + }; + const atFault = { role: "SECOND", person: { clientId: second } }; + expect( + responsibleBlameInsurer({ + type: "THIRD_PARTY", + blameStatus: "AGREED", + parties: [injured], + }), + ).toBeUndefined(); + expect( + responsibleBlameInsurer({ + type: "THIRD_PARTY", + blameStatus: "AGREED", + parties: [injured, atFault], + }), + ).toBe(second); + }); + + it("blocks public intake using the deployment insurer instead of the public JWT key", async () => { + process.env.CLIENT_ID = "8"; + const handle = jest.fn(() => of(true)); + await expect( + interceptor.intercept(context(), { handle }), + ).rejects.toMatchObject({ + status: 403, + response: { + code: "OUTSIDE_WORKING_HOURS", + nextOpening: { weekday: 6, time: "08:00" }, + }, + }); + expect(findWorkingHours).toHaveBeenCalledWith({ clientCode: 8 }); + expect(handle).not.toHaveBeenCalled(); + }); + + it("uses a case's payer over the actor's insurer, including Fanavaran writes", async () => { + claims.find.mockResolvedValue([{ owner: { clientId: second } }]); + const handle = jest.fn(() => of(true)); + await expect( + interceptor.intercept( + context({ claimCaseId: caseId }, RoleEnum.DAMAGE_EXPERT), + { handle }, + ), + ).rejects.toBeInstanceOf(ForbiddenException); + expect(findWorkingHours).toHaveBeenCalledWith({ _id: second }); + expect(handle).not.toHaveBeenCalled(); + }); + + it("uses the initiating insurer for a call-center case before policy details are known", async () => { + blames.find.mockResolvedValue([ + { type: "CAR_BODY", workingHoursIntakeClientId: second }, + ]); + await expect( + interceptor.intercept(context({ requestId: caseId }), { + handle: () => of(true), + }), + ).rejects.toBeInstanceOf(ForbiddenException); + expect(findWorkingHours).toHaveBeenCalledWith({ _id: second }); + }); + + it("checks a newly discovered payer inside the handler before it persists a transition", async () => { + const save = jest.fn(); + const result = await interceptor.intercept( + context({}, RoleEnum.FIELD_EXPERT), + { + handle: () => + defer(async () => { + await checkDiscoveredBlameInsurer({ + type: "THIRD_PARTY", + parties: [ + { role: "FIRST", person: { clientId: first } }, + { + role: "SECOND", + person: { clientId: second }, + statement: { admitsGuilt: true }, + }, + ], + }); + save(); + }), + }, + ); + await expect(lastValueFrom(result)).rejects.toBeInstanceOf( + ForbiddenException, + ); + expect(assertOpen).toHaveBeenNthCalledWith(1, first, afterClosing); + expect(assertOpen).toHaveBeenNthCalledWith(2, second, afterClosing); + expect(save).not.toHaveBeenCalled(); + }); + + it("defaults old insurers to always open and updates only the schedule", async () => { + expect(await hours.read(first)).toEqual(open); + findByIdAndUpdate.mockResolvedValueOnce({ + settings: { workingHours: schedule }, + }); + expect(await hours.update(first, schedule)).toEqual(schedule); + expect(findByIdAndUpdate).toHaveBeenCalledWith(first, { + $set: { "settings.workingHours": schedule }, + }); + }); + + it("leaves reads and the existing missing-case error path alone", async () => { + blames.find.mockResolvedValue([]); + const read = await interceptor.intercept( + context({ requestId: caseId }, RoleEnum.USER, "GET"), + { + handle: () => of("read"), + }, + ); + expect(await lastValueFrom(read)).toBe("read"); + expect(blames.find).not.toHaveBeenCalled(); + const missing = await interceptor.intercept( + context({ requestId: caseId }), + { + handle: () => of("existing not found handling"), + }, + ); + expect(await lastValueFrom(missing)).toBe("existing not found handling"); + expect(assertOpen).not.toHaveBeenCalled(); + }); +}); diff --git a/src/client/working-hours/working-hours.ts b/src/client/working-hours/working-hours.ts new file mode 100644 index 0000000..01ffb97 --- /dev/null +++ b/src/client/working-hours/working-hours.ts @@ -0,0 +1,151 @@ +import { BadRequestException } from "@nestjs/common"; + +export const WORKING_HOURS_TIMEZONE = "Asia/Tehran"; +const DAYS = [ + "یکشنبه", + "دوشنبه", + "سه‌شنبه", + "چهارشنبه", + "پنجشنبه", + "جمعه", + "شنبه", +]; +const WEEKDAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; +const DAY = 1440; +const WEEK = 7 * DAY; +const timeFormat = new Intl.DateTimeFormat("en-GB", { + timeZone: WORKING_HOURS_TIMEZONE, + weekday: "short", + hour: "2-digit", + minute: "2-digit", + hourCycle: "h23", +}); +const timePattern = /^([01]\d|2[0-3]):[0-5]\d$/; + +export type WorkingHoursWindow = { + weekday: number; + opensAt: string; + closesAt: string; +}; +export type WorkingHours = { + alwaysOpen: boolean; + windows: WorkingHoursWindow[]; +}; +export const defaultWorkingHours = (): WorkingHours => ({ + alwaysOpen: true, + windows: [], +}); + +function isRecord(value: unknown): value is Record { + return !!value && typeof value === "object" && !Array.isArray(value); +} + +export function parseWorkingHours(value: unknown): WorkingHours { + if ( + !isRecord(value) || + Object.keys(value).some( + (key) => !["alwaysOpen", "windows"].includes(key), + ) || + typeof value.alwaysOpen !== "boolean" || + !Array.isArray(value.windows) || + value.windows.length > 7 + ) { + throw new BadRequestException("برنامه ساعات کاری معتبر نیست."); + } + + const days = new Set(); + const windows = value.windows.map((window: unknown) => { + if ( + !isRecord(window) || + Object.keys(window).some( + (key) => !["weekday", "opensAt", "closesAt"].includes(key), + ) + ) { + throw new BadRequestException("برنامه روز کاری معتبر نیست."); + } + const { weekday, opensAt, closesAt } = window; + if ( + typeof weekday !== "number" || + !Number.isInteger(weekday) || + weekday < 0 || + weekday > 6 || + days.has(weekday) + ) { + throw new BadRequestException( + "برای هر روز هفته فقط یک بازه کاری تعریف کنید.", + ); + } + if ( + typeof opensAt !== "string" || + !timePattern.test(opensAt) || + typeof closesAt !== "string" || + !(timePattern.test(closesAt) || closesAt === "24:00") || + opensAt === closesAt + ) { + throw new BadRequestException( + `ساعت شروع و پایان روز ${DAYS[weekday]} را به‌درستی وارد کنید.`, + ); + } + days.add(weekday); + return { weekday, opensAt, closesAt }; + }); + if (!value.alwaysOpen && windows.length === 0) { + throw new BadRequestException( + "حداقل یک روز کاری انتخاب کنید یا دسترسی شبانه‌روزی را فعال کنید.", + ); + } + return { + alwaysOpen: value.alwaysOpen, + windows: windows.sort((a, b) => a.weekday - b.weekday), + }; +} + +function minutes(time: string) { + const [hour, minute] = time.split(":").map(Number); + return hour * 60 + minute; +} + +/** Null means open. The opening minute is included and the closing minute is excluded. */ +export function getNextOpening(policy: WorkingHours, now: Date) { + if (policy.alwaysOpen) return null; + const parts = Object.fromEntries( + timeFormat.formatToParts(now).map(({ type, value }) => [type, value]), + ); + const weekday = WEEKDAYS.indexOf(parts.weekday); + const current = + weekday * DAY + Number(parts.hour) * 60 + Number(parts.minute); + const spans = policy.windows.map((window) => { + const open = minutes(window.opensAt); + const close = minutes(window.closesAt); + return { + start: window.weekday * DAY + open, + duration: close > open ? close - open : DAY + close - open, + window, + }; + }); + if ( + spans.some((span) => (current - span.start + WEEK) % WEEK < span.duration) + ) + return null; + + const next = spans.reduce<(typeof spans)[number] | undefined>( + (earliest, span) => { + const delay = (span.start - current + WEEK) % WEEK; + return !earliest || delay < (earliest.start - current + WEEK) % WEEK + ? span + : earliest; + }, + undefined, + ); + return next + ? { weekday: next.window.weekday, time: next.window.opensAt } + : undefined; +} + +export function workingHoursMessage(next: ReturnType) { + const message = + "ثبت و ادامه پرونده فقط در ساعات کاری شرکت بیمه امکان‌پذیر است."; + if (!next) return message; + const time = next.time.replace(/\d/g, (digit) => "۰۱۲۳۴۵۶۷۸۹"[Number(digit)]); + return `${message} شروع بعدی: ${DAYS[next.weekday]} ساعت ${time} به وقت تهران.`; +} diff --git a/src/expert-blame/expert-blame.controller.ts b/src/expert-blame/expert-blame.controller.ts index 168c772..db513fc 100644 --- a/src/expert-blame/expert-blame.controller.ts +++ b/src/expert-blame/expert-blame.controller.ts @@ -1,3 +1,4 @@ +import { EnforceCaseWorkingHours } from "src/client/working-hours/case-working-hours.interceptor"; import { Controller, Get, @@ -38,6 +39,7 @@ import { ExpertBlameService } from "./expert-blame.service"; @ApiExcludeController() // @ApiTags("expert-blame-panel") +@EnforceCaseWorkingHours() @Controller("expert-blame") @ApiBearerAuth() @UseGuards(LocalActorAuthGuard, RolesGuard) diff --git a/src/expert-blame/expert-blame.service.ts b/src/expert-blame/expert-blame.service.ts index 068d4b0..4de9555 100644 --- a/src/expert-blame/expert-blame.service.ts +++ b/src/expert-blame/expert-blame.service.ts @@ -1,3 +1,4 @@ +import { checkDiscoveredBlameInsurer } from "src/client/working-hours/case-working-hours.interceptor"; import { BadRequestException, ConflictException, @@ -2034,6 +2035,11 @@ export class ExpertBlameService { }, }; + await checkDiscoveredBlameInsurer({ + type: request.type, + parties: request.parties, + expert: { decision: decisionPayload }, + }); const updatePayload = { $set: { "workflow.locked": false, diff --git a/src/expert-blame/expert-blame.v2.controller.ts b/src/expert-blame/expert-blame.v2.controller.ts index c0bd256..a830b4d 100644 --- a/src/expert-blame/expert-blame.v2.controller.ts +++ b/src/expert-blame/expert-blame.v2.controller.ts @@ -1,3 +1,4 @@ +import { EnforceCaseWorkingHours } from "src/client/working-hours/case-working-hours.interceptor"; import { Body, Controller, @@ -35,6 +36,7 @@ import { SubmitReplyDto } from "./dto/reply.dto"; import { ResendRequestDto } from "./dto/resend.dto"; @ApiTags("expert-blame-panel (v2)") +@EnforceCaseWorkingHours({ genericId: "blame" }) @Controller("v2/expert-blame") @ApiBearerAuth() @UseGuards(LocalActorAuthGuard, RolesGuard) diff --git a/src/expert-claim/expert-claim.v2.controller.ts b/src/expert-claim/expert-claim.v2.controller.ts index 34eb343..c4c09c2 100644 --- a/src/expert-claim/expert-claim.v2.controller.ts +++ b/src/expert-claim/expert-claim.v2.controller.ts @@ -1,3 +1,4 @@ +import { EnforceCaseWorkingHours } from "src/client/working-hours/case-working-hours.interceptor"; import { AiPricingRequestDto } from "src/ai/ai-pricing-request.dto"; import { ValidationPipe } from "@nestjs/common"; import { AiService } from "src/ai/ai.service"; @@ -68,6 +69,7 @@ class InPersonVisitV2Dto { } @ApiTags("expert-claim-panel (v2)") +@EnforceCaseWorkingHours() @Controller("v2/expert-claim") @ApiBearerAuth() @UseGuards(LocalActorAuthGuard, RolesGuard) diff --git a/src/fanavaran/fanavaran.controller.ts b/src/fanavaran/fanavaran.controller.ts index 3b29b8a..f94b69d 100644 --- a/src/fanavaran/fanavaran.controller.ts +++ b/src/fanavaran/fanavaran.controller.ts @@ -1,3 +1,4 @@ +import { EnforceCaseWorkingHours } from "src/client/working-hours/case-working-hours.interceptor"; import { BadRequestException, Body, @@ -32,6 +33,7 @@ import { } from "src/core/config/fanavaran-client.config"; @ApiTags("fanavaran") +@EnforceCaseWorkingHours() @Controller("v2/fanavaran") @ApiBearerAuth() @UseGuards(LocalActorAuthGuard) diff --git a/src/management/management.controller.ts b/src/management/management.controller.ts index fcc20c4..3a4a824 100644 --- a/src/management/management.controller.ts +++ b/src/management/management.controller.ts @@ -1,3 +1,4 @@ +import { ClientWorkingHoursService } from "src/client/working-hours/client-working-hours.service"; import { Body, Controller, @@ -42,7 +43,19 @@ const validation = new ValidationPipe({ @UsePipes(validation) @Controller("super-admin/management") export class SuperAdminManagementController { - constructor(private management: ManagementService) {} + constructor( + private management: ManagementService, + private readonly workingHours: ClientWorkingHoursService, + ) {} + @Get("working-hours") + readHours(@Query("clientId") clientId: string) { + return this.workingHours.read(clientId); + } + @Patch("working-hours") + updateHours(@Query("clientId") clientId: string, @Body() body: unknown) { + return this.workingHours.update(clientId, body); + } + @Get("clients") clients() { return this.management.listClients(); } @@ -129,7 +142,19 @@ export class SuperAdminManagementController { @UsePipes(validation) @Controller("expert-insurer/management") export class InsurerManagementController { - constructor(private management: ManagementService) {} + constructor( + private management: ManagementService, + private readonly workingHours: ClientWorkingHoursService, + ) {} + @Get("working-hours") + readHours(@CurrentUser() actor: { clientKey: string }) { + return this.workingHours.read(actor.clientKey); + } + @Patch("working-hours") + updateHours(@CurrentUser() actor: { clientKey: string }, @Body() body: unknown) { + return this.workingHours.update(actor.clientKey, body); + } + @Get("staff") staff( @CurrentUser() actor, @Query() query: ManagedListQueryDto, diff --git a/src/management/management.module.ts b/src/management/management.module.ts index 99e08b3..659bf40 100644 --- a/src/management/management.module.ts +++ b/src/management/management.module.ts @@ -1,3 +1,4 @@ +import { ClientModule } from "src/client/client.module"; import { Module } from "@nestjs/common"; import { MongooseModule } from "@nestjs/mongoose"; import { AuthModule } from "src/auth/auth.module"; @@ -47,6 +48,7 @@ import { @Module({ imports: [ AuthModule, + ClientModule, HashModule, MongooseModule.forFeature([ { name: ClientModel.name, schema: ClientDbSchema }, diff --git a/src/management/management.service.spec.ts b/src/management/management.service.spec.ts index 8b257d5..ba87287 100644 --- a/src/management/management.service.spec.ts +++ b/src/management/management.service.spec.ts @@ -28,6 +28,7 @@ import { SetManagedStaffActiveDto, } from "./management.dto"; import { ClientDbSchema } from "src/client/entities/schema/client.schema"; +import { ClientWorkingHoursService } from "src/client/working-hours/client-working-hours.service"; import { BranchSchema } from "src/client/entities/schema/branch.schema"; import { ExpertDbSchema } from "src/users/entities/schema/expert.schema"; import { DamageExpertDbSchema } from "src/users/entities/schema/damage-expert.schema"; @@ -478,6 +479,16 @@ describe("management accounts, optional Fanavaran fields and tenant boundaries", }; } actorAuth.clientDbService = { findOne: async () => repos[0].records[0] }; + const workingHours = new ClientWorkingHoursService({ + findWorkingHours: (filter) => repos[0].findOne(filter).lean(), + findByIdAndUpdate: async (id, update) => { + const client = await repos[0].findOne({ _id: id }).lean(); + if (client) { + client.settings = { ...client.settings, workingHours: update.$set["settings.workingHours"] }; + } + return client; + }, + } as any); const module = await Test.createTestingModule({ imports: [JwtModule.register({})], controllers: [ @@ -489,6 +500,7 @@ describe("management accounts, optional Fanavaran fields and tenant boundaries", SuperAdminGuard, LocalActorAuthGuard, { provide: ManagementService, useValue: service }, + { provide: ClientWorkingHoursService, useValue: workingHours }, { provide: ActorAuthService, useValue: actorAuth }, { provide: CaptchaChallengeService, @@ -550,6 +562,46 @@ describe("management accounts, optional Fanavaran fields and tenant boundaries", ).body.access_token; expect(jwt.decode(makerToken).sub).toBe(maker._id); expect(jwt.decode(reviewerToken).sub).toBe(reviewer._id); + const ownHours = `/expert-insurer/management/working-hours?clientId=${foreign}`; + const otherHours = `/super-admin/management/working-hours?clientId=${foreign}`; + const alwaysOpen = { alwaysOpen: true, windows: [] }; + const restricted = { + alwaysOpen: false, + windows: [{ weekday: 6, opensAt: "08:00", closesAt: "16:00" }], + }; + await request(app.getHttpServer()) + .patch(otherHours) + .auth(companyToken, { type: "bearer" }) + .send(restricted) + .expect(401); + await request(app.getHttpServer()) + .patch(ownHours) + .auth(makerToken, { type: "bearer" }) + .send(restricted) + .expect(403); + await request(app.getHttpServer()) + .patch(ownHours) + .auth(companyToken, { type: "bearer" }) + .send(restricted) + .expect(200, restricted); + await request(app.getHttpServer()) + .get(otherHours) + .auth(adminToken, { type: "bearer" }) + .expect(200, alwaysOpen); + await request(app.getHttpServer()) + .patch(otherHours) + .auth(adminToken, { type: "bearer" }) + .send(restricted) + .expect(200, restricted); + await request(app.getHttpServer()) + .patch(ownHours) + .auth(companyToken, { type: "bearer" }) + .send(alwaysOpen) + .expect(200, alwaysOpen); + await request(app.getHttpServer()) + .get(otherHours) + .auth(adminToken, { type: "bearer" }) + .expect(200, restricted); const statusUrl = `/super-admin/management/staff/file_maker/${maker._id}/status?clientId=${tenant}`; await request(app.getHttpServer()) .patch(statusUrl) @@ -734,7 +786,8 @@ describe("management accounts, optional Fanavaran fields and tenant boundaries", listBranches: jest.fn(), saveBranch: jest.fn(), }; - const controller = new InsurerManagementController(mocked as any); + const workingHours = { read: jest.fn(), update: jest.fn() }; + const controller = new InsurerManagementController(mocked as any, workingHours as any); const actor = { clientKey: tenant }; controller.staff(actor, { clientId: foreign }); controller.createStaff(actor, staff("file_maker")); @@ -742,8 +795,12 @@ describe("management accounts, optional Fanavaran fields and tenant boundaries", controller.branches(actor); controller.createBranch(actor, {} as any); controller.updateBranch(actor, branchId, {}); + controller.readHours(actor); + controller.updateHours(actor, { alwaysOpen: true, windows: [] }); for (const method of Object.values(mocked)) expect(method.mock.calls[0][0]).toBe(tenant); + expect(workingHours.read).toHaveBeenCalledWith(tenant); + expect(workingHours.update).toHaveBeenCalledWith(tenant, { alwaysOpen: true, windows: [] }); }); }); diff --git a/src/request-management/call-center-blame-v6.controller.ts b/src/request-management/call-center-blame-v6.controller.ts index bfd6c1c..746a0d2 100644 --- a/src/request-management/call-center-blame-v6.controller.ts +++ b/src/request-management/call-center-blame-v6.controller.ts @@ -1,3 +1,4 @@ +import { EnforceCaseWorkingHours } from "src/client/working-hours/case-working-hours.interceptor"; import { Body, Controller, @@ -40,6 +41,7 @@ import { * as normal after the blame link is opened. */ @ApiTags("call-center-blame (v6)") +@EnforceCaseWorkingHours() @Controller("v6/call-center-blame") @ApiBearerAuth() @UseGuards(LocalActorAuthGuard, RolesGuard) diff --git a/src/request-management/entities/schema/blame-cases.schema.ts b/src/request-management/entities/schema/blame-cases.schema.ts index ce6d6e7..f7ed679 100644 --- a/src/request-management/entities/schema/blame-cases.schema.ts +++ b/src/request-management/entities/schema/blame-cases.schema.ts @@ -98,6 +98,10 @@ export class BlameRequest { @Prop({ type: Types.ObjectId, index: true }) branchId?: Types.ObjectId; + /** Insurer of the staff member who started intake, before liability is established. */ + @Prop({ type: String }) + workingHoursIntakeClientId?: string; + /** True when this blame was created by a registrar. */ @Prop({ default: false }) registrarInitiated?: boolean; diff --git a/src/request-management/expert-initiated-blame-v3.mirror.controller.ts b/src/request-management/expert-initiated-blame-v3.mirror.controller.ts index 59cf0c4..4450596 100644 --- a/src/request-management/expert-initiated-blame-v3.mirror.controller.ts +++ b/src/request-management/expert-initiated-blame-v3.mirror.controller.ts @@ -1,3 +1,4 @@ +import { EnforceCaseWorkingHours } from "src/client/working-hours/case-working-hours.interceptor"; import { extname } from "node:path"; import { Body, @@ -69,6 +70,7 @@ import { GetCaptureRequirementsV2ResponseDto } from "src/claim-request-managemen * CAR_BODY: same but single party — omit second-party OTP/inquiries/sign steps. */ @ApiTags("expert-initiated blame (mirror v3 in-person)") +@EnforceCaseWorkingHours() @Controller("v3/expert-initiated/blame-request-management") @ApiBearerAuth() @UseGuards(LocalActorAuthGuard, RolesGuard) diff --git a/src/request-management/expert-initiated-blame.mirror.controller.ts b/src/request-management/expert-initiated-blame.mirror.controller.ts index 9b95886..5c8caa0 100644 --- a/src/request-management/expert-initiated-blame.mirror.controller.ts +++ b/src/request-management/expert-initiated-blame.mirror.controller.ts @@ -1,3 +1,4 @@ +import { EnforceCaseWorkingHours } from "src/client/working-hours/case-working-hours.interceptor"; import { extname } from "node:path"; import { Body, @@ -63,6 +64,7 @@ import { PartyRole } from "./entities/schema/partyRole.enum"; * second party steps -> sign FIRST + sign SECOND -> COMPLETED. */ @ApiTags("expert-initiated blame (mirror v2)") +@EnforceCaseWorkingHours() @Controller("v2/expert-initiated/blame-request-management") @ApiBearerAuth() @UseGuards(LocalActorAuthGuard, RolesGuard) diff --git a/src/request-management/expert-initiated.controller.ts b/src/request-management/expert-initiated.controller.ts index 6974baf..3aa4943 100644 --- a/src/request-management/expert-initiated.controller.ts +++ b/src/request-management/expert-initiated.controller.ts @@ -1,3 +1,4 @@ +import { EnforceCaseWorkingHours } from "src/client/working-hours/case-working-hours.interceptor"; import { Body, Controller, Param, Post, UseGuards } from "@nestjs/common"; import { ApiBearerAuth, ApiExcludeController } from "@nestjs/swagger"; import { LocalActorAuthGuard } from "src/auth/guards/actor-local.guard"; @@ -10,6 +11,7 @@ import { ExpertAccidentFieldsDto } from "./dto/expert-accident-fields.dto"; import { RequestManagementService } from "./request-management.service"; @ApiExcludeController() +@EnforceCaseWorkingHours() @Controller("expert-initiated-blame") @ApiBearerAuth() @UseGuards(LocalActorAuthGuard, RolesGuard) diff --git a/src/request-management/expert-initiated.v2.controller.ts b/src/request-management/expert-initiated.v2.controller.ts index 30ccd68..a430a40 100644 --- a/src/request-management/expert-initiated.v2.controller.ts +++ b/src/request-management/expert-initiated.v2.controller.ts @@ -1,3 +1,4 @@ +import { EnforceCaseWorkingHours } from "src/client/working-hours/case-working-hours.interceptor"; import { extname } from "node:path"; import { Controller, @@ -47,6 +48,7 @@ import { PartyRole } from "./entities/schema/partyRole.enum"; * Only the initiating field expert can see/review these files. */ // @ApiTags("expert-initiated-blame (v2)") +@EnforceCaseWorkingHours() @Controller("v2/expert-initiated-blame") @ApiBearerAuth() @UseGuards(LocalActorAuthGuard, RolesGuard) diff --git a/src/request-management/file-maker-blame-v4.controller.ts b/src/request-management/file-maker-blame-v4.controller.ts index 6e4dff8..d19656f 100644 --- a/src/request-management/file-maker-blame-v4.controller.ts +++ b/src/request-management/file-maker-blame-v4.controller.ts @@ -1,3 +1,4 @@ +import { EnforceCaseWorkingHours } from "src/client/working-hours/case-working-hours.interceptor"; import { extname } from "node:path"; import { Body, @@ -70,6 +71,7 @@ import { ListQueryV2Dto } from "src/common/dto/list-query-v2.dto"; * CAR_BODY sequence: same but single party — omit second-party steps. */ @ApiTags("v4 FileMaker — blame file creation") +@EnforceCaseWorkingHours() @Controller("v4/file-maker/blame-request-management") @ApiBearerAuth() @UseGuards(LocalActorAuthGuard, RolesGuard) diff --git a/src/request-management/file-maker-blame-v5.controller.ts b/src/request-management/file-maker-blame-v5.controller.ts index b059ab1..a07749b 100644 --- a/src/request-management/file-maker-blame-v5.controller.ts +++ b/src/request-management/file-maker-blame-v5.controller.ts @@ -1,3 +1,4 @@ +import { EnforceCaseWorkingHours } from "src/client/working-hours/case-working-hours.interceptor"; import { extname } from "node:path"; import { Body, @@ -71,6 +72,7 @@ import { ListQueryV2Dto } from "src/common/dto/list-query-v2.dto"; * → sign (damaged) ← FileMaker job done here */ @ApiTags("v5 FileMaker — blame file creation (with FinancialExpert approval)") +@EnforceCaseWorkingHours() @Controller("v5/file-maker/blame-request-management") @ApiBearerAuth() @UseGuards(LocalActorAuthGuard, RolesGuard) diff --git a/src/request-management/file-maker-claim-approval-v5.controller.ts b/src/request-management/file-maker-claim-approval-v5.controller.ts index 0ee1a32..1574d79 100644 --- a/src/request-management/file-maker-claim-approval-v5.controller.ts +++ b/src/request-management/file-maker-claim-approval-v5.controller.ts @@ -1,3 +1,4 @@ +import { EnforceCaseWorkingHours } from "src/client/working-hours/case-working-hours.interceptor"; import { Body, Controller, Param, Post, UseGuards } from "@nestjs/common"; import { ApiBearerAuth, @@ -44,6 +45,7 @@ class FileMakerRejectDto { * the claimRequestId from the original blame request ID. */ @ApiTags("v5 FileMaker — claim approval before fanavaran") +@EnforceCaseWorkingHours() @Controller("v5/file-maker/claim-approval") @ApiBearerAuth() @UseGuards(LocalActorAuthGuard, RolesGuard) diff --git a/src/request-management/file-reviewer-blame-v4.controller.ts b/src/request-management/file-reviewer-blame-v4.controller.ts index bb56074..a267347 100644 --- a/src/request-management/file-reviewer-blame-v4.controller.ts +++ b/src/request-management/file-reviewer-blame-v4.controller.ts @@ -1,3 +1,4 @@ +import { EnforceCaseWorkingHours } from "src/client/working-hours/case-working-hours.interceptor"; import { randomUUID } from "node:crypto"; import { extname } from "node:path"; import { @@ -74,6 +75,7 @@ import { GetCaptureRequirementsV2ResponseDto } from "src/claim-request-managemen * NOTE: upload-video is a no-op for V4 (blame is already COMPLETED by car-capture). */ @ApiTags("v4 FileReviewer — blame file review & capture") +@EnforceCaseWorkingHours() @Controller("v4/file-reviewer/blame-request-management") @ApiBearerAuth() @UseGuards(LocalActorAuthGuard, RolesGuard) diff --git a/src/request-management/file-reviewer-blame-v5.controller.ts b/src/request-management/file-reviewer-blame-v5.controller.ts index ddaef5f..bd4a65c 100644 --- a/src/request-management/file-reviewer-blame-v5.controller.ts +++ b/src/request-management/file-reviewer-blame-v5.controller.ts @@ -1,3 +1,4 @@ +import { EnforceCaseWorkingHours } from "src/client/working-hours/case-working-hours.interceptor"; import { randomUUID } from "node:crypto"; import { extname } from "node:path"; import { @@ -72,6 +73,7 @@ import { ListQueryV2Dto } from "src/common/dto/list-query-v2.dto"; * NOTE: upload-video is a no-op for V5 (blame is already COMPLETED by car-capture). */ @ApiTags("v5 FileReviewer — blame file review & capture (with FinancialExpert approval)") +@EnforceCaseWorkingHours() @Controller("v5/file-reviewer/blame-request-management") @ApiBearerAuth() @UseGuards(LocalActorAuthGuard, RolesGuard) diff --git a/src/request-management/registrar-blame.mirror.controller.ts b/src/request-management/registrar-blame.mirror.controller.ts index 765ecfa..f3582e5 100644 --- a/src/request-management/registrar-blame.mirror.controller.ts +++ b/src/request-management/registrar-blame.mirror.controller.ts @@ -1,3 +1,4 @@ +import { EnforceCaseWorkingHours } from "src/client/working-hours/case-working-hours.interceptor"; import { extname } from "node:path"; import { BadRequestException, @@ -59,6 +60,7 @@ import { PartyRole } from "./entities/schema/partyRole.enum"; * add-accident-fields -> sign FIRST + sign SECOND -> COMPLETED. */ @ApiTags("registrar blame (mirror v2)") +@EnforceCaseWorkingHours() @Controller("v2/registrar/blame-request-management") @ApiBearerAuth() @UseGuards(LocalActorAuthGuard, RolesGuard) diff --git a/src/request-management/request-management.service.ts b/src/request-management/request-management.service.ts index ade71a2..14a4699 100644 --- a/src/request-management/request-management.service.ts +++ b/src/request-management/request-management.service.ts @@ -1,3 +1,8 @@ +import { + checkDiscoveredBlameInsurer, + checkDiscoveredCaseInsurer, +} from "src/client/working-hours/case-working-hours.interceptor"; +import { actorWorkingHoursClientId } from "src/client/working-hours/client-working-hours.service"; import { normalizeAccidentConditions } from "./accident-conditions"; import { UserClaimBranchService, userClaimBranchContext, usesUserClaimBranch } from "src/client/user-claim-branch.service"; import { normalizeAccidentLocation } from "./accident-location"; @@ -2252,6 +2257,7 @@ export class RequestManagementService { party.person.clientId = await this.resolveCarBodyPolicyClientId(m); } + await checkDiscoveredBlameInsurer(req); // Advance workflow await this.advanceWorkflowToNext(req, stepKey); @@ -2656,6 +2662,7 @@ export class RequestManagementService { } } + await checkDiscoveredBlameInsurer(req); // Advance workflow await this.advanceWorkflowToNext(req, stepKey); @@ -3628,6 +3635,7 @@ export class RequestManagementService { locked: false, }, history: [], + workingHoursIntakeClientId: actorWorkingHoursClientId(registrar), registrarInitiated: true, initiatedByRegistrarId: registrarId, creationMethod: CreationMethod.IN_PERSON, @@ -3758,6 +3766,7 @@ export class RequestManagementService { locked: false, }, history: [], + workingHoursIntakeClientId: actorWorkingHoursClientId(expert), expertInitiated: true, initiatedByFieldExpertId: expertId, ...(expertBranchId ? { branchId: expertBranchId } : {}), @@ -5219,6 +5228,7 @@ export class RequestManagementService { }); const carBodyClientId = await this.resolveCarBodyPolicyClientId(carBodyInfo); + await checkDiscoveredCaseInsurer(carBodyClientId); if (!inquirySubmission.participants.legacy) { const options = carBodyClientId ? { clientId: String(carBodyClientId) } @@ -5624,6 +5634,7 @@ export class RequestManagementService { decidedByExpertId: new Types.ObjectId(expert.sub), fields: { ...MUTUAL_AGREEMENT_EXPERT_DECISION_FIELDS }, } as any; + await checkDiscoveredBlameInsurer(req); req.workflow = { currentStep: WorkflowStep.FIRST_LOCATION as any, nextStep: WorkflowStep.SECOND_LOCATION as any, @@ -7086,6 +7097,15 @@ export class RequestManagementService { } } + // The first party's policy funds the interim third-party claim in this flow. + if ( + req.type === BlameRequestType.THIRD_PARTY && + partyRole === PartyRole.FIRST + ) { + await checkDiscoveredCaseInsurer(party.person?.clientId); + } else { + await checkDiscoveredBlameInsurer(req); + } await this.runParticipantPersonalInquiries( req, partyRole, @@ -7293,6 +7313,7 @@ export class RequestManagementService { payingClientId = guiltyClientId ? String(guiltyClientId) : undefined; } + await checkDiscoveredCaseInsurer(payingClientId); const claimNo = `CL${Math.floor(10000 + Math.random() * 90000)}`; const newClaimData: any = { requestNo: claimNo, @@ -8024,6 +8045,14 @@ export class RequestManagementService { } } + if ( + req.type === BlameRequestType.THIRD_PARTY && + partyRole === PartyRole.FIRST + ) { + await checkDiscoveredCaseInsurer(party.person?.clientId); + } else { + await checkDiscoveredBlameInsurer(req); + } await this.runParticipantPersonalInquiries( req, partyRole, @@ -9257,6 +9286,7 @@ export class RequestManagementService { locked: false, }, history: [], + workingHoursIntakeClientId: actorWorkingHoursClientId(agent), callCenterInitiated: true, initiatedByCallCenterId: agentId, creationMethod: CreationMethod.LINK, diff --git a/src/request-management/request-management.v2.controller.ts b/src/request-management/request-management.v2.controller.ts index 8d791a2..9dd557c 100644 --- a/src/request-management/request-management.v2.controller.ts +++ b/src/request-management/request-management.v2.controller.ts @@ -1,3 +1,4 @@ +import { EnforceCaseWorkingHours } from "src/client/working-hours/case-working-hours.interceptor"; import { extname } from "node:path"; import { randomUUID } from "node:crypto"; import { mkdirSync } from "node:fs"; @@ -55,6 +56,7 @@ import { GetUserBlameListV2ResponseDto } from "./dto/blame-list-user-v2.dto"; * Versioning strategy: prefix the controller route with `v2/` so * all endpoints under this controller are automatically V2. */ +@EnforceCaseWorkingHours() @Controller("v2/blame-request-management") @ApiTags("blame-request-management (v2)") @ApiBearerAuth() diff --git a/test/contracts/api-routes.json b/test/contracts/api-routes.json index 096d642..046f7d4 100644 --- a/test/contracts/api-routes.json +++ b/test/contracts/api-routes.json @@ -337,6 +337,18 @@ "company" ] }, + { + "controller": "InsurerManagementController", + "method": "GET", + "path": "/expert-insurer/management/working-hours", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "company" + ] + }, { "controller": "ExpertInsurerController", "method": "GET", @@ -1072,6 +1084,15 @@ ], "roles": [] }, + { + "controller": "SuperAdminManagementController", + "method": "GET", + "path": "/super-admin/management/working-hours", + "guards": [ + "SuperAdminGuard" + ], + "roles": [] + }, { "controller": "SuperAdminController", "method": "GET", @@ -2045,6 +2066,18 @@ "company" ] }, + { + "controller": "InsurerManagementController", + "method": "PATCH", + "path": "/expert-insurer/management/working-hours", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "company" + ] + }, { "controller": "SuperAdminController", "method": "PATCH", @@ -2099,6 +2132,15 @@ ], "roles": [] }, + { + "controller": "SuperAdminManagementController", + "method": "PATCH", + "path": "/super-admin/management/working-hours", + "guards": [ + "SuperAdminGuard" + ], + "roles": [] + }, { "controller": "SuperAdminController", "method": "PATCH",