Add push notification functionality with tests and digest scheduler
All checks were successful
Chore App Build, Test, and Push Docker Images / build-and-push (push) Successful in 2m14s

- Implemented push subscription API with tests for subscribing and unsubscribing users.
- Created web push notification tests triggered by child actions.
- Added digest scheduler to send email digests to users at 9 PM local time.
- Developed utility functions for creating and validating digest action tokens.
- Integrated web push sender to handle sending notifications to users.
- Added service worker for handling push notifications in the frontend.
- Created a push opt-in component for user notification preferences.
- Implemented tests for the push opt-in component to ensure correct behavior.
- Updated frontend services to manage push subscriptions and permissions.
This commit is contained in:
2026-04-15 21:56:10 -04:00
parent 0d50a324a3
commit ad2bdf4c4f
47 changed files with 3177 additions and 197 deletions

View File

@@ -14,6 +14,9 @@ vi.mock('../../stores/auth', () => ({
isParentPersistent: { value: false },
logoutParent: vi.fn(),
logoutUser: vi.fn(),
consumePendingReturnUrl: vi.fn(() => null),
hasPendingReturnUrl: vi.fn(() => false),
clearPendingReturnUrl: vi.fn(),
}))
vi.mock('@/common/imageCache', () => ({

View File

@@ -612,6 +612,22 @@ async function fetchChildData(id: string | number) {
}
}
function applyHighlightPulse(itemId: string) {
// Delay slightly so the scroll animation has time to settle
setTimeout(() => {
const el = document.querySelector(`[data-item-id="${itemId}"]`)
if (!el) return
el.classList.add('highlight-pulse')
el.addEventListener(
'animationend',
() => {
el.classList.remove('highlight-pulse')
},
{ once: true },
)
}, 200)
}
onMounted(async () => {
try {
eventBus.on('child_task_triggered', handleTaskTriggered)
@@ -648,8 +664,10 @@ onMounted(async () => {
setTimeout(() => {
if (entityType === 'chore') {
childChoreListRef.value?.scrollToItem(scrollToId)
applyHighlightPulse(scrollToId)
} else if (entityType === 'reward') {
childRewardListRef.value?.scrollToItem(scrollToId)
applyHighlightPulse(scrollToId)
}
}, 500)
}
@@ -1404,4 +1422,23 @@ function goToAssignRewards() {
.input-group input.invalid {
border-color: var(--error-color, #e53e3e);
}
@keyframes highlight-pulse {
0% {
box-shadow: 0 0 0 0 var(--accent, #4a90e2);
outline: 2px solid var(--accent, #4a90e2);
}
50% {
box-shadow: 0 0 16px 4px var(--accent, #4a90e2);
outline: 2px solid var(--accent, #4a90e2);
}
100% {
box-shadow: none;
outline: none;
}
}
:global(.highlight-pulse) {
animation: highlight-pulse 1.8s ease-out forwards;
}
</style>

View File

@@ -538,4 +538,56 @@ describe('ParentView', () => {
expect(wrapper.vm.selectedChoreId).toBe(null)
})
})
describe('Highlight pulse animation', () => {
beforeEach(() => {
vi.useFakeTimers()
})
afterEach(() => {
vi.useRealTimers()
})
it('adds highlight-pulse class to element with matching data-item-id', async () => {
const el = document.createElement('div')
el.setAttribute('data-item-id', 'task-1')
document.body.appendChild(el)
wrapper = mount(ParentView, mountOptions)
wrapper.vm.applyHighlightPulse('task-1')
vi.advanceTimersByTime(200)
expect(el.classList.contains('highlight-pulse')).toBe(true)
document.body.removeChild(el)
})
it('removes highlight-pulse class when animationend fires', async () => {
const el = document.createElement('div')
el.setAttribute('data-item-id', 'task-1')
document.body.appendChild(el)
wrapper = mount(ParentView, mountOptions)
wrapper.vm.applyHighlightPulse('task-1')
vi.advanceTimersByTime(200)
expect(el.classList.contains('highlight-pulse')).toBe(true)
el.dispatchEvent(new Event('animationend'))
expect(el.classList.contains('highlight-pulse')).toBe(false)
document.body.removeChild(el)
})
it('does nothing when no element with matching data-item-id exists', () => {
wrapper = mount(ParentView, mountOptions)
// Should not throw
expect(() => {
wrapper.vm.applyHighlightPulse('nonexistent-id')
vi.advanceTimersByTime(200)
}).not.toThrow()
})
})
})

View File

@@ -0,0 +1,91 @@
<template>
<div v-if="showBanner" class="push-opt-in-banner" role="status" aria-live="polite">
<template v-if="permissionState === 'default'">
<span class="push-opt-in-text"
>Enable notifications to stay updated on chores and rewards.</span
>
<button class="btn btn-primary push-opt-in-btn" @click="onEnable">Enable</button>
<button class="push-opt-in-dismiss" @click="dismiss" aria-label="Dismiss"></button>
</template>
<template v-else-if="permissionState === 'denied'">
<span class="push-opt-in-text"
>Notifications are blocked. Enable them in your browser settings to receive alerts.</span
>
<button class="push-opt-in-dismiss" @click="dismiss" aria-label="Dismiss"></button>
</template>
</div>
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { subscribeToPush, getPushPermissionState } from '@/services/pushSubscription'
const permissionState = ref<NotificationPermission | 'unsupported'>('default')
const dismissed = ref(false)
const showBanner = ref(false)
onMounted(() => {
if (!('Notification' in window)) {
return
}
permissionState.value = Notification.permission
if (permissionState.value === 'granted') {
// Already granted — ensure subscription is registered silently
subscribeToPush()
return
}
showBanner.value = true
})
async function onEnable() {
const success = await subscribeToPush()
if (success) {
permissionState.value = 'granted'
showBanner.value = false
} else {
permissionState.value = Notification.permission as NotificationPermission
}
}
function dismiss() {
dismissed.value = true
showBanner.value = false
}
</script>
<style scoped>
.push-opt-in-banner {
display: flex;
align-items: center;
gap: 0.75rem;
background: var(--list-item-bg, #f0f4ff);
border: 1px solid var(--btn-primary, #4a90e2);
border-radius: 8px;
padding: 0.6rem 1rem;
margin: 0.5rem 0;
font-size: 0.88rem;
flex-wrap: wrap;
}
.push-opt-in-text {
flex: 1;
min-width: 0;
}
.push-opt-in-btn {
font-size: 0.85rem;
padding: 0.35rem 0.9rem;
white-space: nowrap;
}
.push-opt-in-dismiss {
background: none;
border: none;
cursor: pointer;
color: var(--text-muted, #888);
font-size: 1rem;
padding: 0 0.25rem;
line-height: 1;
}
</style>

View File

@@ -0,0 +1,133 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { mount, flushPromises } from '@vue/test-utils'
import PushOptIn from '../PushOptIn.vue'
const mockSubscribeToPush = vi.fn()
const mockGetPushPermissionState = vi.fn()
vi.mock('@/services/pushSubscription', () => ({
subscribeToPush: () => mockSubscribeToPush(),
getPushPermissionState: () => mockGetPushPermissionState(),
}))
function setupNotificationMock(permission: NotificationPermission) {
Object.defineProperty(window, 'Notification', {
writable: true,
value: { permission },
})
}
describe('PushOptIn', () => {
afterEach(() => {
vi.clearAllMocks()
})
describe('permission already granted on mount', () => {
beforeEach(() => {
setupNotificationMock('granted')
mockSubscribeToPush.mockResolvedValue(true)
})
it('silently calls subscribeToPush without showing the banner', async () => {
const wrapper = mount(PushOptIn)
await flushPromises()
expect(mockSubscribeToPush).toHaveBeenCalledOnce()
expect(wrapper.find('.push-opt-in-banner').exists()).toBe(false)
})
})
describe('permission default (not yet asked)', () => {
beforeEach(() => {
setupNotificationMock('default')
})
it('shows the opt-in banner with Enable button', async () => {
const wrapper = mount(PushOptIn)
await flushPromises()
expect(wrapper.find('.push-opt-in-banner').exists()).toBe(true)
expect(wrapper.find('.push-opt-in-btn').text()).toBe('Enable')
})
it('does NOT call subscribeToPush on mount', async () => {
mount(PushOptIn)
await flushPromises()
expect(mockSubscribeToPush).not.toHaveBeenCalled()
})
it('calls subscribeToPush when Enable button is clicked', async () => {
mockSubscribeToPush.mockResolvedValue(true)
const wrapper = mount(PushOptIn)
await flushPromises()
await wrapper.find('.push-opt-in-btn').trigger('click')
await flushPromises()
expect(mockSubscribeToPush).toHaveBeenCalledOnce()
})
it('hides banner after Enable is clicked and subscription succeeds', async () => {
mockSubscribeToPush.mockResolvedValue(true)
const wrapper = mount(PushOptIn)
await flushPromises()
await wrapper.find('.push-opt-in-btn').trigger('click')
await flushPromises()
expect(wrapper.find('.push-opt-in-banner').exists()).toBe(false)
})
it('does NOT post subscription to backend when subscribeToPush returns false', async () => {
mockSubscribeToPush.mockResolvedValue(false)
const wrapper = mount(PushOptIn)
await flushPromises()
await wrapper.find('.push-opt-in-btn').trigger('click')
await flushPromises()
// Banner should still be visible (permission was denied)
expect(wrapper.find('.push-opt-in-banner').exists()).toBe(true)
})
it('hides banner on dismiss without calling subscribeToPush', async () => {
const wrapper = mount(PushOptIn)
await flushPromises()
await wrapper.find('.push-opt-in-dismiss').trigger('click')
await flushPromises()
expect(mockSubscribeToPush).not.toHaveBeenCalled()
expect(wrapper.find('.push-opt-in-banner').exists()).toBe(false)
})
})
describe('permission denied', () => {
beforeEach(() => {
setupNotificationMock('denied')
})
it('shows the blocked message banner', async () => {
const wrapper = mount(PushOptIn)
await flushPromises()
expect(wrapper.find('.push-opt-in-banner').exists()).toBe(true)
expect(wrapper.find('.push-opt-in-banner').text()).toContain('blocked')
})
it('does NOT show the Enable button when permission is denied', async () => {
const wrapper = mount(PushOptIn)
await flushPromises()
expect(wrapper.find('.push-opt-in-btn').exists()).toBe(false)
})
it('does NOT call subscribeToPush on mount when already denied', async () => {
mount(PushOptIn)
await flushPromises()
expect(mockSubscribeToPush).not.toHaveBeenCalled()
})
})
})

View File

@@ -32,6 +32,29 @@
</div>
</template>
</EntityEditForm>
<div class="digest-section">
<div class="digest-row">
<div class="digest-label">
<span class="digest-title">Daily Email Digest</span>
<span class="digest-desc"
>Receive a 9pm summary of pending chore and reward requests with one-click approve/deny
links.</span
>
</div>
<button
type="button"
:class="['toggle-btn', { active: emailDigestEnabled }]"
:aria-pressed="emailDigestEnabled"
:disabled="savingDigest"
@click="toggleDigest"
>
<span class="toggle-knob" />
</button>
</div>
<div v-if="digestError" class="error-message digest-error">{{ digestError }}</div>
</div>
<div v-if="errorMsg" class="error-message" aria-live="polite">{{ errorMsg }}</div>
<ModalDialog
v-if="showModal"
@@ -124,6 +147,10 @@ const showDeleteSuccess = ref(false)
const showDeleteError = ref(false)
const deleteErrorMessage = ref('')
const emailDigestEnabled = ref(true)
const savingDigest = ref(false)
const digestError = ref('')
const initialData = ref<{
image_id: string | null
first_name: string
@@ -162,6 +189,7 @@ onMounted(async () => {
last_name: data.last_name || '',
email: data.email || '',
}
emailDigestEnabled.value = data.email_digest_enabled !== false
} catch {
errorMsg.value = 'Could not load user profile.'
} finally {
@@ -283,6 +311,25 @@ async function resetPassword() {
}
}
async function toggleDigest() {
digestError.value = ''
const newValue = !emailDigestEnabled.value
savingDigest.value = true
try {
const res = await fetch('/api/user/profile', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email_digest_enabled: newValue }),
})
if (!res.ok) throw new Error('Failed to update preference')
emailDigestEnabled.value = newValue
} catch {
digestError.value = 'Failed to save notification preference.'
} finally {
savingDigest.value = false
}
}
function goToChangeParentPin() {
router.push({ name: 'ParentPinSetup' })
}
@@ -429,4 +476,80 @@ function closeDeleteError() {
outline: none;
border-color: var(--btn-primary, #4a90e2);
}
.digest-section {
margin-top: 1.5rem;
padding: 1rem 1.2rem;
border-radius: 10px;
background: var(--list-item-bg, #f9f9f9);
border: 1px solid var(--form-input-border, #e6e6e6);
}
.digest-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 1rem;
}
.digest-label {
display: flex;
flex-direction: column;
gap: 0.2rem;
}
.digest-title {
font-weight: 600;
font-size: 0.97rem;
color: var(--text, #1a1a1a);
}
.digest-desc {
font-size: 0.83rem;
color: var(--text-muted, #666);
line-height: 1.4;
}
.digest-error {
margin-top: 0.5rem;
}
.toggle-btn {
flex-shrink: 0;
width: 44px;
height: 24px;
border-radius: 12px;
border: none;
background: var(--form-input-border, #ccc);
cursor: pointer;
position: relative;
transition: background 0.2s;
padding: 0;
}
.toggle-btn.active {
background: var(--btn-primary, #4a90e2);
}
.toggle-btn:disabled {
opacity: 0.6;
cursor: not-allowed;
}
.toggle-knob {
display: block;
width: 18px;
height: 18px;
border-radius: 50%;
background: white;
position: absolute;
top: 3px;
left: 3px;
transition: left 0.2s;
pointer-events: none;
}
.toggle-btn.active .toggle-knob {
left: 23px;
}
</style>

View File

@@ -8,6 +8,9 @@ import {
isParentPersistent,
logoutParent,
logoutUser,
consumePendingReturnUrl,
hasPendingReturnUrl,
clearPendingReturnUrl,
} from '../../stores/auth'
import { getCachedImageUrl, getCachedImageBlob } from '@/common/imageCache'
import '@/assets/styles.css'
@@ -105,6 +108,7 @@ const close = () => {
show.value = false
error.value = ''
stayInParentMode.value = false
clearPendingReturnUrl()
}
const submit = async () => {
@@ -136,7 +140,8 @@ const submit = async () => {
// Authenticate parent and navigate
authenticateParent(stayInParentMode.value)
close()
router.push('/parent')
const returnUrl = consumePendingReturnUrl()
router.push(returnUrl || '/parent')
} catch (e) {
error.value = 'Network error'
}
@@ -253,6 +258,9 @@ onMounted(() => {
eventBus.on('profile_updated', fetchUserProfile)
document.addEventListener('mousedown', handleClickOutside)
fetchUserProfile()
if (!isParentAuthenticated.value && hasPendingReturnUrl()) {
open()
}
})
onUnmounted(() => {

View File

@@ -206,6 +206,7 @@ onBeforeUnmount(() => {
props.getItemClass?.(item),
{ 'item-ready': props.readyItemId === item.id },
]"
:data-item-id="item.id"
:ref="(el) => (itemRefs[item.id] = el)"
@click.stop="handleClicked(item)"
>

View File

@@ -32,6 +32,9 @@ vi.mock('../../../stores/auth', () => ({
isParentPersistent: isParentPersistentRef,
logoutParent: vi.fn(),
logoutUser: vi.fn(),
consumePendingReturnUrl: vi.fn(() => null),
hasPendingReturnUrl: vi.fn(() => false),
clearPendingReturnUrl: vi.fn(),
}))
global.fetch = vi.fn()