|
| 1 | +import { useEffect, useRef } from "react" |
| 2 | +import { useAccount } from "jazz-tools/react" |
| 3 | +import { |
| 4 | + Group, |
| 5 | + generateAuthToken, |
| 6 | + type co, |
| 7 | + type ResolveQuery, |
| 8 | +} from "jazz-tools" |
| 9 | +import { PUBLIC_JAZZ_WORKER_ACCOUNT } from "astro:env/client" |
| 10 | +import { UserAccount } from "#shared/schema/user" |
| 11 | +import { tryCatch } from "#shared/lib/trycatch" |
| 12 | +import { |
| 13 | + migrateNotificationSettings, |
| 14 | + addServerToGroup, |
| 15 | +} from "#app/lib/notification-settings-migration" |
| 16 | +import { triggerNotificationRegistration } from "#app/lib/notification-registration" |
| 17 | +import { findLatestFutureDate } from "#app/lib/reminder-utils" |
| 18 | + |
| 19 | +export { useRegisterNotifications } |
| 20 | + |
| 21 | +let notificationSettingsQuery = { |
| 22 | + root: { |
| 23 | + notificationSettings: true, |
| 24 | + people: { $each: { reminders: { $each: true } } }, |
| 25 | + }, |
| 26 | +} as const satisfies ResolveQuery<typeof UserAccount> |
| 27 | + |
| 28 | +type LoadedAccount = co.loaded< |
| 29 | + typeof UserAccount, |
| 30 | + typeof notificationSettingsQuery |
| 31 | +> |
| 32 | + |
| 33 | +/** |
| 34 | + * Hook that registers notification settings with the server. |
| 35 | + * Handles migration from account-owned to group-owned settings. |
| 36 | + * Runs once on app start. |
| 37 | + */ |
| 38 | +function useRegisterNotifications(): void { |
| 39 | + let registrationRan = useRef(false) |
| 40 | + let me = useAccount(UserAccount, { resolve: notificationSettingsQuery }) |
| 41 | + |
| 42 | + useEffect(() => { |
| 43 | + if (registrationRan.current || !me.$isLoaded) return |
| 44 | + if (!me.root.notificationSettings) return |
| 45 | + |
| 46 | + registrationRan.current = true |
| 47 | + registerNotificationSettings(me).catch(error => { |
| 48 | + console.error("[Notifications] Registration error:", error) |
| 49 | + registrationRan.current = false |
| 50 | + }) |
| 51 | + }, [me.$isLoaded, me]) |
| 52 | +} |
| 53 | + |
| 54 | +async function registerNotificationSettings(me: LoadedAccount): Promise<void> { |
| 55 | + let notificationSettings = me.root.notificationSettings |
| 56 | + if (!notificationSettings) return |
| 57 | + |
| 58 | + let serverAccountId = PUBLIC_JAZZ_WORKER_ACCOUNT |
| 59 | + if (!serverAccountId) { |
| 60 | + console.error("[Notifications] PUBLIC_JAZZ_WORKER_ACCOUNT not configured") |
| 61 | + return |
| 62 | + } |
| 63 | + |
| 64 | + // Sync language from root to notification settings |
| 65 | + let rootLanguage = me.root.language |
| 66 | + if (rootLanguage && notificationSettings.language !== rootLanguage) { |
| 67 | + notificationSettings.$jazz.set("language", rootLanguage) |
| 68 | + } |
| 69 | + |
| 70 | + // Compute and sync latestReminderDueDate |
| 71 | + let latestDueDate = computeLatestReminderDueDate(me) |
| 72 | + if (latestDueDate !== notificationSettings.latestReminderDueDate) { |
| 73 | + notificationSettings.$jazz.set("latestReminderDueDate", latestDueDate) |
| 74 | + } |
| 75 | + |
| 76 | + // Check if settings are owned by a shareable group |
| 77 | + // The key difference: if owner is an Account vs a Group |
| 78 | + let owner = notificationSettings.$jazz.owner |
| 79 | + let isShareableGroup = owner instanceof Group |
| 80 | + |
| 81 | + if (!isShareableGroup) { |
| 82 | + console.log("[Notifications] Migrating to shareable group") |
| 83 | + let migrationResult = await tryCatch( |
| 84 | + migrateNotificationSettings(notificationSettings, serverAccountId, { |
| 85 | + loadAs: me, |
| 86 | + rootLanguage, |
| 87 | + }), |
| 88 | + ) |
| 89 | + if (!migrationResult.ok) { |
| 90 | + console.error("[Notifications] Migration failed:", migrationResult.error) |
| 91 | + return |
| 92 | + } |
| 93 | + let { newSettings, cleanup } = migrationResult.data |
| 94 | + // Update root to point to new settings before cleanup |
| 95 | + me.root.$jazz.set("notificationSettings", newSettings) |
| 96 | + // Defer cleanup to next tick so new settings are persisted first |
| 97 | + setTimeout(cleanup, 0) |
| 98 | + notificationSettings = newSettings |
| 99 | + console.log("[Notifications] Migration complete") |
| 100 | + } else { |
| 101 | + // Ensure server worker is a member |
| 102 | + let group = owner as Group |
| 103 | + let serverIsMember = group.members.some( |
| 104 | + m => m.account?.$jazz.id === serverAccountId, |
| 105 | + ) |
| 106 | + if (!serverIsMember) { |
| 107 | + let addResult = await tryCatch( |
| 108 | + addServerToGroup(group, serverAccountId, { loadAs: me }), |
| 109 | + ) |
| 110 | + if (!addResult.ok) { |
| 111 | + console.error( |
| 112 | + "[Notifications] Failed to add server to group:", |
| 113 | + addResult.error, |
| 114 | + ) |
| 115 | + } |
| 116 | + } |
| 117 | + } |
| 118 | + |
| 119 | + // Register with server using Jazz auth |
| 120 | + let authToken = generateAuthToken(me) |
| 121 | + let registerResult = await triggerNotificationRegistration( |
| 122 | + notificationSettings.$jazz.id, |
| 123 | + authToken, |
| 124 | + ) |
| 125 | + |
| 126 | + if (!registerResult.ok) { |
| 127 | + console.error("[Notifications] Registration failed:", registerResult.error) |
| 128 | + return |
| 129 | + } |
| 130 | + |
| 131 | + console.log("[Notifications] Registration successful") |
| 132 | +} |
| 133 | + |
| 134 | +function computeLatestReminderDueDate(me: LoadedAccount): string | undefined { |
| 135 | + let reminders = extractReminders(me) |
| 136 | + let timezone = |
| 137 | + me.root.notificationSettings?.timezone || |
| 138 | + Intl.DateTimeFormat().resolvedOptions().timeZone |
| 139 | + let today = new Date() |
| 140 | + .toLocaleDateString("sv-SE", { timeZone: timezone }) |
| 141 | + .slice(0, 10) |
| 142 | + return findLatestFutureDate(reminders, today) |
| 143 | +} |
| 144 | + |
| 145 | +function extractReminders( |
| 146 | + me: LoadedAccount, |
| 147 | +): { dueAtDate: string; deleted: boolean; done: boolean }[] { |
| 148 | + let reminders: { dueAtDate: string; deleted: boolean; done: boolean }[] = [] |
| 149 | + for (let person of me.root.people.values()) { |
| 150 | + if (!person || person.deletedAt) continue |
| 151 | + for (let reminder of person.reminders.values()) { |
| 152 | + if (!reminder) continue |
| 153 | + reminders.push({ |
| 154 | + dueAtDate: reminder.dueAtDate, |
| 155 | + deleted: !!reminder.deletedAt, |
| 156 | + done: !!reminder.done, |
| 157 | + }) |
| 158 | + } |
| 159 | + } |
| 160 | + return reminders |
| 161 | +} |
0 commit comments