|
1 | 1 | import "dotenv/config"; //must be first to load environment variables |
2 | | -import { randomUUID } from "node:crypto"; |
3 | 2 | import { EventVisibility, JoinRequestStatus, schema } from "../lib/schema"; |
4 | 3 | import db from "../lib/db"; |
5 | 4 | import { auth } from "@/lib/auth"; |
@@ -580,15 +579,33 @@ export async function main() { |
580 | 579 |
|
581 | 580 | for (const email of memberEmails) { |
582 | 581 | for (const org of ORGS) { |
583 | | - const notificationValues = notificationTemplates.map((tmpl) => ({ |
584 | | - id: randomUUID(), |
585 | | - userId: userIdsByOrganization.get(org.id)!.get(email)!, |
586 | | - organizationId: org.id, |
587 | | - type: tmpl.type, |
588 | | - text: tmpl.text, |
589 | | - read: tmpl.read, |
590 | | - createdAt: new Date(Date.now() - tmpl.minutesAgo * 60 * 1000), |
591 | | - })); |
| 582 | + const userId = userIdsByOrganization.get(org.id)!.get(email)!; |
| 583 | + // Skip the ones the user already has. Seeds before the IDs below were |
| 584 | + // stable gave them random IDs, which onConflictDoNothing can't match. |
| 585 | + const existing = await db |
| 586 | + .select({ text: schema.notifications.text }) |
| 587 | + .from(schema.notifications) |
| 588 | + .where( |
| 589 | + and( |
| 590 | + eq(schema.notifications.userId, userId), |
| 591 | + eq(schema.notifications.organizationId, org.id), |
| 592 | + ), |
| 593 | + ); |
| 594 | + const existingTexts = new Set(existing.map((row) => row.text)); |
| 595 | + const notificationValues = notificationTemplates |
| 596 | + .map((tmpl, index) => ({ |
| 597 | + // Stable, so a seed running at the same time hits |
| 598 | + // onConflictDoNothing instead of inserting a second copy. |
| 599 | + id: `notif_${org.id}_${userId}_${index}`, |
| 600 | + userId, |
| 601 | + organizationId: org.id, |
| 602 | + type: tmpl.type, |
| 603 | + text: tmpl.text, |
| 604 | + read: tmpl.read, |
| 605 | + createdAt: new Date(Date.now() - tmpl.minutesAgo * 60 * 1000), |
| 606 | + })) |
| 607 | + .filter((notification) => !existingTexts.has(notification.text)); |
| 608 | + if (notificationValues.length === 0) continue; |
592 | 609 |
|
593 | 610 | await db |
594 | 611 | .insert(schema.notifications) |
|
0 commit comments