diff --git a/ondeck/src/lib/shape-import/run-import.ts b/ondeck/src/lib/shape-import/run-import.ts index 5f18f63..4ab5c28 100644 --- a/ondeck/src/lib/shape-import/run-import.ts +++ b/ondeck/src/lib/shape-import/run-import.ts @@ -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) => {