feat(claims): enforce insurer working hours

This commit is contained in:
SepehrYahyaee
2026-11-24 12:18:39 +03:30
parent 475780f17e
commit f29461fa67
35 changed files with 879 additions and 3 deletions
+2
View File
@@ -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,
@@ -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)
@@ -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)
@@ -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)
+3
View File
@@ -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 {}
@@ -56,6 +56,14 @@ export class ClientDbService implements OnModuleInit {
return this.clientModel.findOne(client);
}
async findWorkingHours(filter: FilterQuery<ClientModel>) {
return this.clientModel
.findOne(filter)
.select("settings.workingHours")
.lean()
.exec();
}
async findAll(): Promise<ClientModel[]> {
return await this.clientModel.find();
}
@@ -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<ExternalInquiryFla
* working when a field is missing.
*/
export class ClientSettings {
@Prop({ type: Object, required: false })
workingHours?: WorkingHours;
/**
* Max number of days between the accident and the moment a CAR_BODY blame
* file is allowed to be submitted. When unset, consumers fall back to the
@@ -0,0 +1,120 @@
import {
CallHandler,
ExecutionContext,
Injectable,
NestInterceptor,
SetMetadata,
} from "@nestjs/common";
import { Reflector } from "@nestjs/core";
import { AsyncLocalStorage } from "node:async_hooks";
import { Types } from "mongoose";
import { Observable } from "rxjs";
import { ClaimCaseDbService } from "src/claim-request-management/entites/db-service/claim-case.db.service";
import { BlameRequestDbService } from "src/request-management/entities/db-service/blame-request.db.service";
import {
actorWorkingHoursClientId,
ClientWorkingHoursService,
responsibleBlameInsurer,
workingHoursClientId,
} from "./client-working-hours.service";
const CASE_WRITES = Symbol("case-working-hours");
type CaseWriteOptions = { genericId?: "blame" };
export const EnforceCaseWorkingHours = (options: CaseWriteOptions = {}) =>
SetMetadata(CASE_WRITES, options);
const WRITE_METHODS = new Set(["POST", "PUT", "PATCH", "DELETE"]);
const caseScheduleScope = new AsyncLocalStorage<
(clientId: string) => Promise<void>
>();
// 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<typeof responsibleBlameInsurer>[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<CaseWriteOptions>(
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<string | undefined>();
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<string, string>,
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<string, any>[];
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),
};
}
}
@@ -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;
}
}
@@ -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<string, string> = {},
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();
});
});
+151
View File
@@ -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<string, unknown> {
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<number>();
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<typeof getNextOpening>) {
const message =
"ثبت و ادامه پرونده فقط در ساعات کاری شرکت بیمه امکان‌پذیر است.";
if (!next) return message;
const time = next.time.replace(/\d/g, (digit) => "۰۱۲۳۴۵۶۷۸۹"[Number(digit)]);
return `${message} شروع بعدی: ${DAYS[next.weekday]} ساعت ${time} به وقت تهران.`;
}
@@ -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)
+6
View File
@@ -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,
@@ -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)
@@ -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)
+2
View File
@@ -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)
+27 -2
View File
@@ -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,
+2
View File
@@ -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 },
+58 -1
View File
@@ -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: [] });
});
});
@@ -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)
@@ -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;
@@ -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)
@@ -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)
@@ -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)
@@ -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)
@@ -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)
@@ -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)
@@ -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)
@@ -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)
@@ -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)
@@ -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)
@@ -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,
@@ -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()