feat(policies): full CRUD + child editors + insurance lookups (plan phase 3)

Policy header, all five child collections, and the insurance reference
catalogs become create/edit/delete-able on the RBAC foundation.

API:
- Policy gains archivedAt (soft-delete); list/browser default to
  archivedAt=null with ?includeArchived opt-in.
- PoliciesService: header create/update/archive/restore (customer FK
  validated for a clean 404); add/update/remove for installments,
  vehicles, drivers, beneficiaries, claims — each scoped to its policy so
  one policy's id can't touch another's rows; lookups CRUD for providers,
  policy types, adjusters.
- PoliciesController write routes: header create/update need STAFF+
  (policy:create/update), archive/restore need MANAGER+ (policy:delete),
  every child route needs policy:update. New LookupsController at /lookups
  (read open; mutate needs lookup:manage / MANAGER+). Mutations audited.
- DTOs (policy header, children, lookups); dates coerced; shared coerce.ts.

Web:
- Generic ChildCollection editor (config-driven add/edit/remove table),
  reused by both the policy detail child editors and the catalogs screen.
- PolicyForm (header) with type/provider selects and a debounced
  CustomerPicker; /polizas/nuevo (accepts ?customerId prefill) and
  /polizas/[id]/editar. Policy detail: gated action bar (Editar/Archivar)
  + "Administrar detalles" child editors for all five collections.
- /catalogos admin screen (aseguradoras/tipos/ajustadores), nav-gated on
  lookup:manage. "Nueva póliza" buttons on the list and on the customer
  detail (prefilled). api.ts + types for all of the above.

Verified against dev: policy create (dates coerced, archivedAt null),
installment/vehicle add, VIEWER child-add 403, cross-policy child guard
404, lookups CRUD with VIEWER 403 / MANAGER 201, archive drops from the
default list and includeArchived surfaces it. Both apps compile clean.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-07-23 12:22:02 -07:00
co-authored by Claude Opus 4.8
parent 12692a0af8
commit 7a46c30d9b
22 changed files with 1973 additions and 19 deletions
+253 -2
View File
@@ -1,6 +1,27 @@
import { Injectable, NotFoundException } from "@nestjs/common";
import { Prisma } from "@jorgecuadros/database";
import { PrismaService } from "../prisma/prisma.service";
import { toDate } from "../common/coerce";
import { CreatePolicyDto, UpdatePolicyDto } from "./policy.dto";
import {
BeneficiaryDto,
ClaimDto,
DriverDto,
InstallmentDto,
UpdateBeneficiaryDto,
UpdateClaimDto,
UpdateDriverDto,
UpdateInstallmentDto,
VehicleDto,
} from "./children.dto";
import {
AdjusterDto,
PolicyTypeDto,
ProviderDto,
UpdateAdjusterDto,
UpdatePolicyTypeDto,
UpdateProviderDto,
} from "./lookup.dto";
/**
* Vigencia buckets, derived from `policyTo` against today. `undated` is a real
@@ -27,6 +48,7 @@ export interface ListParams {
typeId?: string;
providerId?: string;
liquidated?: boolean;
includeArchived?: boolean;
sort: PolicySort;
}
@@ -97,11 +119,13 @@ export class PoliciesService {
/** Policy list with search, vigencia/type/provider filters, paginated. */
async list(params: ListParams) {
const { query, page, pageSize, status, days, typeId, providerId, liquidated, sort } =
params;
const { query, page, pageSize, status, days, typeId, providerId, liquidated,
includeArchived, sort } = params;
const where: Prisma.PolicyWhereInput = { ...this.statusWhere(status, days) };
if (!includeArchived) where.archivedAt = null;
if (query && query.trim()) {
const q = query.trim();
where.OR = [
@@ -134,6 +158,7 @@ export class PoliciesService {
total: true,
currency: true,
liquidated: true,
archivedAt: true,
customer: { select: { id: true, name: true, city: true } },
policyType: { select: { id: true, name: true } },
insuranceProvider: { select: { id: true, name: true } },
@@ -155,6 +180,7 @@ export class PoliciesService {
total: r.total,
currency: r.currency,
liquidated: r.liquidated,
archived: r.archivedAt != null,
customerId: r.customer.id,
customerName: r.customer.name,
customerCity: r.customer.city,
@@ -278,4 +304,229 @@ export class PoliciesService {
daysToExpiry: daysUntil(policy.policyTo, from),
};
}
// --- policy header writes -------------------------------------------------
private headerData(dto: CreatePolicyDto | UpdatePolicyDto) {
const { policyDate, policyFrom, policyTo, liquidationDate, ...rest } =
dto as CreatePolicyDto;
return {
...rest,
...(policyDate !== undefined && { policyDate: toDate(policyDate) }),
...(policyFrom !== undefined && { policyFrom: toDate(policyFrom) }),
...(policyTo !== undefined && { policyTo: toDate(policyTo) }),
...(liquidationDate !== undefined && { liquidationDate: toDate(liquidationDate) }),
};
}
async create(dto: CreatePolicyDto) {
// Validate the customer FK up front for a clean 404 instead of a raw
// Prisma constraint error.
const customer = await this.prisma.customer.findUnique({
where: { id: dto.customerId },
select: { id: true },
});
if (!customer) throw new NotFoundException(`Customer ${dto.customerId} not found`);
return this.prisma.policy.create({
data: {
...this.headerData(dto),
policyNumber: dto.policyNumber,
customerId: dto.customerId,
},
});
}
async update(id: string, dto: UpdatePolicyDto) {
await this.ensurePolicy(id);
return this.prisma.policy.update({ where: { id }, data: this.headerData(dto) });
}
async archive(id: string) {
await this.ensurePolicy(id);
return this.prisma.policy.update({ where: { id }, data: { archivedAt: new Date() } });
}
async restore(id: string) {
await this.ensurePolicy(id);
return this.prisma.policy.update({ where: { id }, data: { archivedAt: null } });
}
private async ensurePolicy(id: string) {
const found = await this.prisma.policy.findUnique({
where: { id },
select: { id: true },
});
if (!found) throw new NotFoundException(`Policy ${id} not found`);
}
// --- child rows -----------------------------------------------------------
// Each child is created under a policy and edited/removed by its own id,
// scoped to that policy so one policy's id can't touch another's rows.
private async ensureChild(
model: "policyPaymentInstallment" | "vehicle" | "insuredDriver" | "policyBeneficiary" | "claim",
policyId: string,
childId: string,
) {
await this.ensurePolicy(policyId);
// @ts-expect-error dynamic delegate access is safe for these known models
const row = await this.prisma[model].findFirst({
where: { id: childId, policyId },
select: { id: true },
});
if (!row) throw new NotFoundException(`Child ${childId} not found on policy ${policyId}`);
}
async addInstallment(policyId: string, dto: InstallmentDto) {
await this.ensurePolicy(policyId);
return this.prisma.policyPaymentInstallment.create({
data: {
policyId,
sequence: dto.sequence,
amount: dto.amount,
currency: dto.currency,
dueDate: toDate(dto.dueDate) ?? undefined,
paidDate: toDate(dto.paidDate) ?? undefined,
checkNumber: dto.checkNumber,
isCash: dto.isCash,
},
});
}
async updateInstallment(policyId: string, id: string, dto: UpdateInstallmentDto) {
await this.ensureChild("policyPaymentInstallment", policyId, id);
return this.prisma.policyPaymentInstallment.update({
where: { id },
data: {
sequence: dto.sequence,
amount: dto.amount,
currency: dto.currency,
...(dto.dueDate !== undefined && { dueDate: toDate(dto.dueDate) }),
...(dto.paidDate !== undefined && { paidDate: toDate(dto.paidDate) }),
checkNumber: dto.checkNumber,
isCash: dto.isCash,
},
});
}
async removeInstallment(policyId: string, id: string) {
await this.ensureChild("policyPaymentInstallment", policyId, id);
return this.prisma.policyPaymentInstallment.delete({ where: { id } });
}
async addVehicle(policyId: string, dto: VehicleDto) {
await this.ensurePolicy(policyId);
return this.prisma.vehicle.create({ data: { policyId, ...dto } });
}
async updateVehicle(policyId: string, id: string, dto: VehicleDto) {
await this.ensureChild("vehicle", policyId, id);
return this.prisma.vehicle.update({ where: { id }, data: { ...dto } });
}
async removeVehicle(policyId: string, id: string) {
await this.ensureChild("vehicle", policyId, id);
return this.prisma.vehicle.delete({ where: { id } });
}
async addDriver(policyId: string, dto: DriverDto) {
await this.ensurePolicy(policyId);
return this.prisma.insuredDriver.create({
data: { policyId, ...dto, birthDate: toDate(dto.birthDate) ?? undefined },
});
}
async updateDriver(policyId: string, id: string, dto: UpdateDriverDto) {
await this.ensureChild("insuredDriver", policyId, id);
return this.prisma.insuredDriver.update({
where: { id },
data: { ...dto, ...(dto.birthDate !== undefined && { birthDate: toDate(dto.birthDate) }) },
});
}
async removeDriver(policyId: string, id: string) {
await this.ensureChild("insuredDriver", policyId, id);
return this.prisma.insuredDriver.delete({ where: { id } });
}
async addBeneficiary(policyId: string, dto: BeneficiaryDto) {
await this.ensurePolicy(policyId);
return this.prisma.policyBeneficiary.create({ data: { policyId, ...dto } });
}
async updateBeneficiary(policyId: string, id: string, dto: UpdateBeneficiaryDto) {
await this.ensureChild("policyBeneficiary", policyId, id);
return this.prisma.policyBeneficiary.update({ where: { id }, data: { ...dto } });
}
async removeBeneficiary(policyId: string, id: string) {
await this.ensureChild("policyBeneficiary", policyId, id);
return this.prisma.policyBeneficiary.delete({ where: { id } });
}
async addClaim(policyId: string, dto: ClaimDto) {
await this.ensurePolicy(policyId);
return this.prisma.claim.create({ data: { policyId, ...this.claimData(dto) } });
}
async updateClaim(policyId: string, id: string, dto: UpdateClaimDto) {
await this.ensureChild("claim", policyId, id);
return this.prisma.claim.update({ where: { id }, data: this.claimData(dto) });
}
async removeClaim(policyId: string, id: string) {
await this.ensureChild("claim", policyId, id);
return this.prisma.claim.delete({ where: { id } });
}
private claimData(dto: ClaimDto) {
const { incidentDate, reportedDate, settlementDate, ...rest } = dto;
return {
...rest,
...(incidentDate !== undefined && { incidentDate: toDate(incidentDate) }),
...(reportedDate !== undefined && { reportedDate: toDate(reportedDate) }),
...(settlementDate !== undefined && { settlementDate: toDate(settlementDate) }),
};
}
// --- lookups (providers / policy types / adjusters) -----------------------
listLookups() {
return this.prisma.$transaction([
this.prisma.insuranceProvider.findMany({
orderBy: { name: "asc" },
select: { id: true, name: true, _count: { select: { policies: true } } },
}),
this.prisma.policyType.findMany({
orderBy: { name: "asc" },
select: {
id: true,
name: true,
shortDescription: true,
_count: { select: { policies: true } },
},
}),
this.prisma.adjuster.findMany({ orderBy: { name: "asc" } }),
]).then(([providers, types, adjusters]) => ({ providers, types, adjusters }));
}
createProvider(dto: ProviderDto) {
return this.prisma.insuranceProvider.create({ data: dto });
}
updateProvider(id: string, dto: UpdateProviderDto) {
return this.prisma.insuranceProvider.update({ where: { id }, data: dto });
}
removeProvider(id: string) {
return this.prisma.insuranceProvider.delete({ where: { id } });
}
createPolicyType(dto: PolicyTypeDto) {
return this.prisma.policyType.create({ data: dto });
}
updatePolicyType(id: string, dto: UpdatePolicyTypeDto) {
return this.prisma.policyType.update({ where: { id }, data: dto });
}
removePolicyType(id: string) {
return this.prisma.policyType.delete({ where: { id } });
}
createAdjuster(dto: AdjusterDto) {
return this.prisma.adjuster.create({ data: dto });
}
updateAdjuster(id: string, dto: UpdateAdjusterDto) {
return this.prisma.adjuster.update({ where: { id }, data: dto });
}
removeAdjuster(id: string) {
return this.prisma.adjuster.delete({ where: { id } });
}
}