Fix Shape import resolvePolicyLink: use nearest match, no date window

- Removed ±40 day window restriction that caused prior-cycle tasks to miss their group/policy
- Now finds nearest group/policy by absolute date proximity for any cycle
- Deleted 310 client-level orphans created by previous import runs
This commit is contained in:
lorentz 2026-04-13 20:39:09 +00:00
parent 4e54b7e38c
commit c40dd68360

View file

@ -598,28 +598,28 @@ async function ensureTaskAssignment(taskId: string, userId: string, stats: Impor
async function resolvePolicyLink(clientId: string, effectiveDate: Date, templateLevel: string): Promise<{ policyId?: string; policyGroupId?: string }> {
if (templateLevel === 'CLIENT') return {}
const windowMs = 40 * 86400 * 1000
const from = new Date(effectiveDate.getTime() - windowMs)
const to = new Date(effectiveDate.getTime() + windowMs)
if (templateLevel === 'RENEWAL_GROUP' || templateLevel === 'BOTH') {
const group = await prisma.policyGroup.findFirst({
where: { clientId, renewalDate: { gte: from, lte: to } },
orderBy: { renewalDate: 'asc' },
const groups = await prisma.policyGroup.findMany({
where: { clientId },
select: { id: true, renewalDate: true },
})
if (group) return { policyGroupId: group.id }
if (groups.length > 0) {
const best = groups.reduce((a, b) =>
Math.abs(new Date(a.renewalDate).getTime() - effectiveDate.getTime()) <=
Math.abs(new Date(b.renewalDate).getTime() - effectiveDate.getTime()) ? a : b
)
return { policyGroupId: best.id }
}
}
if (templateLevel === 'POLICY' || templateLevel === 'BOTH') {
const policies = await prisma.policy.findMany({
where: {
clientId,
expirationDate: { gte: new Date(from.getTime() - 86400 * 1000), lte: new Date(to.getTime() - 86400 * 1000) },
status: { notIn: ['Cancelled', 'Non-Renewed', 'Rewritten', 'Not taken'] as any[] },
},
select: { id: true, expirationDate: true, policyGroupId: true },
orderBy: { expirationDate: 'asc' },
})
if (policies.length > 0) {
const best = policies.reduce((a, b) => {