Add consented social milestone posting

This commit is contained in:
2026-08-14 09:03:10 +02:00
parent 14c429ff30
commit f7d82aa5bd
14 changed files with 613 additions and 3 deletions

View File

@@ -0,0 +1,53 @@
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { getSocialMilestoneThresholds, milestoneKind } from '@/lib/social-milestones';
export const dynamic = 'force-dynamic';
function isAuthorized(request: NextRequest) {
const secret = process.env.CRON_SECRET;
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 });
}