Files
jorgecuadros-platform/apps/api/src/policies/policies.service.ts
T
rmancinasandClaude Opus 5 48e01ddd21
Build and Push Images / Build jorgecuadros-api (push) Successful in 2m19s
Build and Push Images / Build jorgecuadros-web (push) Successful in 2m1s
feat(policies): capture the full premium breakdown
The capture form only ever had prima neta, derecho de póliza and comisión.
The Access form it replaces has seven figures, and the four that were missing
are the ones that make a policy paid in installments add up.

Adds recargo, IVA, prima total and forma de pago to the policy header, the
same breakdown per installment, and a per-line-of-business IVA rate.

IVA and prima total are the only derived figures:

    base  = prima neta + recargo + derecho de póliza
    IVA   = round(base * tasa)
    total = base + IVA

The recargo is inside the taxable base. That is not a guess — policy 7006785
prints IVA 52.03 on 610.86 + 8.55 + 31.00, and leaving the recargo out gives
51.35, which matches nothing on the page. Both of its money rows are asserted
in premium.spec.ts. The recargo itself is never derived: the carrier quotes it,
so staff key it in, and the field is disabled on ANNUAL/SINGLE. Both derived
figures are stored rather than recomputed on read, and stay editable, because
the printed policy is the record of truth and a later rate change must not
silently restate what was issued.

The rate lives on PolicyType (seeded to 0.08, editable in Catálogos), which is
the legacy one-row IMPUESTOS / IMPUESTOS_AUTOS tables made configurable. The
rate applied is stamped on the policy so an old one reads back at its original
rate.

Per-installment, not two fixed slots on the header: a policy split into several
exhibiciones prices each payment separately — that is why the Access form drew
the money row twice — and a trimestral policy needs four, which the Access
layout could not hold.

Also fixes two losses in the ETL, which is how these went missing:

  - `forma_pago` was marked consumed by the coverage sweep and then never
    written to any column, so FORMA PAGO existed nowhere in the platform.
  - `recargo` and the whole second money row fell into `coveragesJson` as
    loose strings, mislabeled as coverage amounts.

transform_policies.py now writes all of it directly;
backfill_policy_premium_breakdown.py recovers it on a database that must not be
re-imported, and strips the migrated keys back out of coveragesJson. Both are
COALESCE-only, so a figure a human has corrected in the app wins.

IVA and TOTAL are NOT backfilled: they were unbound calculated controls on the
Access form, never columns, so there is nothing to recover and every migrated
policy reads null until it is edited.

The backfill warns on 5 annual policies that carry a non-zero recargo — a
contradiction that predates this change and is left for a human, not silently
corrected.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-18 00:24:22 -07:00

654 lines
22 KiB
TypeScript

import { BadRequestException, Injectable, NotFoundException } from "@nestjs/common";
import { randomUUID } from "node:crypto";
import { Prisma } from "@jorgecuadros/database";
import { PrismaService } from "../prisma/prisma.service";
import { StorageService } from "../storage/storage.service";
import { extForUpload, type UploadedFileLike } from "../storage/upload-file";
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
* bucket rather than an error case: 528 of the migrated policies carry no end
* date at all (the legacy Access tables left it blank), so they can neither be
* called current nor expired.
*/
export type PolicyStatus = "active" | "expiring" | "expired" | "undated";
export type PolicySort =
| "expiry_desc"
| "expiry_asc"
| "customer"
| "number"
| "premium_desc";
export interface ListParams {
query?: string;
page: number;
pageSize: number;
status?: PolicyStatus;
/** Window in days for the `expiring` bucket. */
days: number;
typeId?: string;
providerId?: string;
liquidated?: boolean;
includeArchived?: boolean;
sort: PolicySort;
}
/** Midnight today, UTC — policy dates are stored date-only at 00:00 UTC. */
function today(): Date {
const now = new Date();
return new Date(
Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()),
);
}
function addDays(d: Date, days: number): Date {
return new Date(d.getTime() + days * 86400000);
}
function statusOf(policyTo: Date | null, from: Date, soon: Date): PolicyStatus {
if (!policyTo) return "undated";
if (policyTo < from) return "expired";
return policyTo <= soon ? "expiring" : "active";
}
function daysUntil(policyTo: Date | null, from: Date): number | null {
if (!policyTo) return null;
return Math.round((policyTo.getTime() - from.getTime()) / 86400000);
}
@Injectable()
export class PoliciesService {
constructor(
private readonly prisma: PrismaService,
private readonly storage: StorageService,
) {}
private statusWhere(
status: PolicyStatus | undefined,
days: number,
): Prisma.PolicyWhereInput {
const from = today();
switch (status) {
case "active":
return { policyTo: { gte: from } };
case "expiring":
return { policyTo: { gte: from, lte: addDays(from, days) } };
case "expired":
return { policyTo: { lt: from } };
case "undated":
return { policyTo: null };
default:
return {};
}
}
private orderBy(sort: PolicySort): Prisma.PolicyOrderByWithRelationInput[] {
switch (sort) {
case "expiry_asc":
return [{ policyTo: "asc" }];
case "customer":
return [{ customer: { name: "asc" } }, { policyTo: "desc" }];
case "number":
return [{ policyNumber: "asc" }];
case "premium_desc":
// Sorts on netPremium, not total: `total` is 0 or null on all but 2 of
// the 2378 migrated policies, so ordering by it is meaningless.
return [{ netPremium: "desc" }];
default:
// MySQL sorts NULLs last on DESC, which puts the 528 undated policies
// at the end instead of the top — the behaviour we want by default.
return [{ policyTo: "desc" }];
}
}
/** Policy list with search, vigencia/type/provider filters, paginated. */
async list(params: ListParams) {
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 = [
{ policyNumber: { contains: q } },
{ customer: { name: { contains: q } } },
{ agentName: { contains: q } },
{ vehicles: { some: { licensePlate: { contains: q } } } },
{ insuredDrivers: { some: { fullName: { contains: q } } } },
{ legacyId: { contains: q } },
];
}
if (typeId) where.policyTypeId = typeId;
if (providerId) where.insuranceProviderId = providerId;
if (liquidated !== undefined) where.liquidated = liquidated;
const [total, rows] = await this.prisma.$transaction([
this.prisma.policy.count({ where }),
this.prisma.policy.findMany({
where,
skip: (page - 1) * pageSize,
take: pageSize,
orderBy: this.orderBy(sort),
select: {
id: true,
policyNumber: true,
agentName: true,
policyFrom: true,
policyTo: true,
netPremium: true,
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 } },
_count: { select: { vehicles: true, installments: true, documents: true } },
},
}),
]);
const from = today();
const soon = addDays(from, days);
const items = rows.map((r) => ({
id: r.id,
policyNumber: r.policyNumber,
agentName: r.agentName,
policyFrom: r.policyFrom,
policyTo: r.policyTo,
netPremium: r.netPremium,
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,
policyType: r.policyType,
insuranceProvider: r.insuranceProvider,
status: statusOf(r.policyTo, from, soon),
daysToExpiry: daysUntil(r.policyTo, from),
vehicleCount: r._count.vehicles,
installmentCount: r._count.installments,
documentCount: r._count.documents,
}));
return { items, total, page, pageSize, pageCount: Math.ceil(total / pageSize) };
}
/** Top-line counts for the policies page header. */
async stats(days: number) {
const from = today();
const soon = addDays(from, days);
const [total, active, expiring, expired, undated, liquidated] =
await this.prisma.$transaction([
this.prisma.policy.count(),
this.prisma.policy.count({ where: { policyTo: { gte: from } } }),
this.prisma.policy.count({
where: { policyTo: { gte: from, lte: soon } },
}),
this.prisma.policy.count({ where: { policyTo: { lt: from } } }),
this.prisma.policy.count({ where: { policyTo: null } }),
this.prisma.policy.count({ where: { liquidated: true } }),
]);
// Premium in force, per currency — the two currencies can't be summed.
const inForce = await this.prisma.policy.groupBy({
by: ["currency"],
where: { policyTo: { gte: from } },
_sum: { total: true, netPremium: true },
_count: { _all: true },
});
return {
total,
active,
expiring,
expired,
undated,
liquidated,
pending: total - liquidated,
days,
premiumInForce: inForce.map((r) => ({
currency: r.currency,
total: r._sum.total,
netPremium: r._sum.netPremium,
count: r._count._all,
})),
};
}
/** Filter dropdown options, with counts so empty choices are visible. */
async facets() {
const [types, providers] = await this.prisma.$transaction([
this.prisma.policyType.findMany({
orderBy: { name: "asc" },
select: {
id: true,
name: true,
shortDescription: true,
// The capture form computes IVA client-side as the operator types,
// so the rate has to travel with the type list it already loads —
// an extra round-trip per keystroke is not an option.
taxRate: true,
_count: { select: { policies: true } },
},
}),
this.prisma.insuranceProvider.findMany({
orderBy: { name: "asc" },
select: { id: true, name: true, _count: { select: { policies: true } } },
}),
]);
return {
types: types.map((t) => ({
id: t.id,
name: t.name,
shortDescription: t.shortDescription,
taxRate: t.taxRate,
count: t._count.policies,
})),
providers: providers.map((p) => ({
id: p.id,
name: p.name,
count: p._count.policies,
})),
};
}
/** Full policy view, including the owning customer. */
async detail(id: string, days: number) {
const policy = await this.prisma.policy.findUnique({
where: { id },
include: {
customer: {
select: {
id: true,
name: true,
nameSource: true,
city: true,
state: true,
phone: true,
mobile: true,
email: true,
},
},
policyType: true,
insuranceProvider: true,
installments: { orderBy: { sequence: "asc" } },
vehicles: true,
insuredDrivers: true,
beneficiaries: true,
claims: { include: { adjuster: true } },
documents: true,
properties: {
select: { id: true, addressLine1: true, addressLine2: true, zone: true },
},
},
});
if (!policy) {
throw new NotFoundException(`Policy ${id} not found`);
}
const from = today();
return {
...policy,
status: statusOf(policy.policyTo, from, addDays(from, days)),
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,
netPremium: dto.netPremium,
surcharge: dto.surcharge,
policyFee: dto.policyFee,
tax: dto.tax,
taxRate: dto.taxRate,
total: dto.total,
commission: dto.commission,
},
});
}
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,
netPremium: dto.netPremium,
surcharge: dto.surcharge,
policyFee: dto.policyFee,
tax: dto.tax,
taxRate: dto.taxRate,
total: dto.total,
commission: dto.commission,
},
});
}
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) }),
};
}
// --- documents ------------------------------------------------------------
// Blob in object storage under `policy/<policyId>/…`; row is the pointer.
async addDocument(
policyId: string,
file: UploadedFileLike,
documentType?: string,
) {
await this.ensurePolicy(policyId);
const key = `policy/${policyId}/${randomUUID()}${extForUpload(file)}`;
await this.storage.put(key, file.buffer, file.mimetype);
return this.prisma.policyDocument.create({
data: {
policyId,
documentType: documentType?.trim() || "DOCUMENT",
storageKey: key,
},
});
}
async getDocument(policyId: string, id: string) {
const row = await this.prisma.policyDocument.findFirst({
where: { id, policyId },
});
if (!row) throw new NotFoundException(`Document ${id} not found on policy ${policyId}`);
const blob = await this.storage.getStream(row.storageKey);
return { row, ...blob };
}
async removeDocument(policyId: string, id: string) {
await this.ensurePolicy(policyId);
const row = await this.prisma.policyDocument.findFirst({
where: { id, policyId },
select: { id: true, storageKey: true },
});
if (!row) throw new NotFoundException(`Document ${id} not found on policy ${policyId}`);
const deleted = await this.prisma.policyDocument.delete({ where: { id } });
await this.storage.delete(row.storageKey);
return deleted;
}
// --- 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 });
}
/**
* Deleting a lookup row that policies still point at is silent data loss.
*
* Both FKs are `ON DELETE SET NULL` (see `0000_init`), so the delete
* succeeds, returns 200, and blanks the field on every policy that used it
* — with no error and nothing in the UI to suggest anything happened. That
* is how the `M_EMPR` policy type disappeared and left 5 policies with a
* null `policyTypeId`, only found later by querying.
*
* Refusing is the whole fix. There is no "are you sure": the operator
* reassigns those policies first, which is work the app cannot do for them
* because only they know which type is correct.
*/
private async assertLookupUnused(
kind: "provider" | "policyType",
id: string,
): Promise<void> {
const where = kind === "provider" ? { insuranceProviderId: id } : { policyTypeId: id };
const count = await this.prisma.policy.count({ where });
if (count === 0) return;
const label =
kind === "provider"
? (await this.prisma.insuranceProvider.findUnique({ where: { id } }))?.name
: (await this.prisma.policyType.findUnique({ where: { id } }))?.name;
const noun = kind === "provider" ? "La aseguradora" : "El tipo de póliza";
throw new BadRequestException(
`${noun} «${label ?? id}» está en uso por ${count} póliza(s). ` +
"Reasígnelas antes de eliminarlo.",
);
}
async removeProvider(id: string) {
await this.assertLookupUnused("provider", id);
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 });
}
async removePolicyType(id: string) {
await this.assertLookupUnused("policyType", id);
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 });
}
/** Same `ON DELETE SET NULL` trap as the two above, on `claims.adjusterId`:
* deleting a busy adjuster would quietly strip them off their claims. */
async removeAdjuster(id: string) {
const count = await this.prisma.claim.count({ where: { adjusterId: id } });
if (count > 0) {
const row = await this.prisma.adjuster.findUnique({ where: { id } });
throw new BadRequestException(
`El ajustador «${row?.name ?? id}» está asignado a ${count} siniestro(s). ` +
"Reasígnelos antes de eliminarlo.",
);
}
return this.prisma.adjuster.delete({ where: { id } });
}
}