Detect social milestones when scans arrive

This commit is contained in:
2026-08-14 11:47:28 +02:00
parent 6081b9e6ae
commit e0c32542f9
3 changed files with 49 additions and 40 deletions

View File

@@ -1,6 +1,6 @@
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { getSocialMilestoneThresholds, milestoneKind } from '@/lib/social-milestones';
import { detectSocialMilestones } from '@/lib/social-milestones-server';
import { getSocialMilestoneThresholds } from '@/lib/social-milestones';
export const dynamic = 'force-dynamic';
@@ -9,45 +9,9 @@ function isAuthorized(request: NextRequest) {
return Boolean(secret) && request.headers.get('authorization') === `Bearer ${secret}`;
}
function excludedEmails() {
return (process.env.SOCIAL_MILESTONE_EXCLUDED_EMAILS || '')
.split(',').map(email => email.trim().toLowerCase()).filter(Boolean);
}
// Detection only: this route never contacts customers or an external network.
export async function GET(request: NextRequest) {
if (!isAuthorized(request)) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
const excluded = excludedEmails();
const thresholds = getSocialMilestoneThresholds();
const candidates = await db.qRScan.groupBy({
by: ['qrId'],
where: {
isUnique: true,
qr: { user: excluded.length ? { email: { notIn: excluded, mode: 'insensitive' } } : undefined },
},
_count: { _all: true },
});
const records = candidates.flatMap(({ qrId, _count }) =>
thresholds
.filter(threshold => _count._all >= threshold)
.map(threshold => ({ qrId, kind: milestoneKind(threshold) }))
);
if (records.length) {
const qrs = await db.qRCode.findMany({
where: { id: { in: Array.from(new Set(records.map(record => record.qrId))) } },
select: { id: true, userId: true },
});
const userIdByQr = new Map(qrs.map(qr => [qr.id, qr.userId]));
await db.socialMilestone.createMany({
data: records
.filter(record => userIdByQr.has(record.qrId))
.map(record => ({ ...record, userId: userIdByQr.get(record.qrId)! })),
skipDuplicates: true,
});
}
return NextResponse.json({ ok: true, detected: records.length, thresholds });
const detected = await detectSocialMilestones();
return NextResponse.json({ ok: true, detected, thresholds: getSocialMilestoneThresholds() });
}

View File

@@ -5,6 +5,7 @@ import { getWwwOrigin } from '@/lib/hosts';
import { db } from '@/lib/db';
import { hashIP } from '@/lib/hash';
import { triggerLifecycleScoring } from '@/lib/revops-server';
import { detectSocialMilestones } from '@/lib/social-milestones-server';
export async function GET(
request: NextRequest,
@@ -260,6 +261,12 @@ async function trackScan(qrId: string, userId: string, request: NextRequest) {
},
});
// The customer sees a newly crossed milestone on their next dashboard
// visit; no separate cron invocation is required after a real scan.
if (isUnique) {
await detectSocialMilestones(qrId);
}
const activatedUsers = await db.user.updateMany({
where: {
id: userId,

View File

@@ -0,0 +1,38 @@
import { db } from '@/lib/db';
import { getSocialMilestoneThresholds, milestoneKind } from '@/lib/social-milestones';
function excludedEmails() {
return (process.env.SOCIAL_MILESTONE_EXCLUDED_EMAILS || '')
.split(',').map(email => email.trim().toLowerCase()).filter(Boolean);
}
/** Creates any newly crossed milestones. Safe to call repeatedly. */
export async function detectSocialMilestones(qrId?: string) {
const excluded = excludedEmails();
const candidates = await db.qRScan.groupBy({
by: ['qrId'],
where: {
isUnique: true,
...(qrId ? { qrId } : {}),
qr: { user: excluded.length ? { email: { notIn: excluded, mode: 'insensitive' } } : undefined },
},
_count: { _all: true },
});
const records = candidates.flatMap(({ qrId: candidateQrId, _count }) =>
getSocialMilestoneThresholds()
.filter(threshold => _count._all >= threshold)
.map(threshold => ({ qrId: candidateQrId, kind: milestoneKind(threshold) }))
);
if (!records.length) return 0;
const qrs = await db.qRCode.findMany({
where: { id: { in: Array.from(new Set(records.map(record => record.qrId))) } },
select: { id: true, userId: true },
});
const userIdByQr = new Map(qrs.map(qr => [qr.id, qr.userId]));
const created = await db.socialMilestone.createMany({
data: records.filter(record => userIdByQr.has(record.qrId)).map(record => ({ ...record, userId: userIdByQr.get(record.qrId)! })),
skipDuplicates: true,
});
return created.count;
}