Files
yara724-api/src/client/user-claim-branch.service.ts
T

85 lines
2.9 KiB
TypeScript

import { BadRequestException, Injectable } from "@nestjs/common";
import { Types } from "mongoose";
import { BranchDbService } from "./entities/db-service/branch.db.service";
import { resolveClaimBeneficiary } from "src/helpers/blame-claim-eligibility";
import { resolveClaimOwnerParty } from "src/helpers/blame-damaged-party";
/** User-led v1/v6 only. Expert/registrar-created flows retain their ownership. */
export function usesUserClaimBranch(blame: any): boolean {
return (
!!blame.callCenterInitiated ||
(!blame.expertInitiated &&
!blame.registrarInitiated &&
!blame.isMadeByFileMaker &&
blame.creationMethod !== "IN_PERSON")
);
}
export function userClaimBranchContext(blame: any, userId: string) {
const beneficiary = resolveClaimBeneficiary(blame);
return {
required:
usesUserClaimBranch(blame) &&
!!beneficiary?.person?.userId &&
String(beneficiary.person.userId) === String(userId),
branchId: blame.branchId ? String(blame.branchId) : null,
};
}
@Injectable()
export class UserClaimBranchService {
constructor(private readonly branches: BranchDbService) {}
private payerId(blame: any): string {
const id = String(resolveClaimOwnerParty(blame)?.person?.clientId ?? "");
if (!Types.ObjectId.isValid(id)) {
throw new BadRequestException(
"شرکت بیمه پرداخت‌کننده خسارت مشخص نیست. اطلاعات بیمه‌نامه را بررسی کنید.",
);
}
return id;
}
async options(blame: any) {
const clientId = this.payerId(blame);
const branches = await this.branches.findAllWithFilters(clientId, {
isActive: true,
});
return branches
.map((branch: any) => ({
id: String(branch._id),
name: String(branch.fullName || branch.name || branch.code || "شعبه").trim(),
code: String(branch.code ?? ""),
city: String(branch.city ?? "").trim(),
state: String(branch.state ?? "").trim(),
address: String(branch.address ?? ""),
phoneNumber: branch.phoneNumber,
}))
.sort(
(a, b) =>
a.city.localeCompare(b.city, "fa") ||
a.name.localeCompare(b.name, "fa"),
);
}
async validate(blame: any, branchId: unknown): Promise<string> {
const id = typeof branchId === "string" ? branchId.trim() : "";
if (!Types.ObjectId.isValid(id)) {
throw new BadRequestException(
"شهر و شعبه رسیدگی به خسارت را انتخاب کنید.",
);
}
const branch = await this.branches.findById(id);
if (
!branch ||
branch.isActive !== true ||
String(branch.clientKey) !== this.payerId(blame)
) {
throw new BadRequestException(
"شعبه انتخاب‌شده فعال نیست یا متعلق به شرکت بیمه پرداخت‌کننده خسارت نیست. شعبه دیگری انتخاب کنید.",
);
}
return id;
}
}