diff --git a/README.md b/README.md index e57d5279..b60507cf 100644 --- a/README.md +++ b/README.md @@ -421,6 +421,8 @@ The notification then says the command was sent or the service logged. When it c Settings > Notifications has a push switch for the device you are on and a per-type checklist for these alerts, which offers only the types the car's drivetrain can produce: the plug-in alerts (low EV battery, charging complete, charging interrupted) are left out for a plain hybrid, low fuel for a full electric car, and the RDW type (APK, recalls and insurance) wherever `RDW_ENABLED` is off. Both are kept per device: a type switched off on your phone still reaches your laptop, and still shows up in the notification panel. The weekly and monthly summaries are the other way round: a device gets them, in push and in its notification panel, only once it has switched them on, and **All on** and **All off** leave them as they are. Only the switch turns push on or off; the checklist never asks the browser for permission. +With two or more cars on the account, a **Car** picker above the checklist chooses whether it is for all cars or for one. A type switched off for one car stays on for the others, and a type switched off for all cars stays off for every car, which a car's own list shows as locked. The list for all cars offers every type any of the cars can produce, and a car's own list the types that car can. Like the rest of the checklist, the choice is kept per device, so a phone can mute the doors of one car while a laptop hears about both. A notification that belongs to no car, such as a failed MG sign-in, follows the list for all cars. The summaries are asked for once, for the device, and can then be switched off for a single car. + Notification texts are written by the background worker, which has no browser to take a language from, so their language is a deployment setting: `NOTIFICATION_LANGUAGE=en` (default), `nl`, `es` or `pt`. The web UI's language selection does not affect them. MG app messages are the exception: they are passed on as SAIC wrote them, in the language of your MG account. Each one is sent once, even though the gateway repeats its latest message every time it starts, because GarageStack remembers which message it last saw. Two kinds are left out: the "vehicle started" message, which the engine started alert already covers, and any message sent more than a day ago, so a new install does not announce whatever the account last received. A message that arrives while the worker is not running is not sent afterwards. diff --git a/documentation/openapi.json b/documentation/openapi.json index a33483e2..0a73a659 100644 --- a/documentation/openapi.json +++ b/documentation/openapi.json @@ -9023,6 +9023,18 @@ "items": { "type": "string" } + }, + "excludedCategoriesByVehicle": { + "type": [ + "null", + "object" + ], + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + } } } }, diff --git a/frontend/src/assets/settings.css b/frontend/src/assets/settings.css index 2c94a285..324a7b4e 100644 --- a/frontend/src/assets/settings.css +++ b/frontend/src/assets/settings.css @@ -147,6 +147,19 @@ line-height: 1.25; } +/* A type switched off for all cars, shown under one car: off, and not the car's to change. */ +.notif-type-checklist__item--locked { + cursor: default; +} + +.notif-type-checklist__item--locked:hover { + background: transparent; +} + +.notif-type-checklist__note { + display: block; +} + /* ── Settings tabs ────────────────────────────────────────── */ /* The row sits beside the dialog title and scrolls sideways where it does not fit. Its width, diff --git a/frontend/src/components/settings/NotificationTypeSettings.vue b/frontend/src/components/settings/NotificationTypeSettings.vue index 9343a2bb..01b53a6e 100644 --- a/frontend/src/components/settings/NotificationTypeSettings.vue +++ b/frontend/src/components/settings/NotificationTypeSettings.vue @@ -1,17 +1,22 @@ diff --git a/frontend/src/components/settings/__tests__/NotificationTypeSettings.spec.ts b/frontend/src/components/settings/__tests__/NotificationTypeSettings.spec.ts index 639f7d79..6514038d 100644 --- a/frontend/src/components/settings/__tests__/NotificationTypeSettings.spec.ts +++ b/frontend/src/components/settings/__tests__/NotificationTypeSettings.spec.ts @@ -1,13 +1,20 @@ import { describe, it, expect, vi, beforeEach } from 'vitest' -import { ref } from 'vue' +import { reactive, ref } from 'vue' import { shallowMount } from '@vue/test-utils' import { createI18n } from 'vue-i18n' import NotificationTypeSettings from '../NotificationTypeSettings.vue' +import type { Vehicle } from '@/services/vehicleApi' const vehicleType = vi.hoisted(() => ({ value: 'unknown' as string })) +const cars = vi.hoisted(() => ({ value: [] as Vehicle[] })) + vi.mock('@/stores/vehicle', () => ({ - useVehicleStore: () => ({ effectiveVehicleType: vehicleType.value }), + useVehicleStore: () => ({ + effectiveVehicleType: vehicleType.value, + vehicles: cars.value, + hasMultipleVehicles: cars.value.length > 1, + }), })) const rdwAvailable = vi.hoisted(() => ({ value: null as boolean | null })) @@ -16,13 +23,15 @@ vi.mock('@/stores/rdw', () => ({ useRdwStore: () => ({ available: rdwAvailable.value }), })) +// Reactive, so a row follows the choice made in it as it does in the app. vi.mock('@/stores/settingsUi', () => ({ - useUiSettingsStore: () => settingsStub, + useUiSettingsStore: () => reactive(settingsStub), })) const settingsStub = vi.hoisted(() => ({ notificationTypeExclusions: [] as string[], notificationTypeInclusions: [] as string[], + notificationTypeExclusionsByVehicle: {} as Record, })) const pushSupported = vi.hoisted(() => ({ value: true })) @@ -42,7 +51,7 @@ const i18n = createI18n({ legacy: false, locale: 'en', missingWarn: false, fallb function mountSettings() { // The rows render for real: the switch and the checklist are their slot content. return shallowMount(NotificationTypeSettings, { - global: { plugins: [i18n], stubs: { SettingsToggle: false } }, + global: { plugins: [i18n], stubs: { SettingsToggle: false, SettingsSelect: false } }, }) } @@ -59,6 +68,8 @@ describe('NotificationTypeSettings', () => { rdwAvailable.value = null settingsStub.notificationTypeExclusions = [] settingsStub.notificationTypeInclusions = [] + settingsStub.notificationTypeExclusionsByVehicle = {} + cars.value = [] }) function summarySwitch(wrapper: ReturnType, key: string) { @@ -157,3 +168,167 @@ describe('NotificationTypeSettings', () => { vi.unstubAllGlobals() }) }) + +describe('NotificationTypeSettings with more than one car', () => { + const MG4 = { id: 1, vin: 'FAKEVN00000000001', model: 'MG4', vehicleType: 'bev' } as Vehicle + const HS = { id: 2, vin: 'FAKEVN00000000002', model: 'MG HS', vehicleType: 'hev' } as Vehicle + + beforeEach(() => { + vehicleType.value = 'unknown' + pushSupported.value = true + rdwAvailable.value = null + settingsStub.notificationTypeExclusions = [] + settingsStub.notificationTypeInclusions = [] + settingsStub.notificationTypeExclusionsByVehicle = {} + cars.value = [MG4, HS] + }) + + function row(wrapper: ReturnType, key: string) { + return wrapper + .findAll('.notif-type-checklist__item') + .find((item) => item.text().startsWith(`notifications.categories.${key}`))! + } + + function checked(wrapper: ReturnType, key: string) { + return row(wrapper, key).get('input').element.checked + } + + function disabled(wrapper: ReturnType, key: string) { + return row(wrapper, key).get('input').element.disabled + } + + async function pickScope(wrapper: ReturnType, value: string) { + await wrapper.get('#settings-notification-scope').setValue(value) + } + + it('offers no car picker with a single car', () => { + cars.value = [MG4] + + expect(mountSettings().find('#settings-notification-scope').exists()).toBe(false) + }) + + it('offers all cars and then each car, named as the app names them', () => { + const options = mountSettings() + .findAll('#settings-notification-scope option') + .map((option) => [option.attributes('value'), option.text()]) + + expect(options).toEqual([ + ['all', 'notifications.scopeAll'], + ['1', 'MG4'], + ['2', 'MG HS'], + ]) + }) + + it('keeps what a car switches off to that car, and leaves the device list alone', async () => { + const wrapper = mountSettings() + await pickScope(wrapper, '2') + + await row(wrapper, 'doorsOpenParked').get('input').setValue(false) + + expect(settingsStub.notificationTypeExclusionsByVehicle).toEqual({ '2': ['doors-open-parked'] }) + expect(settingsStub.notificationTypeExclusions).toEqual([]) + await pickScope(wrapper, '1') + expect(checked(wrapper, 'doorsOpenParked')).toBe(true) + await pickScope(wrapper, '2') + expect(checked(wrapper, 'doorsOpenParked')).toBe(false) + }) + + // A car with nothing off is the same as one the device never chose for. + it('drops the car from the choice once nothing is off for it', async () => { + settingsStub.notificationTypeExclusionsByVehicle = { '1': ['low-tyre'], '2': ['engine-start'] } + const wrapper = mountSettings() + await pickScope(wrapper, '2') + + await row(wrapper, 'engineStart').get('input').setValue(true) + + expect(settingsStub.notificationTypeExclusionsByVehicle).toEqual({ '1': ['low-tyre'] }) + }) + + // Off for all cars wins, so a car cannot switch it back on: the row says why instead. + it('shows a type switched off for all cars as off and locked under a car', async () => { + settingsStub.notificationTypeExclusions = ['engine-start'] + const wrapper = mountSettings() + await pickScope(wrapper, '1') + + expect(checked(wrapper, 'engineStart')).toBe(false) + expect(disabled(wrapper, 'engineStart')).toBe(true) + expect(row(wrapper, 'engineStart').text()).toContain('notifications.offForAllCars') + expect(row(wrapper, 'lowTyre').text()).not.toContain('notifications.offForAllCars') + }) + + it('does not lock anything for all cars', () => { + settingsStub.notificationTypeExclusions = ['engine-start'] + const wrapper = mountSettings() + + expect(disabled(wrapper, 'engineStart')).toBe(false) + expect(wrapper.text()).not.toContain('notifications.offForAllCars') + }) + + it('applies "deselect all" and "select all" to the picked car alone', async () => { + settingsStub.notificationTypeExclusions = ['low-tyre'] + settingsStub.notificationTypeExclusionsByVehicle = { '1': ['maintenance'] } + const wrapper = mountSettings() + await pickScope(wrapper, '2') + const [allOn, allOff] = wrapper.findAll('.notif-type-filter__actions button') + + await allOff!.trigger('click') + expect(settingsStub.notificationTypeExclusionsByVehicle['1']).toEqual(['maintenance']) + expect(settingsStub.notificationTypeExclusionsByVehicle['2']).toContain('engine-start') + expect(settingsStub.notificationTypeExclusionsByVehicle['2']).not.toContain('weekly-summary') + expect(settingsStub.notificationTypeExclusions).toEqual(['low-tyre']) + + await allOn!.trigger('click') + expect(settingsStub.notificationTypeExclusionsByVehicle).toEqual({ '1': ['maintenance'] }) + expect(settingsStub.notificationTypeExclusions).toEqual(['low-tyre']) + }) + + // The summaries are asked for once, for the device; a car can only switch one off for itself. + it('switches a summary off for one car without turning it off for the device', async () => { + settingsStub.notificationTypeInclusions = ['weekly-summary'] + const wrapper = mountSettings() + await pickScope(wrapper, '1') + + expect(checked(wrapper, 'weeklySummary')).toBe(true) + await row(wrapper, 'weeklySummary').get('input').setValue(false) + + expect(settingsStub.notificationTypeExclusionsByVehicle).toEqual({ '1': ['weekly-summary'] }) + expect(settingsStub.notificationTypeInclusions).toEqual(['weekly-summary']) + }) + + it('shows a summary the device has not asked for as locked under a car', async () => { + const wrapper = mountSettings() + await pickScope(wrapper, '1') + + expect(disabled(wrapper, 'weeklySummary')).toBe(true) + }) + + // The MG sign-in failing is about the account and names no car, so a car has nothing to switch off. + it("leaves the MG sign-in alert out of a car's own list, and keeps it for all cars", async () => { + const wrapper = mountSettings() + const names = () => wrapper.findAll('.notif-type-checklist__label').map((el) => el.text()) + expect(names()).toContain('notifications.categories.gatewayLogin') + + await pickScope(wrapper, '1') + expect(names()).not.toContain('notifications.categories.gatewayLogin') + + await pickScope(wrapper, 'all') + expect(names()).toContain('notifications.categories.gatewayLogin') + }) + + // A BEV never burns fuel and a plain hybrid never charges: one car's list offers what it can do, + // and the list for all cars what either can. + it('offers each car the types its drivetrain can produce, and all cars what either can', async () => { + const wrapper = mountSettings() + const names = () => wrapper.findAll('.notif-type-checklist__label').map((el) => el.text()) + expect(names()).toContain('notifications.categories.lowEv') + expect(names()).toContain('notifications.categories.lowFuel') + + await pickScope(wrapper, '1') + expect(names()).toContain('notifications.categories.lowEv') + expect(names()).not.toContain('notifications.categories.lowFuel') + + await pickScope(wrapper, '2') + expect(names()).toContain('notifications.categories.lowFuel') + expect(names()).not.toContain('notifications.categories.lowEv') + }) +}) diff --git a/frontend/src/composables/__tests__/useBrowserNotifications.spec.ts b/frontend/src/composables/__tests__/useBrowserNotifications.spec.ts index 70742dc4..89be035a 100644 --- a/frontend/src/composables/__tests__/useBrowserNotifications.spec.ts +++ b/frontend/src/composables/__tests__/useBrowserNotifications.spec.ts @@ -88,6 +88,18 @@ describe('useBrowserNotifications', () => { expect(shown).toEqual([]) }) + it('stays quiet for a type switched off for the car it is about, and only for that car', async () => { + stubNotification('granted') + stubPushSubscription(false) + useUiSettingsStore().notificationTypeExclusionsByVehicle = { '2': ['doors-open-parked'] } + + await useBrowserNotifications().show({ ...doorLeftOpen, vehicleId: 2 }) + expect(shown).toEqual([]) + + await useBrowserNotifications().show({ ...doorLeftOpen, vehicleId: 1 }) + expect(shown).toHaveLength(1) + }) + it('stays quiet until the user has allowed notifications', async () => { stubNotification('default') stubPushSubscription(false) diff --git a/frontend/src/composables/__tests__/useNotificationPushSync.spec.ts b/frontend/src/composables/__tests__/useNotificationPushSync.spec.ts index a9410172..40e84bcb 100644 --- a/frontend/src/composables/__tests__/useNotificationPushSync.spec.ts +++ b/frontend/src/composables/__tests__/useNotificationPushSync.spec.ts @@ -7,10 +7,14 @@ const mockSyncExclusions = vi.fn<() => Promise>() const mockPushState = ref<'unknown' | 'subscribed' | 'unsubscribed' | 'denied'>('unknown') const mockPushError = ref(false) let mockPushSupported = true -let passedOptions: { excludedCategories?: () => readonly string[] } | undefined +type PushOptions = { + excludedCategories?: () => readonly string[] + excludedCategoriesByVehicle?: () => Readonly> +} +let passedOptions: PushOptions | undefined vi.mock('@/composables/usePush', () => ({ - usePush: (options?: { excludedCategories?: () => readonly string[] }) => { + usePush: (options?: PushOptions) => { passedOptions = options return { pushSupported: mockPushSupported, @@ -117,8 +121,42 @@ describe('useNotificationPushSync', () => { const { settings } = await setUp() settings.notificationTypeExclusions = ['maintenance'] + settings.notificationTypeExclusionsByVehicle = { '2': ['low-tyre'] } expect(passedOptions?.excludedCategories?.()).toEqual(['maintenance']) + expect(passedOptions?.excludedCategoriesByVehicle?.()).toEqual({ '2': ['low-tyre'] }) + }) + + it('tells the server whenever a car has a different set of types switched off', async () => { + mockPushState.value = 'subscribed' + const { settings } = await setUp() + + settings.notificationTypeExclusionsByVehicle = { '2': ['low-tyre'] } + await nextTick() + settings.notificationTypeExclusionsByVehicle = { '2': ['low-tyre'], '3': ['engine-start'] } + await nextTick() + settings.notificationTypeExclusionsByVehicle = {} + await nextTick() + + expect(mockSyncExclusions).toHaveBeenCalledTimes(3) + }) + + it('leaves the server alone when the same car types arrive in another order', async () => { + localStorage.setItem( + 'garagestack-settings-ui', + JSON.stringify({ + notificationTypeExclusionsByVehicle: { '2': ['low-tyre', 'engine-start'], '3': ['rdw'] }, + }), + ) + const { settings } = await setUp() + + settings.notificationTypeExclusionsByVehicle = { + '3': ['rdw'], + '2': ['engine-start', 'low-tyre'], + } + await nextTick() + + expect(mockSyncExclusions).not.toHaveBeenCalled() }) it('registers no push side effects when pushSupported is false', async () => { diff --git a/frontend/src/composables/__tests__/useNotifications.spec.ts b/frontend/src/composables/__tests__/useNotifications.spec.ts index 50382fd1..88980ab9 100644 --- a/frontend/src/composables/__tests__/useNotifications.spec.ts +++ b/frontend/src/composables/__tests__/useNotifications.spec.ts @@ -216,6 +216,65 @@ describe('useNotifications', () => { expect(notifications.value.map((n) => n.id).sort()).toEqual([1, 2]) }) + it('hides a type only for the car it is switched off for', async () => { + localStorage.setItem( + 'garagestack-settings-ui', + JSON.stringify({ notificationTypeExclusionsByVehicle: { '2': ['doors-open-parked'] } }), + ) + vi.mocked(notificationsApi.list).mockResolvedValue([ + makeNotification({ id: 1, category: 'doors-open-parked', vehicleId: 1 }), + makeNotification({ id: 2, category: 'doors-open-parked', vehicleId: 2 }), + makeNotification({ id: 3, category: 'low-tyre', vehicleId: 2 }), + ]) + + const { useNotifications } = await import('@/composables/useNotifications') + const { fetchNotifications, notifications, unreadCount } = useNotifications() + await fetchNotifications() + + expect(notifications.value.map((n) => n.id)).toEqual([1, 3]) + expect(unreadCount.value).toBe(2) + }) + + it('keeps a type out for every car when the device has it off, whatever a car says', async () => { + localStorage.setItem( + 'garagestack-settings-ui', + JSON.stringify({ + notificationTypeExclusions: ['engine-start'], + notificationTypeExclusionsByVehicle: { '1': ['low-tyre'] }, + }), + ) + vi.mocked(notificationsApi.list).mockResolvedValue([ + makeNotification({ id: 1, category: 'engine-start', vehicleId: 1 }), + makeNotification({ id: 2, category: 'engine-start', vehicleId: 2 }), + makeNotification({ id: 3, category: 'low-tyre', vehicleId: 1 }), + makeNotification({ id: 4, category: 'low-tyre', vehicleId: 2 }), + ]) + + const { useNotifications } = await import('@/composables/useNotifications') + const { fetchNotifications, notifications } = useNotifications() + await fetchNotifications() + + expect(notifications.value.map((n) => n.id)).toEqual([4]) + }) + + // A notification about no car answers to the device's own list alone. + it('shows a notification without a car whatever a car has off', async () => { + localStorage.setItem( + 'garagestack-settings-ui', + JSON.stringify({ notificationTypeExclusionsByVehicle: { '1': ['gateway-login'] } }), + ) + vi.mocked(notificationsApi.list).mockResolvedValue([ + makeNotification({ id: 1, category: 'gateway-login', vehicleId: null }), + makeNotification({ id: 2, category: 'gateway-login' }), + ]) + + const { useNotifications } = await import('@/composables/useNotifications') + const { fetchNotifications, notifications } = useNotifications() + await fetchNotifications() + + expect(notifications.value).toHaveLength(2) + }) + it('fetchNotifications() populates the notifications list', async () => { const items = [makeNotification({ id: 10 }), makeNotification({ id: 11 })] vi.mocked(notificationsApi.list).mockResolvedValue(items) diff --git a/frontend/src/composables/__tests__/usePush.spec.ts b/frontend/src/composables/__tests__/usePush.spec.ts index 9c999bed..2ea7e2d9 100644 --- a/frontend/src/composables/__tests__/usePush.spec.ts +++ b/frontend/src/composables/__tests__/usePush.spec.ts @@ -7,7 +7,17 @@ import { usePush, type UsePushOptions } from '@/composables/usePush' vi.mock('@/services/pushApi', () => ({ pushApi: { getVapidPublicKey: vi.fn<() => Promise<{ publicKey: string }>>(), - subscribe: vi.fn<(e: string, p: string, a: string, x?: readonly string[]) => Promise>(), + subscribe: + vi.fn< + ( + e: string, + p: string, + a: string, + x?: readonly string[], + i?: readonly string[], + v?: Readonly>, + ) => Promise + >(), unsubscribe: vi.fn<(e: string) => Promise>(), }, })) @@ -101,6 +111,7 @@ describe('usePush on load', () => { 'auth-key', undefined, undefined, + undefined, ) expect(pushManager.subscribe).not.toHaveBeenCalled() expect(api().pushState.value).toBe('subscribed') @@ -123,6 +134,7 @@ describe('usePush on load', () => { 'auth-key', undefined, undefined, + undefined, ) expect(api().pushState.value).toBe('subscribed') }) @@ -186,6 +198,7 @@ describe('usePush on load', () => { 'auth-key', undefined, undefined, + undefined, ) expect(api().pushState.value).toBe('subscribed') }) @@ -244,6 +257,7 @@ describe('usePush togglePush', () => { 'auth-key', undefined, undefined, + undefined, ) expect(api().pushState.value).toBe('subscribed') expect(api().pushError.value).toBe(false) @@ -280,6 +294,7 @@ describe('usePush and the types this device switched off', () => { 'auth-key', ['engine-start'], undefined, + undefined, ) }) @@ -299,6 +314,7 @@ describe('usePush and the types this device switched off', () => { 'auth-key', ['engine-start', 'maintenance'], undefined, + undefined, ) }) @@ -315,6 +331,47 @@ describe('usePush and the types this device switched off', () => { 'auth-key', [], ['weekly-summary'], + undefined, + ) + }) + + it('sends the types switched off for one car along with them', async () => { + pushManager.getSubscription.mockResolvedValue(makeSubscription()) + setPermission('granted') + + mountUsePush({ + excludedCategories: () => [], + excludedCategoriesByVehicle: () => ({ '2': ['doors-open-parked'] }), + }) + await flush() + + expect(subscribeMock).toHaveBeenCalledWith( + 'https://push.example/abc', + 'p256dh-key', + 'auth-key', + [], + undefined, + { '2': ['doors-open-parked'] }, + ) + }) + + it('registers the subscription again when a car changes', async () => { + pushManager.getSubscription.mockResolvedValue(makeSubscription()) + setPermission('granted') + let byVehicle: Record = { '2': ['doors-open-parked'] } + + const { api } = mountUsePush({ excludedCategoriesByVehicle: () => byVehicle }) + await flush() + byVehicle = {} + await api().syncExclusions() + + expect(subscribeMock).toHaveBeenLastCalledWith( + 'https://push.example/abc', + 'p256dh-key', + 'auth-key', + undefined, + undefined, + {}, ) }) diff --git a/frontend/src/composables/useBrowserNotifications.ts b/frontend/src/composables/useBrowserNotifications.ts index 464b584a..16d27098 100644 --- a/frontend/src/composables/useBrowserNotifications.ts +++ b/frontend/src/composables/useBrowserNotifications.ts @@ -1,6 +1,10 @@ import type { AppNotification } from '@/services/notificationsApi' import { useUiSettingsStore } from '@/stores/settingsUi' -import { isCategoryShown, notificationCategoryId } from '@/utils/notificationCategories' +import { + isCategoryShown, + notificationCategoryId, + vehicleExclusionsOf, +} from '@/utils/notificationCategories' import { useVehicleStore } from '@/stores/vehicle' import { titleWithCar } from '@/utils/vehicleLabels' @@ -32,6 +36,7 @@ export function useBrowserNotifications() { category, settings.notificationTypeExclusions, settings.notificationTypeInclusions, + vehicleExclusionsOf(settings.notificationTypeExclusionsByVehicle, notification.vehicleId), ) ) return diff --git a/frontend/src/composables/useNotificationPushSync.ts b/frontend/src/composables/useNotificationPushSync.ts index f43c0fda..87d9fc85 100644 --- a/frontend/src/composables/useNotificationPushSync.ts +++ b/frontend/src/composables/useNotificationPushSync.ts @@ -1,6 +1,15 @@ import { computed, watch } from 'vue' import { useUiSettingsStore } from '@/stores/settingsUi' import { usePush } from '@/composables/usePush' +import type { VehicleExclusions } from '@/utils/notificationCategories' + +// The types off for each car as one sorted string, whatever order they were switched in. +function vehicleExclusionsKey(byVehicle: VehicleExclusions): string { + return Object.keys(byVehicle) + .sort() + .map((vehicleId) => `${vehicleId}:${[...(byVehicle[vehicleId] ?? [])].sort().join()}`) + .join(';') +} // Keeps this device's push subscription in step with its settings. The push switch subscribes and // unsubscribes; the notification-type checklist only tells the server which types to leave out, @@ -10,6 +19,7 @@ export function useNotificationPushSync() { const { pushSupported, pushState, pushError, togglePush, syncExclusions } = usePush({ excludedCategories: () => settings.notificationTypeExclusions, includedCategories: () => settings.notificationTypeInclusions, + excludedCategoriesByVehicle: () => settings.notificationTypeExclusionsByVehicle, }) const showPermissionDeniedNotice = computed(() => pushSupported && pushState.value === 'denied') @@ -32,7 +42,7 @@ export function useNotificationPushSync() { // As a sorted string, so only a change in which types are off, or on, reaches the server. watch( () => - `${[...settings.notificationTypeExclusions].sort().join()}|${[...settings.notificationTypeInclusions].sort().join()}`, + `${[...settings.notificationTypeExclusions].sort().join()}|${[...settings.notificationTypeInclusions].sort().join()}|${vehicleExclusionsKey(settings.notificationTypeExclusionsByVehicle)}`, () => void syncExclusions(), ) } diff --git a/frontend/src/composables/useNotifications.ts b/frontend/src/composables/useNotifications.ts index c916945a..eecb674e 100644 --- a/frontend/src/composables/useNotifications.ts +++ b/frontend/src/composables/useNotifications.ts @@ -2,7 +2,11 @@ import { ref, computed, watch, onUnmounted, getCurrentInstance } from 'vue' import { notificationsApi, type AppNotification } from '@/services/notificationsApi' import { useAuthStore } from '@/stores/auth' import { useUiSettingsStore } from '@/stores/settingsUi' -import { isCategoryShown, notificationCategoryId } from '@/utils/notificationCategories' +import { + isCategoryShown, + notificationCategoryId, + vehicleExclusionsOf, +} from '@/utils/notificationCategories' import { asError } from '@/utils/errors' const notifications = ref([]) @@ -55,8 +59,14 @@ export function useNotifications() { const visibleNotifications = computed(() => { const excluded = uiSettings.notificationTypeExclusions const included = uiSettings.notificationTypeInclusions + const byVehicle = uiSettings.notificationTypeExclusionsByVehicle return notifications.value.filter((n) => - isCategoryShown(notificationCategoryId(n.category), excluded, included), + isCategoryShown( + notificationCategoryId(n.category), + excluded, + included, + vehicleExclusionsOf(byVehicle, n.vehicleId), + ), ) }) diff --git a/frontend/src/composables/usePush.ts b/frontend/src/composables/usePush.ts index f113bd7e..b3508d7d 100644 --- a/frontend/src/composables/usePush.ts +++ b/frontend/src/composables/usePush.ts @@ -1,5 +1,6 @@ import { ref, onMounted } from 'vue' import { pushApi } from '@/services/pushApi' +import type { VehicleExclusions } from '@/utils/notificationCategories' function urlBase64ToUint8Array(base64String: string): Uint8Array { const padding = '='.repeat((4 - (base64String.length % 4)) % 4) @@ -17,6 +18,8 @@ export interface UsePushOptions { excludedCategories?: () => readonly string[] /** The opt-in types this device switched on, which the server sends nobody until asked. */ includedCategories?: () => readonly string[] + /** The types this device switched off for one car only, by vehicle id. */ + excludedCategoriesByVehicle?: () => VehicleExclusions } export function usePush(options: UsePushOptions = {}) { @@ -37,6 +40,7 @@ export function usePush(options: UsePushOptions = {}) { json.keys?.['auth'] ?? '', options.excludedCategories?.(), options.includedCategories?.(), + options.excludedCategoriesByVehicle?.(), ) } diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.json index 63da8496..fdd57159 100644 --- a/frontend/src/locales/en.json +++ b/frontend/src/locales/en.json @@ -538,6 +538,10 @@ "typeFilterDesc": "Choose which notification types this device shows and gets pushed. The weekly and monthly summaries are off until you switch them on, and come only to a device with push on.", "selectAll": "Select all", "deselectAll": "Deselect all", + "scope": "Car", + "scopeDesc": "Choose which car the list below is for. A type switched off for all cars stays off for every car.", + "scopeAll": "All cars", + "offForAllCars": "Off for all cars", "categories": { "lowTyre": "Low tyre pressure", "highTyre": "High tyre pressure", diff --git a/frontend/src/locales/es.json b/frontend/src/locales/es.json index a14e8a3f..5c02a924 100644 --- a/frontend/src/locales/es.json +++ b/frontend/src/locales/es.json @@ -538,6 +538,10 @@ "typeFilterDesc": "Elija qué tipos de notificaciones muestra y recibe este dispositivo. Los resúmenes semanal y mensual están desactivados hasta que los actives, y solo llegan a un dispositivo con las notificaciones push activadas.", "selectAll": "Seleccionar todo", "deselectAll": "Deseleccionar todo", + "scope": "Coche", + "scopeDesc": "Elija para qué coche es la lista de abajo. Un tipo desactivado para todos los coches sigue desactivado para cada coche.", + "scopeAll": "Todos los coches", + "offForAllCars": "Desactivado para todos los coches", "categories": { "lowTyre": "Baja presión de neumáticos", "highTyre": "Alta presión de neumáticos", diff --git a/frontend/src/locales/nl.json b/frontend/src/locales/nl.json index bb54f4d7..26fa6fb6 100644 --- a/frontend/src/locales/nl.json +++ b/frontend/src/locales/nl.json @@ -538,6 +538,10 @@ "typeFilterDesc": "Kies welke meldingstypen dit apparaat toont en als pushmelding krijgt. Het week- en maandoverzicht staan uit tot je ze aanzet, en komen alleen op een apparaat met pushmeldingen aan.", "selectAll": "Alles selecteren", "deselectAll": "Alles deselecteren", + "scope": "Auto", + "scopeDesc": "Kies voor welke auto de lijst hieronder geldt. Een type dat voor alle auto’s uit staat, blijft voor elke auto uit.", + "scopeAll": "Alle auto’s", + "offForAllCars": "Uit voor alle auto’s", "categories": { "lowTyre": "Lage bandenspanning", "highTyre": "Hoge bandenspanning", diff --git a/frontend/src/locales/pt-PT.json b/frontend/src/locales/pt-PT.json index 6c373372..9a9e45de 100644 --- a/frontend/src/locales/pt-PT.json +++ b/frontend/src/locales/pt-PT.json @@ -538,6 +538,10 @@ "typeFilterDesc": "Escolha quais tipos de notificação este dispositivo mostra e recebe por push. Os resumos semanal e mensal ficam desligados até os ligar, e só chegam a um dispositivo com push ligado.", "selectAll": "Selecionar todas", "deselectAll": "Desmarcar todas", + "scope": "Carro", + "scopeDesc": "Escolha para que carro serve a lista abaixo. Um tipo desligado para todos os carros continua desligado em cada carro.", + "scopeAll": "Todos os carros", + "offForAllCars": "Desligado para todos os carros", "categories": { "lowTyre": "Pressão baixa dos pneus", "highTyre": "Pressão alta dos pneus", diff --git a/frontend/src/locales/pt.json b/frontend/src/locales/pt.json index 531e82dd..a5e079fd 100644 --- a/frontend/src/locales/pt.json +++ b/frontend/src/locales/pt.json @@ -538,6 +538,10 @@ "typeFilterDesc": "Escolha quais tipos de notificação este dispositivo mostra e recebe por push. Os resumos semanal e mensal ficam desligados até você ligá-los, e só chegam a um dispositivo com push ligado.", "selectAll": "Selecionar todas", "deselectAll": "Desmarcar todas", + "scope": "Carro", + "scopeDesc": "Escolha para qual carro vale a lista abaixo. Um tipo desligado para todos os carros continua desligado para cada carro.", + "scopeAll": "Todos os carros", + "offForAllCars": "Desligado para todos os carros", "categories": { "lowTyre": "Pressão baixa dos pneus", "highTyre": "Pressão alta dos pneus", diff --git a/frontend/src/services/pushApi.ts b/frontend/src/services/pushApi.ts index ee790878..431bbe91 100644 --- a/frontend/src/services/pushApi.ts +++ b/frontend/src/services/pushApi.ts @@ -1,14 +1,17 @@ import { request, send } from '@/services/apiCore' +import type { VehicleExclusions } from '@/utils/notificationCategories' export const pushApi = { getVapidPublicKey: () => request<{ publicKey: string }>('/api/push/vapid-public-key'), - // Left out, either list keeps whatever the server holds for this subscription. + // Left out, any of the lists keeps whatever the server holds for this subscription. + // excludedCategoriesByVehicle holds the types switched off for one car only, by vehicle id. subscribe: ( endpoint: string, p256DhKey: string, authKey: string, excludedCategories?: readonly string[], includedCategories?: readonly string[], + excludedCategoriesByVehicle?: VehicleExclusions, ) => send('/api/push/subscribe', 'POST', { endpoint, @@ -16,6 +19,7 @@ export const pushApi = { authKey, excludedCategories, includedCategories, + excludedCategoriesByVehicle, }), unsubscribe: (endpoint: string) => send('/api/push/unsubscribe', 'POST', { endpoint }), } diff --git a/frontend/src/stores/__tests__/settingsStores.spec.ts b/frontend/src/stores/__tests__/settingsStores.spec.ts index 48392772..83c98644 100644 --- a/frontend/src/stores/__tests__/settingsStores.spec.ts +++ b/frontend/src/stores/__tests__/settingsStores.spec.ts @@ -504,6 +504,48 @@ describe('useUiSettingsStore', () => { expect(store.notificationTypeExclusions).toEqual(['charging-complete']) }) + it('defaults the types switched off per car to none', () => { + expect(useUiSettingsStore().notificationTypeExclusionsByVehicle).toEqual({}) + }) + + it('persists the types switched off per car to its own localStorage key', async () => { + const store = useUiSettingsStore() + store.notificationTypeExclusionsByVehicle = { '2': ['doors-open-parked'] } + await nextTick() + vi.advanceTimersByTime(SAVE_DEBOUNCE_MS) + const saved = JSON.parse(localStorage.getItem(UI_KEY)!) + expect(saved.notificationTypeExclusionsByVehicle).toEqual({ '2': ['doors-open-parked'] }) + }) + + it('loads the types switched off per car, keeping only a vehicle id with types in a list', () => { + localStorage.setItem( + UI_KEY, + JSON.stringify({ + notificationTypeExclusionsByVehicle: { + '2': ['low-tyre', 'low-tyre', 7, 'engine-start'], + '3': [], + '4': 'low-tyre', + '0': ['low-tyre'], + abc: ['low-tyre'], + '-5': ['low-tyre'], + '5': null, + }, + }), + ) + + expect(useUiSettingsStore().notificationTypeExclusionsByVehicle).toEqual({ + '2': ['low-tyre', 'engine-start'], + }) + }) + + it.each([null, 'low-tyre', ['low-tyre'], 3])( + 'reads %j as no types switched off per car', + (stored) => { + localStorage.setItem(UI_KEY, JSON.stringify({ notificationTypeExclusionsByVehicle: stored })) + expect(useUiSettingsStore().notificationTypeExclusionsByVehicle).toEqual({}) + }, + ) + it('leaves the region, the clock and every unit on automatic until one is chosen', () => { localStorage.setItem(UI_KEY, JSON.stringify({ theme: 'light' })) const store = useUiSettingsStore() diff --git a/frontend/src/stores/__tests__/settingsSync.spec.ts b/frontend/src/stores/__tests__/settingsSync.spec.ts index 69a6217f..73a860ce 100644 --- a/frontend/src/stores/__tests__/settingsSync.spec.ts +++ b/frontend/src/stores/__tests__/settingsSync.spec.ts @@ -136,6 +136,26 @@ describe('settings kept on the account', () => { expect(save).toHaveBeenCalledExactlyOnceWith('ui', { locale: 'nl' }) }) + it('keeps the types switched off per car on this device too, with the checklist they belong to', async () => { + localStorage.setItem( + UI_KEY, + JSON.stringify({ notificationTypeExclusionsByVehicle: { '2': ['low-tyre'] } }), + ) + load.mockResolvedValue({ + ui: { theme: 'light', notificationTypeExclusionsByVehicle: { '3': ['engine-start'] } }, + }) + const ui = useUiSettingsStore() + await useSettingsSyncStore().start() + + expect(ui.notificationTypeExclusionsByVehicle).toEqual({ '2': ['low-tyre'] }) + + ui.notificationTypeExclusionsByVehicle = {} + ui.locale = 'nl' + await settle() + + expect(save).toHaveBeenCalledExactlyOnceWith('ui', { locale: 'nl' }) + }) + it('keeps the screen and GPS settings on this device, since they suit one phone and not every one', async () => { localStorage.setItem(UI_KEY, JSON.stringify({ keepScreenOn: true, recordPhoneGps: true })) load.mockResolvedValue({ ui: { theme: 'light', keepScreenOn: false, recordPhoneGps: false } }) diff --git a/frontend/src/stores/settingsUi.ts b/frontend/src/stores/settingsUi.ts index 601b05c8..ff756745 100644 --- a/frontend/src/stores/settingsUi.ts +++ b/frontend/src/stores/settingsUi.ts @@ -109,6 +109,11 @@ interface UiSettings { notificationTypeExclusions: string[] /** The opt-in notification types this device switched on (the weekly and monthly summaries). */ notificationTypeInclusions: string[] + /** + * The notification types this device switched off for one car only, by vehicle id. They come on + * top of notificationTypeExclusions, which leave a type out for every car. + */ + notificationTypeExclusionsByVehicle: Record /** * The colour of each car, by VIN, used only while the account has more than one car. A car * without an entry, and every one-car install, uses carColorScheme above. vehicleTypeOverride @@ -142,6 +147,7 @@ function defaultsFor(): UiSettings { logLevel: DEFAULT_LOG_LEVEL, notificationTypeExclusions: [], notificationTypeInclusions: [], + notificationTypeExclusionsByVehicle: {}, vehicleSettings: {}, // Everything follows the region the browser is in, which its time zone tells far better than // its language does. An install from before these settings keeps the units it stored. @@ -233,6 +239,21 @@ function parseVehicleSettings( return result } +// The cars are the account's, so the cap is the one above; a key that is not a vehicle id, or a +// car with no type switched off, is dropped rather than kept. +function parseVehicleNotificationExclusions(raw: unknown): Record { + if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) return {} + const result: Record = {} + for (const [vehicleId, value] of Object.entries(raw).slice(0, MAX_VEHICLE_SETTINGS)) { + if (!/^[1-9]\d{0,8}$/.test(vehicleId) || !Array.isArray(value)) continue + const types = [ + ...new Set((value as unknown[]).filter((v): v is string => typeof v === 'string')), + ] + if (types.length > 0) result[vehicleId] = types + } + return result +} + function parseRegion(raw: unknown, fallback: RegionSetting): RegionSetting { return raw === 'auto' || isRegion(raw) ? raw : fallback } @@ -283,6 +304,9 @@ function parseUiFields(parsed: Record, fallback: UiSettings): U (value): value is string => typeof value === 'string', ) : fallback.notificationTypeInclusions, + notificationTypeExclusionsByVehicle: parseVehicleNotificationExclusions( + parsed.notificationTypeExclusionsByVehicle, + ), vehicleSettings: parseVehicleSettings(parsed.vehicleSettings, carColor), region: parseRegion(parsed.region, fallback.region), clock: oneOf(parsed.clock, CLOCK_SETTINGS, fallback.clock), @@ -324,6 +348,7 @@ export const useUiSettingsStore = defineStore('settingsUi', () => { localKeys: [ 'notificationTypeExclusions', 'notificationTypeInclusions', + 'notificationTypeExclusionsByVehicle', 'keepScreenOn', 'recordPhoneGps', ], diff --git a/frontend/src/utils/__tests__/notificationCategories.spec.ts b/frontend/src/utils/__tests__/notificationCategories.spec.ts index c51ca825..2b45e58e 100644 --- a/frontend/src/utils/__tests__/notificationCategories.spec.ts +++ b/frontend/src/utils/__tests__/notificationCategories.spec.ts @@ -1,9 +1,11 @@ import { describe, it, expect } from 'vitest' import { isCategoryShown, + isPerCarCategory, notificationCategoryId, notificationCategoryIdsFor, NOTIFICATION_CATEGORY_IDS, + vehicleExclusionsOf, } from '@/utils/notificationCategories' describe('notificationCategoryId', () => { @@ -69,4 +71,55 @@ describe('isCategoryShown', () => { expect(isCategoryShown('engine-start', ['engine-start'], [])).toBe(false) expect(isCategoryShown(null, ['engine-start'], [])).toBe(true) }) + + // The same rule as the server's NotificationCategories.IsWanted: either list keeps a type out. + it('leaves out a type switched off for the car, and only for that car', () => { + expect(isCategoryShown('doors-open-parked', [], [], ['doors-open-parked'])).toBe(false) + expect(isCategoryShown('doors-open-parked', [], [], [])).toBe(true) + expect(isCategoryShown('doors-open-parked', [], [], ['low-tyre'])).toBe(true) + expect(isCategoryShown('low-tyre', [], [], ['doors-open-parked'])).toBe(true) + }) + + it('keeps a type out when the device has it off, whatever the car says', () => { + expect(isCategoryShown('engine-start', ['engine-start'], [], [])).toBe(false) + expect(isCategoryShown('engine-start', ['engine-start'], [], ['engine-start'])).toBe(false) + }) + + it('lets a car switch a summary off once the device has asked for it', () => { + expect(isCategoryShown('weekly-summary', [], ['weekly-summary'], [])).toBe(true) + expect(isCategoryShown('weekly-summary', [], ['weekly-summary'], ['weekly-summary'])).toBe( + false, + ) + expect(isCategoryShown('weekly-summary', [], [], [])).toBe(false) + }) + + it('shows a notification without a type whatever a car has off', () => { + expect(isCategoryShown(null, [], [], ['engine-start'])).toBe(true) + }) +}) + +describe('isPerCarCategory', () => { + // The MG sign-in failing is about the account: the Worker sends it without a car. + it('is false only for the types the Worker sends without naming a car', () => { + expect(NOTIFICATION_CATEGORY_IDS.filter((id) => !isPerCarCategory(id))).toEqual([ + 'gateway-login', + ]) + }) +}) + +describe('vehicleExclusionsOf', () => { + const byVehicle = { '7': ['low-tyre'], '9': ['engine-start', 'maintenance'] } + + it('returns the types switched off for that car', () => { + expect(vehicleExclusionsOf(byVehicle, 9)).toEqual(['engine-start', 'maintenance']) + }) + + it('returns none for a car the device never chose for', () => { + expect(vehicleExclusionsOf(byVehicle, 8)).toEqual([]) + }) + + // A notification about no car (the MG sign-in failing) answers to the device's own list alone. + it.each([null, undefined])('returns none for a notification without a car (%s)', (vehicleId) => { + expect(vehicleExclusionsOf(byVehicle, vehicleId)).toEqual([]) + }) }) diff --git a/frontend/src/utils/notificationCategories.ts b/frontend/src/utils/notificationCategories.ts index 6981fd70..f6ee8d46 100644 --- a/frontend/src/utils/notificationCategories.ts +++ b/frontend/src/utils/notificationCategories.ts @@ -55,6 +55,15 @@ export function notificationCategoryIdsFor( ) } +// The Worker sends these without naming a car (the MG sign-in failing is about the account, and +// no car reports it), so a car's own list has nothing to switch off for them. +const ACCOUNT_WIDE_CATEGORY_IDS: readonly NotificationCategoryId[] = ['gateway-login'] + +/** Whether a notification of the type `id` can be about one car, and so be switched off for it. */ +export function isPerCarCategory(id: NotificationCategoryId): boolean { + return !ACCOUNT_WIDE_CATEGORY_IDS.includes(id) +} + /** * The types a device switches on rather than off, as NotificationCategories.OptInGroups on the * server: a summary every week unasked would be noise. @@ -68,16 +77,35 @@ export function isOptIn(id: NotificationCategoryId): boolean { return OPT_IN_CATEGORY_IDS.includes(id) } +/** + * The types switched off for one car only, by vehicle id, on top of the device's own exclusions + * (which leave a type out for every car). Keyed by the id as text, since that is what a JSON + * object holds. + */ +export type VehicleExclusions = Readonly> + +/** The types switched off for the car `vehicleId`; none for a notification that names no car. */ +export function vehicleExclusionsOf( + byVehicle: VehicleExclusions, + vehicleId: number | null | undefined, +): readonly string[] { + return vehicleId == null ? [] : (byVehicle[String(vehicleId)] ?? []) +} + /** * Whether this device shows a notification of the type `id`: an opt-in type once switched on, any * other until switched off, and one without a known type always, since nothing can switch it off. + * `vehicleExclusions` is what the device also switched off for the car the notification is about; + * a type in either list stays out, as on the server (NotificationCategories.IsWanted). */ export function isCategoryShown( id: NotificationCategoryId | null, exclusions: readonly string[], inclusions: readonly string[], + vehicleExclusions: readonly string[] = [], ): boolean { if (id === null) return true + if (vehicleExclusions.includes(id)) return false return isOptIn(id) ? inclusions.includes(id) : !exclusions.includes(id) } diff --git a/src/GarageStack.Api/Endpoints/PushEndpoints.cs b/src/GarageStack.Api/Endpoints/PushEndpoints.cs index 61101c5d..675d04b5 100644 --- a/src/GarageStack.Api/Endpoints/PushEndpoints.cs +++ b/src/GarageStack.Api/Endpoints/PushEndpoints.cs @@ -1,4 +1,5 @@ using GarageStack.Core.Configuration; +using GarageStack.Core.Helpers; using GarageStack.Core.Interfaces; using GarageStack.Core.Models; @@ -101,6 +102,7 @@ internal static Task UpsertSubscriptionAsync( req.Endpoint, req.P256DhKey, req.AuthKey, req.ExcludedCategories is { } requested ? KnownGroups(requested) : null, req.IncludedCategories is { } included ? KnownGroups(included.Where(NotificationCategories.OptInGroups.Contains)) : null, + req.ExcludedCategoriesByVehicle is { } byVehicle ? VehicleCategoryExclusions.Normalize(byVehicle) : null, ct); // Only the types the checklist offers, once each and in one order, so an unchanged list @@ -109,11 +111,13 @@ private static List KnownGroups(IEnumerable requested) => [.. requested.Where(NotificationCategories.Groups.Contains).Distinct().Order(StringComparer.Ordinal)]; } -// ExcludedCategories: the notification types this device switched off; IncludedCategories: the opt-in -// ones it switched on (the weekly and monthly summaries). Null leaves that stored list as it is. +// ExcludedCategories: the notification types this device switched off for every car; IncludedCategories: +// the opt-in ones it switched on (the weekly and monthly summaries); ExcludedCategoriesByVehicle: the +// types it switched off for one car only, by vehicle id. Null leaves that stored choice as it is. public record PushSubscribeRequest( string Endpoint, string P256DhKey, string AuthKey, - IReadOnlyList? ExcludedCategories = null, IReadOnlyList? IncludedCategories = null); + IReadOnlyList? ExcludedCategories = null, IReadOnlyList? IncludedCategories = null, + IReadOnlyDictionary>? ExcludedCategoriesByVehicle = null); public record PushUnsubscribeRequest(string Endpoint); /// The server's VAPID public key, which a browser subscribes to push with. diff --git a/src/GarageStack.Core/Helpers/VehicleCategoryExclusions.cs b/src/GarageStack.Core/Helpers/VehicleCategoryExclusions.cs new file mode 100644 index 00000000..f8c5786d --- /dev/null +++ b/src/GarageStack.Core/Helpers/VehicleCategoryExclusions.cs @@ -0,0 +1,60 @@ +using System.Text.Json; +using GarageStack.Core.Models; + +namespace GarageStack.Core.Helpers; + +/// +/// The notification types a device switched off for one car, kept as {"<vehicle id>": ["low-tyre", ...]} +/// beside . Both the request and the stored +/// column go through , so an unchanged choice always compares equal to what +/// is stored, whatever order the page listed it in. +/// +public static class VehicleCategoryExclusions +{ + /// + /// More cars than any account has. The map comes from the browser, and every push reads it, so + /// it is held to a size no real choice reaches. + /// + public const int MaxVehicles = 32; + + /// + /// Only the types the checklist offers, once each and in one order; only cars with at least one + /// type off, by ascending id; and at most of them. + /// + public static Dictionary> Normalize(IEnumerable>> requested) + { + var normalized = new Dictionary>(); + foreach (var (vehicleId, groups) in requested.OrderBy(entry => entry.Key)) + { + if (vehicleId <= 0 || normalized.Count >= MaxVehicles) continue; + + List known = + [.. (groups ?? []).Where(NotificationCategories.Groups.Contains).Distinct().Order(StringComparer.Ordinal)]; + if (known.Count > 0) normalized[vehicleId] = known; + } + return normalized; + } + + /// Whether two normalized choices hold the same types for the same cars. + public static bool AreEqual(IReadOnlyDictionary> a, IReadOnlyDictionary> b) => + a.Count == b.Count + && a.All(entry => b.TryGetValue(entry.Key, out var other) && entry.Value.SequenceEqual(other, StringComparer.Ordinal)); + + /// The column's JSON. Normalized choices serialize the same way every time. + public static string ToJson(IReadOnlyDictionary> exclusions) => + JsonSerializer.Serialize(exclusions); + + /// The choice a column holds. A value that is not the JSON written above reads as no exclusions. + public static Dictionary> FromJson(string? json) + { + if (string.IsNullOrWhiteSpace(json)) return []; + try + { + return JsonSerializer.Deserialize>>(json) ?? []; + } + catch (JsonException) + { + return []; + } + } +} diff --git a/src/GarageStack.Core/Interfaces/IPushSubscriptionRepository.cs b/src/GarageStack.Core/Interfaces/IPushSubscriptionRepository.cs index 348c80eb..86768ab4 100644 --- a/src/GarageStack.Core/Interfaces/IPushSubscriptionRepository.cs +++ b/src/GarageStack.Core/Interfaces/IPushSubscriptionRepository.cs @@ -11,12 +11,14 @@ public interface IPushSubscriptionRepository /// /// Stores a subscription against its endpoint, inserting or updating as needed. The app /// registers its subscription again on every load, so this runs often and is both idempotent - /// and safe to run twice at once. A null or - /// leaves that stored list as it is. + /// and safe to run twice at once. A null , + /// or + /// (the types switched off for one car only, by vehicle id) leaves that stored choice as it is. /// Task UpsertAsync( string endpoint, string p256DhKey, string authKey, IReadOnlyList? excludedCategories, - IReadOnlyList? includedCategories, CancellationToken ct = default); + IReadOnlyList? includedCategories, IReadOnlyDictionary>? excludedCategoriesByVehicle, + CancellationToken ct = default); /// Removes the subscriptions with these endpoints; unknown ones are ignored. Task RemoveAsync(IReadOnlyCollection endpoints, CancellationToken ct = default); diff --git a/src/GarageStack.Core/Models/NotificationCategories.cs b/src/GarageStack.Core/Models/NotificationCategories.cs index 1190e03c..58736dfc 100644 --- a/src/GarageStack.Core/Models/NotificationCategories.cs +++ b/src/GarageStack.Core/Models/NotificationCategories.cs @@ -122,13 +122,20 @@ _ when Groups.Contains(category) => category, /// Whether a device that switched off , and switched on /// , wants a notification. One /// without a known type always goes out: the checklist offers no way to switch it off. An - /// opt-in type goes out only once switched on. + /// opt-in type goes out only once switched on. is what + /// the device also switched off for the car the notification is about, or null when it names + /// no car: a type in either list stays out, so a type is wanted for a car only when neither + /// the device nor that car has it off. /// public static bool IsWanted( - string? category, IReadOnlyCollection excludedGroups, IReadOnlyCollection? includedGroups = null) => + string? category, + IReadOnlyCollection excludedGroups, + IReadOnlyCollection? includedGroups = null, + IReadOnlyCollection? excludedForVehicle = null) => GroupOf(category) switch { null => true, + var group when excludedForVehicle?.Contains(group) == true => false, var group when OptInGroups.Contains(group) => includedGroups?.Contains(group) == true, var group => !excludedGroups.Contains(group), }; diff --git a/src/GarageStack.Core/Models/PushSubscription.cs b/src/GarageStack.Core/Models/PushSubscription.cs index 961a5be3..2026ebde 100644 --- a/src/GarageStack.Core/Models/PushSubscription.cs +++ b/src/GarageStack.Core/Models/PushSubscription.cs @@ -19,4 +19,16 @@ public class PushSubscription /// which no device gets until it does. /// public List IncludedCategories { get; set; } = []; + + /// + /// The notification types this device switched off for one car only, by , + /// on top of , which leaves a type out for every car. A type + /// reaches the device when neither list holds it. Notifications that belong to no car (the MG + /// sign-in failing) answer to alone. + /// + public Dictionary> ExcludedCategoriesByVehicle { get; set; } = []; + + /// The types this device switched off for alone, or null for a notification without a car. + public IReadOnlyCollection? ExcludedCategoriesFor(int? vehicleId) => + vehicleId is { } id && ExcludedCategoriesByVehicle.TryGetValue(id, out var groups) ? groups : null; } diff --git a/src/GarageStack.Data/AppDbContext.cs b/src/GarageStack.Data/AppDbContext.cs index 1c278fd6..4ece72c6 100644 --- a/src/GarageStack.Data/AppDbContext.cs +++ b/src/GarageStack.Data/AppDbContext.cs @@ -1,6 +1,7 @@ using GarageStack.Core.Helpers; using GarageStack.Core.Models; using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.ChangeTracking; namespace GarageStack.Data; @@ -141,6 +142,18 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) // Subscriptions from before devices could switch types off want every type. e.PrimitiveCollection(p => p.ExcludedCategories).HasDefaultValueSql("'{}'::text[]"); e.PrimitiveCollection(p => p.IncludedCategories).HasDefaultValueSql("'{}'::text[]"); + // Types switched off for one car only: {"": ["low-tyre", ...]}. Nothing + // before this wanted a type for one car and not the other, so every row starts empty. + e.Property(p => p.ExcludedCategoriesByVehicle) + .HasConversion( + exclusions => VehicleCategoryExclusions.ToJson(exclusions), + json => VehicleCategoryExclusions.FromJson(json), + new ValueComparer>>( + (a, b) => VehicleCategoryExclusions.AreEqual(a!, b!), + exclusions => VehicleCategoryExclusions.ToJson(exclusions).GetHashCode(), + exclusions => VehicleCategoryExclusions.FromJson(VehicleCategoryExclusions.ToJson(exclusions)))) + .HasColumnType("jsonb") + .HasDefaultValueSql("'{}'::jsonb"); }); modelBuilder.Entity(e => diff --git a/src/GarageStack.Data/Migrations/20261126205019_AddPushSubscriptionVehicleExclusions.Designer.cs b/src/GarageStack.Data/Migrations/20261126205019_AddPushSubscriptionVehicleExclusions.Designer.cs new file mode 100644 index 00000000..8caf44c0 --- /dev/null +++ b/src/GarageStack.Data/Migrations/20261126205019_AddPushSubscriptionVehicleExclusions.Designer.cs @@ -0,0 +1,1397 @@ +// +using System; +using System.Collections.Generic; +using GarageStack.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace GarageStack.Data.Migrations; + +[DbContext(typeof(AppDbContext))] +[Migration("20261126205019_AddPushSubscriptionVehicleExclusions")] +partial class _20261126205019_AddPushSubscriptionVehicleExclusions +{ + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "11.0.0") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("GarageStack.Core.Models.ApiToken", b => + { + var id = b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(id); + + b.Property("AccountKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("LastUsedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("Prefix") + .IsRequired() + .HasMaxLength(9) + .HasColumnType("character varying(9)"); + + b.Property("Scope") + .HasColumnType("integer"); + + b.Property("TokenHash") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Id"); + + b.HasIndex("AccountKey"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("ApiTokens"); + }); + + modelBuilder.Entity("GarageStack.Core.Models.AppNotification", b => + { + var id = b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(id); + + b.Property("Body") + .IsRequired() + .HasColumnType("text"); + + b.Property("Category") + .HasColumnType("text"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("IsArchived") + .HasColumnType("boolean"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("Title") + .IsRequired() + .HasColumnType("text"); + + b.Property("VehicleId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("CreatedAt"); + + b.HasIndex("IsDeleted", "CreatedAt"); + + b.ToTable("AppNotifications"); + }); + + modelBuilder.Entity("GarageStack.Core.Models.ClimateSchedule", b => + { + var id = b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(id); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Days") + .HasColumnType("integer"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("LastRunAt") + .HasColumnType("timestamp with time zone"); + + b.Property("LastRunDetail") + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("LastRunFailedCommand") + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("LastRunOutcome") + .HasMaxLength(24) + .HasColumnType("character varying(24)"); + + b.Property("Mode") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.Property("Name") + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("NextRunUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("OnlyAboveC") + .HasColumnType("double precision"); + + b.Property("OnlyBelowC") + .HasColumnType("double precision"); + + b.Property("RearDefroster") + .HasColumnType("boolean"); + + b.Property("SeatLeftLevel") + .HasColumnType("integer"); + + b.Property("SeatRightLevel") + .HasColumnType("integer"); + + b.Property("StartTime") + .HasColumnType("time without time zone"); + + b.Property("TemperatureC") + .HasColumnType("integer"); + + b.Property("TimeZoneId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("VehicleId") + .HasColumnType("integer"); + + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("VehicleId"); + + b.ToTable("ClimateSchedules"); + }); + + modelBuilder.Entity("GarageStack.Core.Models.CommutePlace", b => + { + var id = b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(id); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(8) + .HasColumnType("character varying(8)"); + + b.Property("Label") + .HasMaxLength(60) + .HasColumnType("character varying(60)"); + + b.Property("Latitude") + .HasColumnType("double precision"); + + b.Property("Longitude") + .HasColumnType("double precision"); + + b.Property("Notify") + .HasColumnType("boolean"); + + b.Property("RadiusMeters") + .HasColumnType("integer"); + + b.Property("VehicleId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("VehicleId"); + + b.ToTable("CommutePlaces"); + }); + + modelBuilder.Entity("GarageStack.Core.Models.GeocodeCacheEntry", b => + { + var id = b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(id); + + b.Property("CachedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("CellLat") + .HasColumnType("integer"); + + b.Property("CellLng") + .HasColumnType("integer"); + + b.Property("City") + .HasMaxLength(120) + .HasColumnType("character varying(120)"); + + b.Property("CountryCode") + .HasMaxLength(8) + .HasColumnType("character varying(8)"); + + b.Property("DisplayName") + .HasMaxLength(300) + .HasColumnType("character varying(300)"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("HouseNumber") + .HasMaxLength(120) + .HasColumnType("character varying(120)"); + + b.Property("Language") + .IsRequired() + .HasMaxLength(8) + .HasColumnType("character varying(8)"); + + b.Property("Postcode") + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.Property("Precision") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.Property("Road") + .HasMaxLength(120) + .HasColumnType("character varying(120)"); + + b.HasKey("Id"); + + b.HasIndex("ExpiresAt") + .HasDatabaseName("IX_GeocodeCacheEntries_ExpiresAt"); + + b.HasIndex("Precision", "Language", "CellLat", "CellLng") + .IsUnique() + .HasDatabaseName("IX_GeocodeCacheEntries_Precision_Language_CellLatLng"); + + b.ToTable("GeocodeCacheEntries"); + }); + + modelBuilder.Entity("GarageStack.Core.Models.MaintenanceItem", b => + { + var id = b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(id); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("IntervalKm") + .HasColumnType("double precision"); + + b.Property("IntervalMonths") + .HasColumnType("integer"); + + b.Property("LastServiceDate") + .HasColumnType("timestamp with time zone"); + + b.Property("LastServiceOdometerKm") + .HasColumnType("double precision"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Notes") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("VehicleId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("VehicleId"); + + b.ToTable("MaintenanceItems"); + }); + + modelBuilder.Entity("GarageStack.Core.Models.MaintenanceLogEntry", b => + { + var id = b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(id); + + b.Property("Cost") + .HasPrecision(10, 2) + .HasColumnType("numeric(10,2)"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("MaintenanceItemId") + .HasColumnType("integer"); + + b.Property("Notes") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("OdometerKm") + .HasColumnType("double precision"); + + b.Property("PerformedAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("MaintenanceItemId", "PerformedAt"); + + b.ToTable("MaintenanceLogEntries"); + }); + + modelBuilder.Entity("GarageStack.Core.Models.MapMatchCacheEntry", b => + { + var id = b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(id); + + b.Property("CachedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("MatchedKm") + .HasColumnType("double precision"); + + b.Property("PointIndexesJson") + .HasColumnType("text"); + + b.Property("Provider") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("Shape") + .HasColumnType("text"); + + b.Property("SpeedLimitRunsJson") + .HasColumnType("text"); + + b.Property("TraceHash") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Id"); + + b.HasIndex("ExpiresAt") + .HasDatabaseName("IX_MapMatchCacheEntries_ExpiresAt"); + + b.HasIndex("Provider", "TraceHash") + .IsUnique() + .HasDatabaseName("IX_MapMatchCacheEntries_Provider_TraceHash"); + + b.ToTable("MapMatchCacheEntries"); + }); + + modelBuilder.Entity("GarageStack.Core.Models.PhoneBackfillRequest", b => + { + b.Property("VehicleId") + .HasColumnType("integer"); + + b.Property("AfterTripId") + .HasColumnType("bigint"); + + b.Property("From") + .HasColumnType("timestamp with time zone"); + + b.Property("Until") + .HasColumnType("timestamp with time zone"); + + b.HasKey("VehicleId"); + + b.ToTable("PhoneBackfillRequests"); + }); + + modelBuilder.Entity("GarageStack.Core.Models.PhonePosition", b => + { + var id = b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(id); + + b.Property("AccuracyM") + .HasColumnType("double precision"); + + b.Property("Latitude") + .HasColumnType("double precision"); + + b.Property("Longitude") + .HasColumnType("double precision"); + + b.Property("RecordedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("SpeedKmh") + .HasColumnType("double precision"); + + b.Property("TrackerId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("VehicleId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("VehicleId", "RecordedAt"); + + b.HasIndex("VehicleId", "TrackerId", "RecordedAt") + .IsUnique(); + + b.ToTable("PhonePositions"); + }); + + modelBuilder.Entity("GarageStack.Core.Models.PoiCacheTile", b => + { + var id = b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(id); + + b.Property("CachedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("CellLat") + .HasColumnType("integer"); + + b.Property("CellLng") + .HasColumnType("integer"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("PoiType") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("Source") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.HasKey("Id"); + + b.HasIndex("ExpiresAt") + .HasDatabaseName("IX_PoiCacheTiles_ExpiresAt"); + + b.HasIndex("Source", "PoiType", "CellLat", "CellLng") + .IsUnique() + .HasDatabaseName("IX_PoiCacheTiles_Source_PoiType_CellLatLng"); + + b.ToTable("PoiCacheTiles"); + }); + + modelBuilder.Entity("GarageStack.Core.Models.PoiItem", b => + { + var id = b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(id); + + b.Property("Brand") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("CellLat") + .HasColumnType("integer"); + + b.Property("CellLng") + .HasColumnType("integer"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("ExternalId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Latitude") + .HasColumnType("double precision"); + + b.Property("Longitude") + .HasColumnType("double precision"); + + b.Property("MetaJson") + .HasColumnType("text"); + + b.Property("Name") + .HasColumnType("text"); + + b.Property("PoiType") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("Source") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Source", "ExternalId") + .IsUnique() + .HasDatabaseName("IX_PoiItems_Source_ExternalId"); + + b.HasIndex("Source", "PoiType", "Brand") + .HasDatabaseName("IX_PoiItems_Source_PoiType_Brand"); + + b.HasIndex("Source", "PoiType", "CellLat", "CellLng") + .HasDatabaseName("IX_PoiItems_Source_PoiType_CellLatLng"); + + b.HasIndex("Source", "PoiType", "Latitude", "Longitude") + .HasDatabaseName("IX_PoiItems_Source_PoiType_LatLon"); + + b.ToTable("PoiItems"); + }); + + modelBuilder.Entity("GarageStack.Core.Models.PushSubscription", b => + { + var id = b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(id); + + b.Property("AuthKey") + .IsRequired() + .HasColumnType("text"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Endpoint") + .IsRequired() + .HasColumnType("text"); + + b.PrimitiveCollection>("ExcludedCategories") + .IsRequired() + .ValueGeneratedOnAdd() + .HasColumnType("text[]") + .HasDefaultValueSql("'{}'::text[]"); + + b.Property("ExcludedCategoriesByVehicle") + .IsRequired() + .ValueGeneratedOnAdd() + .HasColumnType("jsonb") + .HasDefaultValueSql("'{}'::jsonb"); + + b.PrimitiveCollection>("IncludedCategories") + .IsRequired() + .ValueGeneratedOnAdd() + .HasColumnType("text[]") + .HasDefaultValueSql("'{}'::text[]"); + + b.Property("P256DhKey") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("Endpoint") + .IsUnique(); + + b.ToTable("PushSubscriptions"); + }); + + modelBuilder.Entity("GarageStack.Core.Models.RdwVehicleInfo", b => + { + var id = b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(id); + + b.Property("ApkExpiresOn") + .HasColumnType("date"); + + b.Property("FetchedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Found") + .HasColumnType("boolean"); + + b.Property("LastError") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("LicensePlate") + .IsRequired() + .HasMaxLength(8) + .HasColumnType("character varying(8)"); + + b.Property("Make") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Model") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("OpenRecallIndicator") + .HasColumnType("boolean"); + + b.Property("RecallsJson") + .IsRequired() + .HasColumnType("text"); + + b.Property("VehicleId") + .HasColumnType("integer"); + + b.Property("WamInsured") + .HasColumnType("boolean"); + + b.HasKey("Id"); + + b.HasIndex("VehicleId") + .IsUnique(); + + b.ToTable("RdwVehicleInfos"); + }); + + modelBuilder.Entity("GarageStack.Core.Models.RevokedToken", b => + { + var id = b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(id); + + b.Property("ExpiresAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Jti") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Id"); + + b.HasIndex("Jti") + .IsUnique(); + + b.ToTable("RevokedTokens"); + }); + + modelBuilder.Entity("GarageStack.Core.Models.TelemetrySnapshot", b => + { + var id = b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(id); + + b.Property("BatteryHeating") + .HasColumnType("boolean"); + + b.Property("BatteryHeatingScheduleMode") + .HasColumnType("text"); + + b.Property("BatteryHeatingScheduleStartTime") + .HasColumnType("text"); + + b.Property("BatteryVoltage") + .HasColumnType("double precision"); + + b.Property("BmsChargeStatus") + .HasColumnType("text"); + + b.Property("BonnetOpen") + .HasColumnType("boolean"); + + b.Property("ChargeCurrentLimit") + .HasColumnType("text"); + + b.Property("ChargerConnected") + .HasColumnType("boolean"); + + b.Property("ChargingCableLock") + .HasColumnType("boolean"); + + b.Property("ChargingLastEndAt") + .HasColumnType("timestamp with time zone"); + + b.Property("ChargingLastStartAt") + .HasColumnType("timestamp with time zone"); + + b.Property("ChargingScheduleEndTime") + .HasColumnType("text"); + + b.Property("ChargingScheduleMode") + .HasColumnType("text"); + + b.Property("ChargingScheduleStartTime") + .HasColumnType("text"); + + b.Property("ChargingStopReason") + .HasColumnType("text"); + + b.Property("ChargingType") + .HasColumnType("text"); + + b.Property("ClimateMode") + .HasColumnType("text"); + + b.Property("ClimateOn") + .HasColumnType("boolean"); + + b.Property("CurrentJourneyDistance") + .HasColumnType("double precision"); + + b.Property("DriverDoorOpen") + .HasColumnType("boolean"); + + b.Property("DriverWindowOpen") + .HasColumnType("boolean"); + + b.Property("ElectricRangeKm") + .HasColumnType("double precision"); + + b.Property("Elevation") + .HasColumnType("double precision"); + + b.Property("EngineRunning") + .HasColumnType("boolean"); + + b.Property("EvSocPercent") + .HasColumnType("double precision"); + + b.Property("ExteriorTemperature") + .HasColumnType("double precision"); + + b.Property("FuelLevelPercent") + .HasColumnType("double precision"); + + b.Property("FuelRangeKm") + .HasColumnType("double precision"); + + b.Property("Heading") + .HasColumnType("double precision"); + + b.Property("HeatedSeatFrontLeft") + .HasColumnType("integer"); + + b.Property("HeatedSeatFrontRight") + .HasColumnType("integer"); + + b.Property("HvBatteryActive") + .HasColumnType("boolean"); + + b.Property("HvCurrent") + .HasColumnType("double precision"); + + b.Property("HvPower") + .HasColumnType("double precision"); + + b.Property("HvSocKwh") + .HasColumnType("double precision"); + + b.Property("HvTotalCapacityKwh") + .HasColumnType("double precision"); + + b.Property("HvVoltage") + .HasColumnType("double precision"); + + b.Property("InteriorTemperature") + .HasColumnType("double precision"); + + b.Property("IsAvailable") + .HasColumnType("boolean"); + + b.Property("IsCharging") + .HasColumnType("boolean"); + + b.Property("IsLocked") + .HasColumnType("boolean"); + + b.Property("LastChargeEndingPower") + .HasColumnType("double precision"); + + b.Property("LastChargeStateAt") + .HasColumnType("timestamp with time zone"); + + b.Property("LastVehicleStateAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Latitude") + .HasColumnType("double precision"); + + b.Property("LightsDippedBeam") + .HasColumnType("boolean"); + + b.Property("LightsMainBeam") + .HasColumnType("boolean"); + + b.Property("LightsSide") + .HasColumnType("boolean"); + + b.Property("Longitude") + .HasColumnType("double precision"); + + b.Property("MileageOfTheDay") + .HasColumnType("double precision"); + + b.Property("MileageSinceLastCharge") + .HasColumnType("double precision"); + + b.Property("ObcCurrent") + .HasColumnType("double precision"); + + b.Property("ObcPowerSinglePhase") + .HasColumnType("double precision"); + + b.Property("ObcPowerThreePhase") + .HasColumnType("double precision"); + + b.Property("ObcVoltage") + .HasColumnType("double precision"); + + b.Property("OdometerKm") + .HasColumnType("double precision"); + + b.Property("OffboardChargerPlugStatus") + .HasColumnType("integer"); + + b.Property("OnboardChargerPlugStatus") + .HasColumnType("integer"); + + b.Property("PassengerDoorOpen") + .HasColumnType("boolean"); + + b.Property("PassengerWindowOpen") + .HasColumnType("boolean"); + + b.Property("PowerUsageOfDay") + .HasColumnType("double precision"); + + b.Property("PowerUsageSinceLastCharge") + .HasColumnType("double precision"); + + b.Property("RearLeftDoorOpen") + .HasColumnType("boolean"); + + b.Property("RearLeftWindowOpen") + .HasColumnType("boolean"); + + b.Property("RearRightDoorOpen") + .HasColumnType("boolean"); + + b.Property("RearRightWindowOpen") + .HasColumnType("boolean"); + + b.Property("RearWindowDefroster") + .HasColumnType("boolean"); + + b.Property("RecordedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("RemainingChargingTime") + .HasColumnType("integer"); + + b.Property("RemoteTemperature") + .HasColumnType("double precision"); + + b.Property("SocTargetPercent") + .HasColumnType("integer"); + + b.Property("Speed") + .HasColumnType("double precision"); + + b.Property("SteeringWheelHeating") + .HasColumnType("boolean"); + + b.Property("SunRoofOpen") + .HasColumnType("boolean"); + + b.Property("TrunkOpen") + .HasColumnType("boolean"); + + b.Property("TyrePressureFrontLeft") + .HasColumnType("double precision"); + + b.Property("TyrePressureFrontRight") + .HasColumnType("double precision"); + + b.Property("TyrePressureRearLeft") + .HasColumnType("double precision"); + + b.Property("TyrePressureRearRight") + .HasColumnType("double precision"); + + b.Property("VehicleId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("VehicleId", "RecordedAt"); + + var index = b.HasIndex(new[] { "VehicleId", "RecordedAt" }, "IX_TelemetrySnapshots_VehicleId_RecordedAt_Gps") + .HasFilter("\"Latitude\" IS NOT NULL AND \"Longitude\" IS NOT NULL"); + + NpgsqlIndexBuilderExtensions.IncludeProperties(index, new[] { "Latitude", "Longitude", "Speed", "Heading" }); + + b.HasIndex(new[] { "VehicleId", "RecordedAt" }, "IX_TelemetrySnapshots_VehicleId_RecordedAt_Schedule") + .HasFilter("\"ChargingScheduleMode\" IS NOT NULL OR \"ChargingScheduleStartTime\" IS NOT NULL OR \"ChargingScheduleEndTime\" IS NOT NULL OR \"BatteryHeatingScheduleMode\" IS NOT NULL OR \"BatteryHeatingScheduleStartTime\" IS NOT NULL"); + + b.ToTable("TelemetrySnapshots"); + }); + + modelBuilder.Entity("GarageStack.Core.Models.Trip", b => + { + var id = b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(id); + + b.Property("AvgMovingSpeedKmh") + .HasColumnType("double precision"); + + b.Property("CounterReadings") + .HasColumnType("integer"); + + b.Property("CounterUsed") + .HasColumnType("double precision"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("DistanceKm") + .HasColumnType("double precision"); + + b.Property("EditedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("EndLatitude") + .HasColumnType("double precision"); + + b.Property("EndLongitude") + .HasColumnType("double precision"); + + b.Property("EndPlaceJson") + .HasColumnType("text"); + + b.Property("EndedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("IsHidden") + .HasColumnType("boolean"); + + b.Property("JoinedFromJson") + .HasColumnType("text"); + + b.Property("MaxSpeedKmh") + .HasColumnType("double precision"); + + b.Property("MovingSpeedSamples") + .HasColumnType("integer"); + + b.Property("Notes") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("OdometerEndKm") + .HasColumnType("double precision"); + + b.Property("OdometerStartKm") + .HasColumnType("double precision"); + + b.Property("OriginalPointsJson") + .HasColumnType("text"); + + b.Property("PhoneFusion") + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.Property("PhoneFusionAt") + .HasColumnType("timestamp with time zone"); + + b.Property("PointCount") + .HasColumnType("integer"); + + b.Property("PointsJson") + .IsRequired() + .HasColumnType("text"); + + b.Property("Purpose") + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.Property("PurposeIsManual") + .HasColumnType("boolean"); + + b.Property("StartLatitude") + .HasColumnType("double precision"); + + b.Property("StartLongitude") + .HasColumnType("double precision"); + + b.Property("StartPlaceJson") + .HasColumnType("text"); + + b.Property("StartedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("VehicleId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("PhoneFusion", "EndedAt"); + + b.HasIndex("VehicleId", "StartedAt") + .IsUnique(); + + b.ToTable("Trips"); + }); + + modelBuilder.Entity("GarageStack.Core.Models.UserSettings", b => + { + var id = b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(id); + + b.Property("AccountKey") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Json") + .IsRequired() + .HasColumnType("text"); + + b.Property("Section") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("AccountKey", "Section") + .IsUnique(); + + b.ToTable("UserSettings"); + }); + + modelBuilder.Entity("GarageStack.Core.Models.Vehicle", b => + { + var id = b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(id); + + b.Property("ConfigJson") + .HasColumnType("text"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("HasPowerTailgate") + .HasColumnType("boolean"); + + b.Property("LastMessageId") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("LastParkedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("LicensePlate") + .HasMaxLength(8) + .HasColumnType("character varying(8)"); + + b.Property("Model") + .HasColumnType("text"); + + b.Property("ParkedLatitude") + .HasColumnType("double precision"); + + b.Property("ParkedLongitude") + .HasColumnType("double precision"); + + b.Property("SaicUser") + .HasColumnType("text"); + + b.Property("Series") + .HasColumnType("text"); + + b.Property("TelemetryCompactedUntil") + .HasColumnType("timestamp with time zone"); + + b.Property("TripsRecordedUntil") + .HasColumnType("timestamp with time zone"); + + b.Property("Vin") + .IsRequired() + .HasMaxLength(17) + .HasColumnType("character varying(17)"); + + b.HasKey("Id"); + + b.HasIndex("Vin") + .IsUnique(); + + b.ToTable("Vehicles"); + }); + + modelBuilder.Entity("GarageStack.Core.Models.VehiclePhoneTracker", b => + { + var id = b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(id); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("TrackerId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("VehicleId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("VehicleId", "TrackerId") + .IsUnique(); + + b.ToTable("VehiclePhoneTrackers"); + }); + + modelBuilder.Entity("GarageStack.Core.Models.ClimateSchedule", b => + { + b.HasOne("GarageStack.Core.Models.Vehicle", "Vehicle") + .WithMany() + .HasForeignKey("VehicleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Vehicle"); + }); + + modelBuilder.Entity("GarageStack.Core.Models.CommutePlace", b => + { + b.HasOne("GarageStack.Core.Models.Vehicle", "Vehicle") + .WithMany() + .HasForeignKey("VehicleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Vehicle"); + }); + + modelBuilder.Entity("GarageStack.Core.Models.MaintenanceItem", b => + { + b.HasOne("GarageStack.Core.Models.Vehicle", "Vehicle") + .WithMany() + .HasForeignKey("VehicleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Vehicle"); + }); + + modelBuilder.Entity("GarageStack.Core.Models.MaintenanceLogEntry", b => + { + b.HasOne("GarageStack.Core.Models.MaintenanceItem", "MaintenanceItem") + .WithMany("LogEntries") + .HasForeignKey("MaintenanceItemId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("MaintenanceItem"); + }); + + modelBuilder.Entity("GarageStack.Core.Models.PhoneBackfillRequest", b => + { + b.HasOne("GarageStack.Core.Models.Vehicle", "Vehicle") + .WithMany() + .HasForeignKey("VehicleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Vehicle"); + }); + + modelBuilder.Entity("GarageStack.Core.Models.PhonePosition", b => + { + b.HasOne("GarageStack.Core.Models.Vehicle", "Vehicle") + .WithMany() + .HasForeignKey("VehicleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Vehicle"); + }); + + modelBuilder.Entity("GarageStack.Core.Models.RdwVehicleInfo", b => + { + b.HasOne("GarageStack.Core.Models.Vehicle", "Vehicle") + .WithMany() + .HasForeignKey("VehicleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Vehicle"); + }); + + modelBuilder.Entity("GarageStack.Core.Models.TelemetrySnapshot", b => + { + b.HasOne("GarageStack.Core.Models.Vehicle", "Vehicle") + .WithMany("TelemetrySnapshots") + .HasForeignKey("VehicleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Vehicle"); + }); + + modelBuilder.Entity("GarageStack.Core.Models.Trip", b => + { + b.HasOne("GarageStack.Core.Models.Vehicle", "Vehicle") + .WithMany() + .HasForeignKey("VehicleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Vehicle"); + }); + + modelBuilder.Entity("GarageStack.Core.Models.Vehicle", b => + { + b.OwnsOne("GarageStack.Core.Models.VehicleSettings", "Settings", b1 => + { + b1.Property("VehicleId") + .HasColumnType("integer"); + + b1.Property("AuxBatteryLowVolt") + .HasColumnType("double precision"); + + b1.Property("HvBatteryCapacityKwh") + .HasColumnType("double precision"); + + b1.Property("LowEvPercent") + .HasColumnType("double precision"); + + b1.Property("LowFuelPercent") + .HasColumnType("double precision"); + + b1.Property("TyreDropBar") + .HasColumnType("double precision"); + + b1.Property("TyreGoodBar") + .HasColumnType("double precision"); + + b1.Property("TyreHighBar") + .HasColumnType("double precision"); + + b1.Property("TyreLowBar") + .HasColumnType("double precision"); + + b1.Property("VehicleType") + .HasMaxLength(8) + .HasColumnType("character varying(8)"); + + b1.HasKey("VehicleId"); + + b1.ToTable("VehicleSettings"); + + b1.WithOwner() + .HasForeignKey("VehicleId"); + }); + + b.Navigation("Settings"); + }); + + modelBuilder.Entity("GarageStack.Core.Models.VehiclePhoneTracker", b => + { + b.HasOne("GarageStack.Core.Models.Vehicle", "Vehicle") + .WithMany() + .HasForeignKey("VehicleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Vehicle"); + }); + + modelBuilder.Entity("GarageStack.Core.Models.MaintenanceItem", b => + { + b.Navigation("LogEntries"); + }); + + modelBuilder.Entity("GarageStack.Core.Models.Vehicle", b => + { + b.Navigation("TelemetrySnapshots"); + }); +#pragma warning restore 612, 618 + } +} diff --git a/src/GarageStack.Data/Migrations/20261126205019_AddPushSubscriptionVehicleExclusions.cs b/src/GarageStack.Data/Migrations/20261126205019_AddPushSubscriptionVehicleExclusions.cs new file mode 100644 index 00000000..26c4607a --- /dev/null +++ b/src/GarageStack.Data/Migrations/20261126205019_AddPushSubscriptionVehicleExclusions.cs @@ -0,0 +1,28 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace GarageStack.Data.Migrations; + +/// +public partial class _20261126205019_AddPushSubscriptionVehicleExclusions : Migration +{ + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "ExcludedCategoriesByVehicle", + table: "PushSubscriptions", + type: "jsonb", + nullable: false, + defaultValueSql: "'{}'::jsonb"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "ExcludedCategoriesByVehicle", + table: "PushSubscriptions"); + } +} diff --git a/src/GarageStack.Data/Migrations/AppDbContextModelSnapshot.cs b/src/GarageStack.Data/Migrations/AppDbContextModelSnapshot.cs index e61ada75..3c98eb90 100644 --- a/src/GarageStack.Data/Migrations/AppDbContextModelSnapshot.cs +++ b/src/GarageStack.Data/Migrations/AppDbContextModelSnapshot.cs @@ -17,7 +17,7 @@ partial class AppDbContextModelSnapshot : ModelSnapshot // If you encounter a merge conflict in the line below, it means you need to // discard one of the migration branches and recreate its migrations on top of // the other branch. See https://aka.ms/efcore-docs-migrations-conflicts for more info. - public override string LastMigrationId => "20261124185218_AddTripJoinSnapshot"; + public override string LastMigrationId => "20261126205019_AddPushSubscriptionVehicleExclusions"; protected override void BuildModel(ModelBuilder modelBuilder) { @@ -628,6 +628,12 @@ protected override void BuildModel(ModelBuilder modelBuilder) .HasColumnType("text[]") .HasDefaultValueSql("'{}'::text[]"); + b.Property("ExcludedCategoriesByVehicle") + .IsRequired() + .ValueGeneratedOnAdd() + .HasColumnType("jsonb") + .HasDefaultValueSql("'{}'::jsonb"); + b.PrimitiveCollection>("IncludedCategories") .IsRequired() .ValueGeneratedOnAdd() diff --git a/src/GarageStack.Data/Repositories/PushSubscriptionRepository.cs b/src/GarageStack.Data/Repositories/PushSubscriptionRepository.cs index 77d7b688..1e1fce30 100644 --- a/src/GarageStack.Data/Repositories/PushSubscriptionRepository.cs +++ b/src/GarageStack.Data/Repositories/PushSubscriptionRepository.cs @@ -1,3 +1,4 @@ +using GarageStack.Core.Helpers; using GarageStack.Core.Interfaces; using GarageStack.Core.Models; using Microsoft.EntityFrameworkCore; @@ -11,7 +12,8 @@ public async Task> ListAsync(CancellationToken c public async Task UpsertAsync( string endpoint, string p256DhKey, string authKey, IReadOnlyList? excludedCategories, - IReadOnlyList? includedCategories, CancellationToken ct = default) + IReadOnlyList? includedCategories, IReadOnlyDictionary>? excludedCategoriesByVehicle, + CancellationToken ct = default) { var existing = await db.PushSubscriptions.FirstOrDefaultAsync(s => s.Endpoint == endpoint, ct); @@ -22,7 +24,9 @@ public async Task UpsertAsync( var keysChanged = existing.P256DhKey != p256DhKey || existing.AuthKey != authKey; var exclusionsChanged = excludedCategories is not null && !excludedCategories.SequenceEqual(existing.ExcludedCategories); var inclusionsChanged = includedCategories is not null && !includedCategories.SequenceEqual(existing.IncludedCategories); - if (!keysChanged && !exclusionsChanged && !inclusionsChanged) + var vehicleExclusionsChanged = excludedCategoriesByVehicle is not null + && !VehicleCategoryExclusions.AreEqual(excludedCategoriesByVehicle, existing.ExcludedCategoriesByVehicle); + if (!keysChanged && !exclusionsChanged && !inclusionsChanged && !vehicleExclusionsChanged) return; existing.P256DhKey = p256DhKey; @@ -31,6 +35,8 @@ public async Task UpsertAsync( existing.ExcludedCategories = [.. excludedCategories]; if (includedCategories is not null) existing.IncludedCategories = [.. includedCategories]; + if (excludedCategoriesByVehicle is not null) + existing.ExcludedCategoriesByVehicle = new(excludedCategoriesByVehicle); await db.SaveChangesAsync(ct); return; } @@ -42,6 +48,7 @@ public async Task UpsertAsync( AuthKey = authKey, ExcludedCategories = [.. excludedCategories ?? []], IncludedCategories = [.. includedCategories ?? []], + ExcludedCategoriesByVehicle = new(excludedCategoriesByVehicle ?? new Dictionary>()), }); try diff --git a/src/GarageStack.Tests/NotificationCategoriesTests.cs b/src/GarageStack.Tests/NotificationCategoriesTests.cs index f8e124df..83c29e6a 100644 --- a/src/GarageStack.Tests/NotificationCategoriesTests.cs +++ b/src/GarageStack.Tests/NotificationCategoriesTests.cs @@ -55,6 +55,62 @@ public void IsWanted_NotificationWithoutAType_AlwaysGoesOut() Assert.True(NotificationCategories.IsWanted(null, ["engine-start"])); } + // A type switched off for one car leaves out that car's notifications of it, and no other car's. + [Fact] + public void IsWanted_TypeSwitchedOffForOneCar_IsLeftOutForThatCarOnly() + { + IReadOnlyCollection offForThisCar = ["doors-open-parked"]; + + Assert.False(NotificationCategories.IsWanted("doors-open-parked", [], null, offForThisCar)); + Assert.True(NotificationCategories.IsWanted("doors-open-parked", [], null, null)); + Assert.True(NotificationCategories.IsWanted("doors-open-parked", [], null, ["low-tyre"])); + Assert.True(NotificationCategories.IsWanted("low-tyre", [], null, offForThisCar)); + } + + // Either list keeps a type out: the device's own does not come back for a car that has it on. + [Fact] + public void IsWanted_TypeSwitchedOffForEveryCar_StaysOutWhateverTheCarSays() + { + Assert.False(NotificationCategories.IsWanted("engine-start", ["engine-start"], null, [])); + Assert.False(NotificationCategories.IsWanted("engine-start", ["engine-start"], null, ["engine-start"])); + } + + // The per-car list names the type the checklist offers, so a car's maintenance and RDW types + // switch off as a group, as they do for the whole device. + [Fact] + public void IsWanted_GroupedTypeSwitchedOffForOneCar_LeavesOutEveryOfItsCategories() + { + Assert.False(NotificationCategories.IsWanted("maintenance-overdue-3", [], null, ["maintenance"])); + Assert.False(NotificationCategories.IsWanted("rdw-recall-MGP230061", [], null, ["rdw"])); + } + + // A summary is switched on for the device and can still be switched off for one car. + [Fact] + public void IsWanted_OptInTypeSwitchedOffForOneCar_IsLeftOutForThatCar() + { + Assert.False(NotificationCategories.IsWanted("weekly-summary", [], ["weekly-summary"], ["weekly-summary"])); + Assert.True(NotificationCategories.IsWanted("weekly-summary", [], ["weekly-summary"], ["low-tyre"])); + Assert.False(NotificationCategories.IsWanted("weekly-summary", [], null, [])); + } + + // A notification without a type, or without a car, answers to what the checklist can switch off. + [Fact] + public void IsWanted_NotificationWithoutATypeOrACar_IgnoresThePerCarList() + { + Assert.True(NotificationCategories.IsWanted(null, [], null, ["gateway-login", "engine-start"])); + Assert.True(NotificationCategories.IsWanted("gateway-login", [], null, null)); + } + + [Fact] + public void ExcludedCategoriesFor_ReturnsTheTypesOffForThatCarAndNullForOthers() + { + var subscription = new PushSubscription { ExcludedCategoriesByVehicle = { [7] = ["low-tyre"] } }; + + Assert.Equal(["low-tyre"], subscription.ExcludedCategoriesFor(7)); + Assert.Null(subscription.ExcludedCategoriesFor(8)); + Assert.Null(subscription.ExcludedCategoriesFor(null)); + } + // A summary every week unasked would be noise, so it goes out only to a device that asked. [Fact] public void IsWanted_OptInType_GoesOutOnlyOnceSwitchedOn() diff --git a/src/GarageStack.Tests/Postgres/PushSubscriptionPostgresTests.cs b/src/GarageStack.Tests/Postgres/PushSubscriptionPostgresTests.cs new file mode 100644 index 00000000..4c4894bd --- /dev/null +++ b/src/GarageStack.Tests/Postgres/PushSubscriptionPostgresTests.cs @@ -0,0 +1,71 @@ +using GarageStack.Api.Endpoints; +using GarageStack.Data.Repositories; +using Microsoft.EntityFrameworkCore; + +namespace GarageStack.Tests; + +// What a device switched off for one car is a jsonb column with a converter, which the in-memory +// database does not exercise: its type, its default for the rows that existed before it, and the +// change tracking that decides whether a registration writes at all. +public class PushSubscriptionPostgresTests +{ + private const string Endpoint = "https://push.example/abc"; + + [Fact] + public async Task TheTypesForACar_SurviveARoundTripThroughJsonb() + { + var ct = TestContext.Current.CancellationToken; + await using var database = await PostgresDatabase.CreateAsync(ct); + await using (var db = database.CreateContext()) + { + await PushEndpoints.UpsertSubscriptionAsync(new PushSubscriptionRepository(db), new PushSubscribeRequest(Endpoint, "p256dh", "auth", + ["maintenance"], null, new Dictionary> { [12] = ["low-tyre", "engine-start"], [3] = ["rdw"] }), ct); + } + + await using var check = database.CreateContext(); + var stored = Assert.Single(await new PushSubscriptionRepository(check).ListAsync(ct)); + Assert.Equal([3, 12], stored.ExcludedCategoriesByVehicle.Keys.Order()); + Assert.Equal(["engine-start", "low-tyre"], stored.ExcludedCategoriesByVehicle[12]); + Assert.Equal(["rdw"], stored.ExcludedCategoriesFor(3)); + Assert.Equal(["maintenance"], stored.ExcludedCategories); + } + + [Fact] + public async Task ChangingACarsTypes_IsWrittenAndTheSameChoiceIsNot() + { + var ct = TestContext.Current.CancellationToken; + await using var database = await PostgresDatabase.CreateAsync(ct); + await using var db = database.CreateContext(); + var repo = new PushSubscriptionRepository(db); + PushSubscribeRequest Req(params string[] types) => new(Endpoint, "p256dh", "auth", + ExcludedCategoriesByVehicle: new Dictionary> { [1] = types }); + await PushEndpoints.UpsertSubscriptionAsync(repo, Req("low-tyre"), ct); + + await PushEndpoints.UpsertSubscriptionAsync(repo, Req("low-tyre"), ct); + Assert.DoesNotContain(db.ChangeTracker.Entries(), e => e.State != EntityState.Unchanged); + + await PushEndpoints.UpsertSubscriptionAsync(repo, Req("low-tyre", "low-fuel"), ct); + + await using var check = database.CreateContext(); + Assert.Equal(["low-fuel", "low-tyre"], Assert.Single(await new PushSubscriptionRepository(check).ListAsync(ct)).ExcludedCategoriesByVehicle[1]); + } + + // A subscription from before the column wants every type for every car, and reads as that. + [Fact] + public async Task ASubscriptionWithoutTheColumnsValue_HasNoTypesOffForAnyCar() + { + var ct = TestContext.Current.CancellationToken; + await using var database = await PostgresDatabase.CreateAsync(ct); + await using (var db = database.CreateContext()) + { + await db.Database.ExecuteSqlRawAsync( + "INSERT INTO \"PushSubscriptions\" (\"Endpoint\", \"P256DhKey\", \"AuthKey\", \"CreatedAt\") VALUES ({0}, 'k', 'a', now())", + [Endpoint], ct); + } + + await using var check = database.CreateContext(); + var stored = Assert.Single(await new PushSubscriptionRepository(check).ListAsync(ct)); + Assert.Empty(stored.ExcludedCategoriesByVehicle); + Assert.Null(stored.ExcludedCategoriesFor(1)); + } +} diff --git a/src/GarageStack.Tests/PushSubscriptionUpsertTests.cs b/src/GarageStack.Tests/PushSubscriptionUpsertTests.cs index ace148f3..5d6a5455 100644 --- a/src/GarageStack.Tests/PushSubscriptionUpsertTests.cs +++ b/src/GarageStack.Tests/PushSubscriptionUpsertTests.cs @@ -128,6 +128,84 @@ public async Task ARequestWithoutTheList_KeepsTheStoredTypes() Assert.Equal(["engine-start"], stored.ExcludedCategories); } + // ── The types each device switched off for one car ───────────────────────── + + [Fact] + public async Task StoresTheTypesSwitchedOffForOneCar_KnownOnesOnlyAndInOneOrder() + { + var ct = TestContext.Current.CancellationToken; + await using var db = CreateDb(); + var byVehicle = new Dictionary> + { + [4] = ["low-tyre", "engine-start", "not-a-type", "low-tyre"], + [2] = ["not-a-type"], + }; + + await PushEndpoints.UpsertSubscriptionAsync(new PushSubscriptionRepository(db), + new PushSubscribeRequest(Endpoint, "p256dh", "auth", ExcludedCategoriesByVehicle: byVehicle), ct); + + var stored = await db.PushSubscriptions.SingleAsync(ct); + Assert.Equal([4], stored.ExcludedCategoriesByVehicle.Keys); + Assert.Equal(["engine-start", "low-tyre"], stored.ExcludedCategoriesByVehicle[4]); + Assert.Empty(stored.ExcludedCategories); + } + + [Fact] + public async Task UpdatesTheTypesForACarWhenTheDeviceChangedThem_AndClearsACarWithNoneOff() + { + var ct = TestContext.Current.CancellationToken; + await using var db = CreateDb(); + var repo = new PushSubscriptionRepository(db); + await PushEndpoints.UpsertSubscriptionAsync(repo, new PushSubscribeRequest(Endpoint, "p256dh", "auth", + ExcludedCategoriesByVehicle: new Dictionary> { [1] = ["low-tyre"], [2] = ["engine-start"] }), ct); + + await PushEndpoints.UpsertSubscriptionAsync(repo, new PushSubscribeRequest(Endpoint, "p256dh", "auth", + ExcludedCategoriesByVehicle: new Dictionary> { [1] = ["maintenance"] }), ct); + + var stored = await db.PushSubscriptions.SingleAsync(ct); + Assert.Equal([1], stored.ExcludedCategoriesByVehicle.Keys); + Assert.Equal(["maintenance"], stored.ExcludedCategoriesByVehicle[1]); + } + + // An empty map is a choice (every car back to the device's own list); a missing one is not. + [Fact] + public async Task AnEmptyMapClearsTheCarsTypes_AndAMissingOneKeepsThem() + { + var ct = TestContext.Current.CancellationToken; + await using var db = CreateDb(); + var repo = new PushSubscriptionRepository(db); + await PushEndpoints.UpsertSubscriptionAsync(repo, new PushSubscribeRequest(Endpoint, "p256dh", "auth", + ExcludedCategoriesByVehicle: new Dictionary> { [1] = ["low-tyre"] }), ct); + + await PushEndpoints.UpsertSubscriptionAsync(repo, new PushSubscribeRequest(Endpoint, "p256dh", "auth", ["engine-start"]), ct); + Assert.Equal(["low-tyre"], (await db.PushSubscriptions.SingleAsync(ct)).ExcludedCategoriesByVehicle[1]); + + await PushEndpoints.UpsertSubscriptionAsync(repo, new PushSubscribeRequest(Endpoint, "p256dh", "auth", + ExcludedCategoriesByVehicle: new Dictionary>()), ct); + var stored = await db.PushSubscriptions.SingleAsync(ct); + Assert.Empty(stored.ExcludedCategoriesByVehicle); + Assert.Equal(["engine-start"], stored.ExcludedCategories); + } + + // The page registers its subscription on every load: the same choice listed in another order + // must not look like a change. + [Fact] + public async Task TheSameChoiceInAnotherOrder_IsNotAChange() + { + var ct = TestContext.Current.CancellationToken; + await using var db = CreateDb(); + var repo = new PushSubscriptionRepository(db); + await PushEndpoints.UpsertSubscriptionAsync(repo, new PushSubscribeRequest(Endpoint, "p256dh", "auth", + ExcludedCategoriesByVehicle: new Dictionary> { [1] = ["low-tyre", "engine-start"] }), ct); + db.ChangeTracker.Clear(); + + await PushEndpoints.UpsertSubscriptionAsync(repo, new PushSubscribeRequest(Endpoint, "p256dh", "auth", + ExcludedCategoriesByVehicle: new Dictionary> { [1] = ["engine-start", "low-tyre"] }), ct); + + Assert.DoesNotContain(db.ChangeTracker.Entries(), e => e.State != EntityState.Unchanged); + Assert.Equal(["engine-start", "low-tyre"], (await db.PushSubscriptions.SingleAsync(ct)).ExcludedCategoriesByVehicle[1]); + } + // The Worker drops the subscriptions a push service reported gone; others stay, and an // endpoint that was never stored is no error. [Fact] @@ -136,8 +214,8 @@ public async Task Remove_DropsOnlyTheNamedEndpoints() var ct = TestContext.Current.CancellationToken; await using var db = CreateDb(); var repo = new PushSubscriptionRepository(db); - await repo.UpsertAsync(Endpoint, "p256dh", "auth", null, null, ct); - await repo.UpsertAsync("https://push.example/other", "p256dh", "auth", null, null, ct); + await repo.UpsertAsync(Endpoint, "p256dh", "auth", null, null, null, ct); + await repo.UpsertAsync("https://push.example/other", "p256dh", "auth", null, null, null, ct); await repo.RemoveAsync([Endpoint, "https://push.example/unknown"], ct); diff --git a/src/GarageStack.Tests/VehicleCategoryExclusionsTests.cs b/src/GarageStack.Tests/VehicleCategoryExclusionsTests.cs new file mode 100644 index 00000000..78323f89 --- /dev/null +++ b/src/GarageStack.Tests/VehicleCategoryExclusionsTests.cs @@ -0,0 +1,86 @@ +using GarageStack.Core.Helpers; + +namespace GarageStack.Tests; + +// What a device switched off for one car arrives from the browser and is stored as JSON, so an +// unchanged choice has to come out the same however the page listed it. +public class VehicleCategoryExclusionsTests +{ + private static Dictionary> Request(params (int Vehicle, string[] Types)[] entries) => + entries.ToDictionary(e => e.Vehicle, e => (IReadOnlyList)e.Types); + + [Fact] + public void Normalize_KeepsKnownTypesOnceEachInOneOrder() + { + var result = VehicleCategoryExclusions.Normalize(Request((2, ["low-tyre", "engine-start", "not-a-type", "low-tyre"]))); + + Assert.Equal(["engine-start", "low-tyre"], result[2]); + } + + // A car with nothing off needs no entry: it is the same as a car the device never mentioned. + [Fact] + public void Normalize_DropsCarsWithNoKnownTypeOff() + { + var result = VehicleCategoryExclusions.Normalize(Request((1, []), (2, ["not-a-type"]), (3, ["low-tyre"]))); + + Assert.Equal([3], result.Keys); + } + + [Theory] + [InlineData(0)] + [InlineData(-4)] + public void Normalize_DropsAVehicleIdNoCarHas(int vehicleId) + { + Assert.Empty(VehicleCategoryExclusions.Normalize(Request((vehicleId, ["low-tyre"])))); + } + + // The map comes from the browser and every push reads it, so it is held to a size. + [Fact] + public void Normalize_KeepsTheLowestIdsWhenThereAreMoreCarsThanAnAccountHas() + { + var many = Request(Enumerable.Range(1, VehicleCategoryExclusions.MaxVehicles + 10) + .Select(id => (id, new[] { "low-tyre" })).ToArray()); + + var result = VehicleCategoryExclusions.Normalize(many); + + Assert.Equal(VehicleCategoryExclusions.MaxVehicles, result.Count); + Assert.Contains(1, result.Keys); + Assert.DoesNotContain(VehicleCategoryExclusions.MaxVehicles + 1, result.Keys); + } + + [Fact] + public void AreEqual_ComparesTheTypesPerCar() + { + var a = new Dictionary> { [1] = ["low-tyre"], [2] = ["engine-start"] }; + + Assert.True(VehicleCategoryExclusions.AreEqual(a, new Dictionary> { [2] = ["engine-start"], [1] = ["low-tyre"] })); + Assert.False(VehicleCategoryExclusions.AreEqual(a, new Dictionary> { [1] = ["low-tyre"] })); + Assert.False(VehicleCategoryExclusions.AreEqual(a, new Dictionary> { [1] = ["low-tyre"], [2] = ["low-fuel"] })); + Assert.False(VehicleCategoryExclusions.AreEqual(a, new Dictionary> { [1] = ["low-tyre"], [3] = ["engine-start"] })); + } + + [Fact] + public void Json_RoundTrips_AndWritesTheSameTextForTheSameChoice() + { + var choice = VehicleCategoryExclusions.Normalize(Request((9, ["low-tyre", "engine-start"]), (4, ["maintenance"]))); + + var json = VehicleCategoryExclusions.ToJson(choice); + + Assert.Equal("""{"4":["maintenance"],"9":["engine-start","low-tyre"]}""", json); + Assert.True(VehicleCategoryExclusions.AreEqual(choice, VehicleCategoryExclusions.FromJson(json))); + } + + // A column that was never written, or holds something else, must not stop a notification going out. + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(" ")] + [InlineData("{}")] + [InlineData("not json")] + [InlineData("""{"abc":["low-tyre"]}""")] + [InlineData("[1,2]")] + public void FromJson_AnythingUnreadable_MeansNoExclusions(string? json) + { + Assert.Empty(VehicleCategoryExclusions.FromJson(json)); + } +} diff --git a/src/GarageStack.Worker/Services/PushSenderService.cs b/src/GarageStack.Worker/Services/PushSenderService.cs index 264a421a..240e0eda 100644 --- a/src/GarageStack.Worker/Services/PushSenderService.cs +++ b/src/GarageStack.Worker/Services/PushSenderService.cs @@ -103,10 +103,12 @@ public async Task SendToAllAsync(string title, string body, CancellationToken ct using var scope = _scopeFactory.CreateScope(); var subscriptionRepository = scope.ServiceProvider.GetRequiredService(); - // Each device switched its own types off. The in-app record above is shared and kept - // regardless; only the push to a device that does not want this type is left out. + // Each device switched its own types off, for every car or for one. The in-app record above + // is shared and kept regardless; only the push to a device that does not want this type + // for this car is left out. var subscriptions = (await subscriptionRepository.ListAsync(ct)) - .Where(s => NotificationCategories.IsWanted(category, s.ExcludedCategories, s.IncludedCategories)) + .Where(s => NotificationCategories.IsWanted( + category, s.ExcludedCategories, s.IncludedCategories, s.ExcludedCategoriesFor(vehicleId))) .ToList(); if (subscriptions.Count == 0) return;