Feature 16: Google Calendar Sync (#130)
CI / ci (push) Successful in 4m51s

Co-authored-by: orchestrator-agent <20+orchestrator-agent@code.cubecraftcreations.com>
This commit was merged in pull request #130.
This commit is contained in:
2026-10-08 03:13:21 -04:00
committed by approver_agent
parent 5ac5982c1f
commit 7003ff92ec
65 changed files with 8092 additions and 222 deletions
+18 -3
View File
@@ -258,9 +258,9 @@
color: var(--color-neutral-700);
}
/* An action with nothing behind it yet (Push to Calendar until Feature 16,
the shopping list until Feature 17): it keeps focus, so hovering, tapping
or focusing it shows the tooltip. */
/* An action with nothing behind it yet (the shopping list until Feature
17): it keeps focus, so hovering, tapping or focusing it shows the
tooltip. */
.unavailable {
position: relative;
display: flex;
@@ -406,6 +406,21 @@
color: var(--color-accent-2-800);
}
/* Under the Draft board's push button the line is centred and may wrap. */
.mobileStatus {
flex: none;
justify-content: center;
white-space: normal;
text-align: center;
}
/* A push failure's way to the Google Calendar settings. */
.settingsLink {
color: inherit;
font-weight: 800;
text-decoration: underline;
}
.actions {
display: flex;
flex-wrap: wrap;
+359 -12
View File
@@ -15,6 +15,7 @@ const THIS_WEEK = '/api/v1/plans/2026-10-05'
const NEXT_WEEK = '/api/v1/plans/2026-10-12'
const PREVIOUS_WEEK = '/api/v1/plans/2026-09-28'
const DRAFT = `${THIS_WEEK}/draft`
const PUSH = `${THIS_WEEK}/push-calendar`
const JOB = '/api/v1/jobs/j1'
const DAYS = ['2026-10-05', '2026-10-06', '2026-10-07', '2026-10-08', '2026-10-09', '2026-10-10', '2026-10-11']
@@ -50,6 +51,21 @@ function planBody(status: string, names = NAMES) {
}
}
// syncedNow is the plan of the week of Oct 5 as a push answers it: synced
// at the tests' noon.
function syncedNow() {
return { ...planBody('synced'), calendar_synced_at: '2026-10-07T16:00:00Z' }
}
// deferred is a response the test sends when it chooses.
function deferred() {
let send!: (response: Response) => void
const response = new Promise<Response>((resolve) => {
send = resolve
})
return { response, send }
}
// draftJob is job j1 drafting the week of Oct 5 into plan planId: a
// redraft keeps the plan's id.
function draftJob(status: string, error: string | null = null, planId = 'plan-1') {
@@ -225,17 +241,312 @@ describe('PlanPage', () => {
expect(screen.queryByText('Draft')).not.toBeInTheDocument()
})
it('offers Push to Calendar unavailable, with a tooltip saying why', async () => {
const fetchMock = stubServer({ [`GET ${THIS_WEEK}`]: () => jsonResponse(200, planBody('draft')) })
it('pushes the plan to Calendar, showing progress, then the plan as synced', async () => {
const answer = deferred()
const fetchMock = stubServer({
[`GET ${THIS_WEEK}`]: () => jsonResponse(200, planBody('draft')),
[`POST ${PUSH}`]: () => answer.response,
})
await renderPage()
const push = await screen.findByRole('button', { name: 'Looks good — push to Calendar' })
expect(push).toHaveAttribute('aria-disabled', 'true')
expect(push).toHaveAccessibleDescription('Push to Calendar arrives once Google Calendar can be connected.')
expect(screen.getByRole('tooltip', { hidden: true })).toHaveTextContent('Push to Calendar arrives once Google Calendar can be connected.')
expect(await screen.findByText('Not pushed to Google Calendar yet')).toBeInTheDocument()
const push = screen.getByRole('button', { name: 'Looks good — push to Calendar' })
expect(declaredStyle(push).minHeight).toBe('50px')
fireEvent.click(push)
expect(posts(fetchMock)).toEqual([])
await waitFor(() => expect(posts(fetchMock)).toEqual([`${PUSH} undefined`]))
const call = fetchMock.mock.calls.find(([, init]) => init?.method === 'POST')!
expect(new Headers(call[1]?.headers).get('X-MealQuest-CSRF')).toBe(ME.csrfToken)
// In progress: the button says so and is disabled, as is Rebuild week,
// and no day can be swapped.
const pushing = await screen.findByRole('button', { name: 'Pushing to Calendar…' })
expect(pushing).toBeDisabled()
expect(pushing).toHaveAttribute('aria-busy', 'true')
expect(screen.getByRole('button', { name: 'Rebuild week' })).toBeDisabled()
fireEvent.click(within(tile('MON')).getByRole('button'))
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
answer.send(jsonResponse(200, syncedNow()))
const status = await screen.findByText('Synced to Google Calendar just now')
expect(declaredStyle(status).color).toBe('var(--color-accent-2-800)')
expect(status.querySelector('svg')).not.toBeNull()
expect(screen.getByText('Synced')).toBeInTheDocument()
expect(screen.queryByText('Draft')).not.toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Looks good — push to Calendar' })).toBeEnabled()
expect(screen.queryByRole('alert')).not.toBeInTheDocument()
// The plan shown is the one the push answered with: no second read.
expect(planReads(fetchMock)).toBe(1)
})
it('says a synced plan is on Google Calendar, and how long ago it was pushed', async () => {
stubServer({ [`GET ${THIS_WEEK}`]: () => jsonResponse(200, planBody('synced')) })
await renderPage()
const status = await screen.findByText('Synced to Google Calendar 2 min ago')
expect(declaredStyle(status).color).toBe('var(--color-accent-2-800)')
expect(status.querySelector('svg')).not.toBeNull()
})
it('says changes to a pushed plan are not pushed, and pushes them', async () => {
const fetchMock = stubServer({
[`GET ${THIS_WEEK}`]: () => jsonResponse(200, planBody('changed')),
[`POST ${PUSH}`]: () => jsonResponse(200, syncedNow()),
})
await renderPage()
expect(await screen.findByText('Changes not pushed')).toBeInTheDocument()
const status = screen.getByText('Changes not pushed to Google Calendar')
expect(declaredStyle(status).color).toBe('var(--color-neutral-700)')
fireEvent.click(screen.getByRole('button', { name: 'Looks good — push to Calendar' }))
expect(await screen.findByText('Synced to Google Calendar just now')).toBeInTheDocument()
expect(screen.queryByText('Changes not pushed')).not.toBeInTheDocument()
expect(posts(fetchMock)).toEqual([`${PUSH} undefined`])
})
it.each([
['google_reconnect_required', 'Google access was revoked or expired.', 'Reconnect Google Calendar'],
['no_calendar', 'No calendar is chosen for dinners yet.', 'Choose a calendar in Settings'],
['not_connected', 'Google Calendar is not connected.', 'Connect Google Calendar'],
['calendar_unavailable', 'The chosen calendar was deleted or MealQuest can no longer add dinners to it.', 'Choose another calendar'],
])('sends a %s push failure to the Google Calendar settings', async (code, reason, fix) => {
stubServer({
[`GET ${THIS_WEEK}`]: () => jsonResponse(200, planBody('draft')),
[`POST ${PUSH}`]: () => errorResponse(409, code),
})
await renderPage()
fireEvent.click(await screen.findByRole('button', { name: 'Looks good — push to Calendar' }))
const alert = await screen.findByRole('alert')
expect(alert).toHaveTextContent(`Couldn't push to Calendar. ${reason} ${fix}`)
expect(within(alert).getByRole('link', { name: fix })).toHaveAttribute('href', '/settings/calendar')
expect(within(alert).queryByRole('button', { name: 'Retry' })).not.toBeInTheDocument()
// The plan is as it was: not synced.
expect(screen.getByText('Draft')).toBeInTheDocument()
expect(screen.getByText('Not pushed to Google Calendar yet')).toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Looks good — push to Calendar' })).toBeEnabled()
})
it('marks the Google Calendar connection to be read again when Google refused the grant', async () => {
const connection = { status: 'connected', calendar_id: 'c1', calendar_name: 'Dinners', connected_at: null, last_sync_error: null }
const api = createApiClient(fakeLocation('/plan'), createNetworkStatus(window), createVerifiedSession(localStorage))
const queryClient = createQueryClient()
queryClient.setQueryData(['integrations', 'google'], connection)
const fetchMock = stubServer({
[`GET ${THIS_WEEK}`]: () => jsonResponse(200, planBody('draft')),
[`POST ${PUSH}`]: () => errorResponse(409, 'google_reconnect_required'),
})
await api.loadMe()
render(
<ApiProvider client={api}>
<QueryClientProvider client={queryClient}>
<MemoryRouter initialEntries={['/plan']}>
<PlanPage />
</MemoryRouter>
</QueryClientProvider>
</ApiProvider>,
)
fireEvent.click(await screen.findByRole('button', { name: 'Looks good — push to Calendar' }))
expect(await screen.findByRole('link', { name: 'Reconnect Google Calendar' })).toBeInTheDocument()
// The settings screen reads it again as it opens: it is now reconnect
// required.
expect(queryClient.getQueryState(['integrations', 'google'])?.isInvalidated).toBe(true)
expect(posts(fetchMock)).toEqual([`${PUSH} undefined`])
})
it('says why any other push failed, and pushes again on Retry', async () => {
let push = () => errorResponse(502, 'google_failed')
const fetchMock = stubServer({
[`GET ${THIS_WEEK}`]: () => jsonResponse(200, planBody('draft')),
[`POST ${PUSH}`]: () => push(),
})
await renderPage()
fireEvent.click(await screen.findByRole('button', { name: 'Looks good — push to Calendar' }))
const alert = await screen.findByRole('alert')
expect(alert).toHaveTextContent("Couldn't push to Calendar. google_failed message")
expect(within(alert).queryByRole('link')).not.toBeInTheDocument()
push = () => jsonResponse(200, syncedNow())
fireEvent.click(within(alert).getByRole('button', { name: 'Retry' }))
expect(await screen.findByText('Synced to Google Calendar just now')).toBeInTheDocument()
expect(screen.queryByRole('alert')).not.toBeInTheDocument()
expect(posts(fetchMock)).toEqual([`${PUSH} undefined`, `${PUSH} undefined`])
})
it('reads the plan again when it changed while being pushed', async () => {
let plan = planBody('draft')
const fetchMock = stubServer({
[`GET ${THIS_WEEK}`]: () => jsonResponse(200, plan),
[`POST ${PUSH}`]: () => errorResponse(409, 'plan_changed'),
})
await renderPage()
await screen.findByText('Beef tacos')
plan = planBody('draft', ['Lasagna', ...NAMES.slice(1)])
fireEvent.click(screen.getByRole('button', { name: 'Looks good — push to Calendar' }))
expect(await screen.findByRole('alert')).toHaveTextContent(
"Couldn't push to Calendar. The plan changed while it was being pushed; push it again.",
)
expect(await screen.findByText('Lasagna')).toBeInTheDocument()
expect(planReads(fetchMock)).toBe(2)
})
it('pushes nothing again until the changed plan is read and shown', async () => {
let read: () => Response | Promise<Response> = () => jsonResponse(200, planBody('draft'))
let push = () => errorResponse(409, 'plan_changed')
const fetchMock = stubServer({
[`GET ${THIS_WEEK}`]: () => read(),
[`POST ${PUSH}`]: () => push(),
})
await renderPage()
await screen.findByText('Beef tacos')
const reread = deferred()
read = () => reread.response
const pushButton = screen.getByRole('button', { name: 'Looks good — push to Calendar' })
fireEvent.click(pushButton)
await waitFor(() => expect(planReads(fetchMock)).toBe(2))
// While the changed plan is read, the push stays busy: neither Push
// nor Retry sends it again.
expect(screen.getByRole('button', { name: 'Pushing to Calendar…' })).toBeDisabled()
expect(screen.queryByRole('button', { name: 'Retry' })).not.toBeInTheDocument()
fireEvent.click(screen.getByRole('button', { name: 'Pushing to Calendar…' }))
expect(screen.getByText('Beef tacos')).toBeInTheDocument()
expect(posts(fetchMock)).toEqual([`${PUSH} undefined`])
reread.send(jsonResponse(200, planBody('draft', ['Lasagna', ...NAMES.slice(1)])))
const alert = await screen.findByRole('alert')
expect(alert).toHaveTextContent("Couldn't push to Calendar. The plan changed while it was being pushed; push it again.")
expect(screen.getByText('Lasagna')).toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Looks good — push to Calendar' })).toBeEnabled()
push = () => jsonResponse(200, syncedNow())
fireEvent.click(within(alert).getByRole('button', { name: 'Retry' }))
expect(await screen.findByText('Synced to Google Calendar just now')).toBeInTheDocument()
expect(posts(fetchMock)).toEqual([`${PUSH} undefined`, `${PUSH} undefined`])
})
it('pushes nothing again until the changed plan is shown, even after leaving the week and coming back', async () => {
let read: () => Response | Promise<Response> = () => jsonResponse(200, planBody('draft'))
let push = () => errorResponse(409, 'plan_changed')
const fetchMock = stubServer({
[`GET ${THIS_WEEK}`]: () => read(),
[`GET ${NEXT_WEEK}`]: () => errorResponse(404, 'not_found'),
[`POST ${PUSH}`]: () => push(),
})
await renderPage()
await screen.findByText('Beef tacos')
const reread = deferred()
read = () => reread.response
fireEvent.click(screen.getByRole('button', { name: 'Looks good — push to Calendar' }))
await waitFor(() => expect(planReads(fetchMock)).toBe(2))
// Leaving the week and coming back while the changed plan is read
// remounts the board: the push is still busy, and sends nothing again.
fireEvent.click(screen.getByRole('button', { name: 'Next week' }))
expect(await screen.findByRole('button', { name: 'Draft this week' })).toBeInTheDocument()
fireEvent.click(screen.getByRole('button', { name: 'Previous week' }))
await screen.findByText('Beef tacos')
expect(screen.getByRole('button', { name: 'Pushing to Calendar…' })).toBeDisabled()
expect(screen.queryByRole('button', { name: 'Retry' })).not.toBeInTheDocument()
fireEvent.click(screen.getByRole('button', { name: 'Pushing to Calendar…' }))
expect(posts(fetchMock)).toEqual([`${PUSH} undefined`])
await act(async () => reread.send(jsonResponse(200, planBody('draft', ['Lasagna', ...NAMES.slice(1)]))))
const alert = await screen.findByRole('alert')
expect(alert).toHaveTextContent("Couldn't push to Calendar. The plan changed while it was being pushed; push it again.")
expect(screen.getByText('Lasagna')).toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Looks good — push to Calendar' })).toBeEnabled()
push = () => jsonResponse(200, syncedNow())
fireEvent.click(within(alert).getByRole('button', { name: 'Retry' }))
expect(await screen.findByText('Synced to Google Calendar just now')).toBeInTheDocument()
expect(screen.queryByRole('alert')).not.toBeInTheDocument()
expect(posts(fetchMock)).toEqual([`${PUSH} undefined`, `${PUSH} undefined`])
})
it("pushes nothing again while the changed plan's read is answered from the cache", async () => {
let read = () => jsonResponse(200, planBody('draft'))
let push = () => errorResponse(409, 'plan_changed')
const fetchMock = stubServer({
[`GET ${THIS_WEEK}`]: () => read(),
[`POST ${PUSH}`]: () => push(),
})
await renderPage()
await screen.findByText('Beef tacos')
// The server can't be reached: the service worker answers the read of
// the changed plan with the plan it cached before.
read = () => {
const response = jsonResponse(200, planBody('draft'))
response.headers.set(cacheFallbackHeader, '1')
return response
}
fireEvent.click(screen.getByRole('button', { name: 'Looks good — push to Calendar' }))
const cachedCopy = "The plan changed while it was being pushed. The plan shown came from this device's cache, not the server; read it again before pushing."
const failed = await screen.findByRole('alert')
expect(planReads(fetchMock)).toBe(2)
expect(screen.getByText('Beef tacos')).toBeInTheDocument()
const pushButton = screen.getByRole('button', { name: 'Looks good — push to Calendar' })
expect(pushButton).toBeDisabled()
fireEvent.click(pushButton)
expect(failed).toHaveTextContent(cachedCopy)
// Retry reads the plan again rather than pushing: still the cache, so
// nothing is pushed.
fireEvent.click(within(screen.getByRole('alert')).getByRole('button', { name: 'Retry' }))
await waitFor(() => expect(planReads(fetchMock)).toBe(3))
expect(await screen.findByRole('alert')).toHaveTextContent(cachedCopy)
expect(screen.getByRole('button', { name: 'Looks good — push to Calendar' })).toBeDisabled()
expect(posts(fetchMock)).toEqual([`${PUSH} undefined`])
// The server is back: Retry shows the changed plan, and only then may it
// be pushed.
read = () => jsonResponse(200, planBody('draft', ['Lasagna', ...NAMES.slice(1)]))
fireEvent.click(within(screen.getByRole('alert')).getByRole('button', { name: 'Retry' }))
expect(await screen.findByText('Lasagna')).toBeInTheDocument()
const alert = screen.getByRole('alert')
expect(alert).toHaveTextContent("Couldn't push to Calendar. The plan changed while it was being pushed; push it again.")
expect(screen.getByRole('button', { name: 'Looks good — push to Calendar' })).toBeEnabled()
expect(posts(fetchMock)).toEqual([`${PUSH} undefined`])
push = () => jsonResponse(200, syncedNow())
fireEvent.click(within(alert).getByRole('button', { name: 'Retry' }))
expect(await screen.findByText('Synced to Google Calendar just now')).toBeInTheDocument()
expect(posts(fetchMock)).toEqual([`${PUSH} undefined`, `${PUSH} undefined`])
})
it('shows the changed plan read while the week was left, and pushes it', async () => {
let read: () => Response | Promise<Response> = () => jsonResponse(200, planBody('draft'))
let push = () => errorResponse(409, 'plan_changed')
const fetchMock = stubServer({
[`GET ${THIS_WEEK}`]: () => read(),
[`GET ${NEXT_WEEK}`]: () => errorResponse(404, 'not_found'),
[`POST ${PUSH}`]: () => push(),
})
await renderPage()
await screen.findByText('Beef tacos')
const reread = deferred()
read = () => reread.response
fireEvent.click(screen.getByRole('button', { name: 'Looks good — push to Calendar' }))
await waitFor(() => expect(planReads(fetchMock)).toBe(2))
fireEvent.click(screen.getByRole('button', { name: 'Next week' }))
expect(await screen.findByRole('button', { name: 'Draft this week' })).toBeInTheDocument()
await act(async () => reread.send(jsonResponse(200, planBody('draft', ['Lasagna', ...NAMES.slice(1)]))))
read = () => jsonResponse(200, planBody('draft', ['Lasagna', ...NAMES.slice(1)]))
fireEvent.click(screen.getByRole('button', { name: 'Previous week' }))
// The board comes back on the changed plan: Push sends that one.
expect(await screen.findByText('Lasagna')).toBeInTheDocument()
expect(screen.queryByText('Beef tacos')).not.toBeInTheDocument()
expect(screen.getByRole('alert')).toHaveTextContent('The plan changed while it was being pushed; push it again.')
push = () => jsonResponse(200, syncedNow())
fireEvent.click(screen.getByRole('button', { name: 'Looks good — push to Calendar' }))
expect(await screen.findByText('Synced to Google Calendar just now')).toBeInTheDocument()
expect(posts(fetchMock)).toEqual([`${PUSH} undefined`, `${PUSH} undefined`])
})
it('rebuilds a draft at once, showing skeleton tiles until the new plan is read', async () => {
@@ -715,20 +1026,19 @@ describe.each([
expect(screen.getByRole('button', { name: 'Next week' })).toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'This week' }) !== null).toBe(layout === 'desktop')
// Actions: the shopping list and Push to Calendar unavailable, saying
// why; Rebuild week outlined and working.
// Actions: the shopping list unavailable, saying why; Rebuild week
// outlined and Push to Calendar primary, both working.
const shopping = screen.getByRole('button', { name: 'Shopping list' })
expect(shopping).toHaveAttribute('aria-disabled', 'true')
expect(shopping).toHaveAccessibleDescription('The shopping list arrives once the Supply run is built.')
const push = screen.getByRole('button', { name: 'Push to Calendar' })
expect(push).toHaveAttribute('aria-disabled', 'true')
expect(push).toHaveAccessibleDescription('Push to Calendar arrives once Google Calendar can be connected.')
expect(push).toBeEnabled()
expect(push).not.toHaveAttribute('aria-disabled')
expect(declaredStyle(push).background).toBe('var(--color-accent)')
const rebuild = screen.getByRole('button', { name: 'Rebuild week' })
expect(rebuild).toBeEnabled()
expect(declaredStyle(rebuild).borderColor).toBe('var(--color-neutral-300)')
fireEvent.click(shopping)
fireEvent.click(push)
expect(posts(fetchMock)).toEqual([])
// Mobile's own pieces are not shown.
expect(screen.queryByRole('button', { name: 'Looks good — push to Calendar' })).not.toBeInTheDocument()
@@ -795,6 +1105,43 @@ describe.each([
expect(await screen.findByText('Changes not pushed to Google Calendar')).toBeInTheDocument()
})
it('pushes the plan from the header, showing progress, then the plan as synced', async () => {
const answer = deferred()
stubServer({
[`GET ${THIS_WEEK}`]: () => jsonResponse(200, planBody('changed')),
[`POST ${PUSH}`]: () => answer.response,
...lists,
})
await renderPage()
await screen.findByText('Beef tacos')
fireEvent.click(screen.getByRole('button', { name: 'Push to Calendar' }))
const pushing = await screen.findByRole('button', { name: 'Pushing…' })
expect(pushing).toBeDisabled()
expect(pushing).toHaveAttribute('aria-busy', 'true')
expect(screen.getByRole('button', { name: 'Rebuild week' })).toBeDisabled()
answer.send(jsonResponse(200, syncedNow()))
const status = await screen.findByText('Synced to Google Calendar just now')
expect(declaredStyle(status).color).toBe('var(--color-accent-2-800)')
expect(screen.getByRole('button', { name: 'Push to Calendar' })).toBeEnabled()
})
it('links a google_reconnect_required push failure to the Google Calendar settings', async () => {
stubServer({
[`GET ${THIS_WEEK}`]: () => jsonResponse(200, planBody('synced')),
[`POST ${PUSH}`]: () => errorResponse(409, 'google_reconnect_required'),
...lists,
})
await renderPage()
await screen.findByText('Beef tacos')
fireEvent.click(screen.getByRole('button', { name: 'Push to Calendar' }))
const alert = await screen.findByRole('alert')
expect(within(alert).getByRole('link', { name: 'Reconnect Google Calendar' })).toHaveAttribute('href', '/settings/calendar')
expect(screen.getByText('Synced to Google Calendar 2 min ago')).toBeInTheDocument()
})
if (layout === 'desktop') {
it('shows the Quest log and Regulars in the 290 px right panel', async () => {
stubServer({ [`GET ${THIS_WEEK}`]: () => jsonResponse(200, planBody('draft')), ...lists })
+103 -29
View File
@@ -1,7 +1,8 @@
import { useQueryClient } from '@tanstack/react-query'
import { CalendarDays, Check, ChevronLeft, ChevronRight, Plus, RefreshCw, ShoppingCart } from 'lucide-react'
import { useEffect, useId, useMemo, useState, type ReactNode } from 'react'
import { useJob } from '../api/index.ts'
import { Link } from 'react-router'
import { ApiError, useJob } from '../api/index.ts'
import { QUEST_LOG_KEY } from '../discover/api.ts'
import { Confirm } from '../settings/LeaveGuard.tsx'
import { methodLabels } from '../settings/RegularsSettingsPage.tsx'
@@ -20,6 +21,7 @@ import {
parseDraftResult,
planKey,
usePlan,
usePushToCalendar,
useStartDraft,
useSwapDay,
type DraftResult,
@@ -62,9 +64,20 @@ const draftFailures: Record<string, string> = {
internal_error: 'Something went wrong on the server.',
}
// PUSH_HINT is why Push to Calendar is unavailable.
// TODO(Feature 16): connect Push to Calendar once Google Calendar is.
const PUSH_HINT = 'Push to Calendar arrives once Google Calendar can be connected.'
// CALENDAR_SETTINGS is the Google Calendar settings screen.
const CALENDAR_SETTINGS = '/settings/calendar'
// settingsFailures says why a push failed, by its API error code, for the
// failures only the Google Calendar settings can fix, and what to do there.
const settingsFailures: Record<string, { reason: string; fix: string }> = {
google_reconnect_required: { reason: 'Google access was revoked or expired.', fix: 'Reconnect Google Calendar' },
not_connected: { reason: 'Google Calendar is not connected.', fix: 'Connect Google Calendar' },
no_calendar: { reason: 'No calendar is chosen for dinners yet.', fix: 'Choose a calendar in Settings' },
calendar_unavailable: {
reason: 'The chosen calendar was deleted or MealQuest can no longer add dinners to it.',
fix: 'Choose another calendar',
},
}
// SHOPPING_HINT is why the shopping list is unavailable.
// TODO(Feature 17): open the Supply run, with its count, once it is built.
@@ -204,9 +217,13 @@ function SkeletonTiles({ label, layout, children }: { label: string; layout: Bre
// the plan is read again. Rebuilding a plan pushed to Calendar asks first,
// and sends confirm. A failed draft is shown with Retry; no plan is made up.
//
// From tablet up it is the plan manager (mocks 2c, 2d): Rebuild week and the
// unavailable Shopping list and Push to Calendar are actions in the header,
// From tablet up it is the plan manager (mocks 2c, 2d): Rebuild week, Push to
// Calendar and the unavailable Shopping list are actions in the header,
// over the plan's sync status and the 7-column grid.
//
// Push to Calendar, on either layout, sends the plan shown and shows it as
// synced once the server answers; a failure says why, linking to the Google
// Calendar settings when only they can fix it.
function WeekBoard({
weekStart,
timezone,
@@ -225,6 +242,8 @@ function WeekBoard({
const job = useJob<unknown>(DRAFT_JOB_KIND, jobId)
const [confirming, setConfirming] = useState(false)
const swap = useSwapDay(weekStart)
const push = usePushToCalendar(weekStart)
const pushing = push.pending
// The date of the day being swapped, while the swap sheet is open.
const [swappingDate, setSwappingDate] = useState<string | null>(null)
const label = weekLabel(weekStart)
@@ -282,13 +301,28 @@ function WeekBoard({
const drafting = startDraft.isPending || (jobId !== null && job.status !== 'failed' && resultError === null)
// A push sends the plan shown: it waits for a draft or a swap of the week
// to settle, and neither starts while it runs, even across leaving the
// week and coming back. Nor does it send a plan from this device's cache,
// which may not be the server's: after a push refused because the plan
// changed, the read of the changed plan may be answered from the cache.
const cached = plan.isSuccess && plan.data !== null && plan.data.cached
const canPush = plan.isSuccess && plan.data !== null && !cached && !drafting && !swap.pending && !pushing
function pushToCalendar() {
if (!canPush) return
swap.dismiss()
push.reset()
push.mutate()
}
const { mutate } = startDraft
function start(confirm: boolean) {
setConfirming(false)
// A draft asked for again leaves the last one's failure, and a failed
// swap's, behind.
// A draft asked for again leaves the last one's failure, a failed
// swap's and a failed push's behind.
setJobId(null)
swap.dismiss()
push.reset()
mutate(
{ weekStart, confirm },
{
@@ -302,12 +336,14 @@ function WeekBoard({
// It waits for a swap of the week still pending, which may yet fail: the
// Rebuild week tile is disabled meanwhile.
function rebuild() {
if (swap.pending) return
if (swap.pending || pushing) return
if (plan.data && pushedToCalendar(plan.data.status)) setConfirming(true)
else start(false)
}
const failure = swap.failed !== null ? (
const failure = push.error !== null ? (
<PushFailure error={push.error} cached={cached} onRetry={cached ? () => void plan.refetch() : pushToCalendar} />
) : swap.failed !== null ? (
<ErrorBanner onRetry={() => swapIn(swap.failed!.swap)}>
Couldn't swap {weekdayName(swap.failed.swap.date)}'s dinner. {swap.failed.error.message}
</ErrorBanner>
@@ -328,6 +364,7 @@ function WeekBoard({
// swapIn sends the swap chosen in the sheet and closes it.
function swapIn(chosen: Swap) {
setSwappingDate(null)
push.reset()
swap.mutate(chosen)
}
// dropIn swaps in a dinner dragged onto a day. A drag is not picked up,
@@ -338,9 +375,10 @@ function WeekBoard({
}
// openSwap opens the swap sheet on a day. One swap of the week is sent at
// a time, even across leaving the week and coming back: the plan the
// server answers it with must not overwrite another still pending.
// server answers it with must not overwrite another still pending. Nor is
// one sent while the week is being pushed to Calendar.
function openSwap(date: string) {
if (swap.pending) return
if (swap.pending || pushing) return
swap.dismiss()
setSwappingDate(date)
}
@@ -379,7 +417,7 @@ function WeekBoard({
body =
layout !== 'mobile' ? (
<>
<DropBoard days={days} pending={swap.pending} drop={dropIn} />
<DropBoard days={days} pending={swap.pending || pushing} drop={dropIn} />
<ul className={`${styles.week} ${styles[layout]}`} aria-label="Dinners this week">
{days.map((day) => (
<DayColumn
@@ -414,15 +452,16 @@ function WeekBoard({
/>
))}
<li className={styles.rebuildCell}>
<button type="button" className={styles.rebuild} onClick={rebuild} disabled={swap.pending}>
<button type="button" className={styles.rebuild} onClick={rebuild} disabled={swap.pending || pushing}>
<Icon icon={Plus} size="inline" />
Rebuild week
</button>
</li>
</ul>
<Unavailable hint={PUSH_HINT} className={styles.pushButton}>
Looks good — push to Calendar
</Unavailable>
<Button className={styles.pushButton} onClick={pushToCalendar} disabled={!canPush} aria-busy={pushing}>
{pushing ? 'Pushing to Calendar…' : 'Looks good — push to Calendar'}
</Button>
<SyncStatus plan={plan.data} className={styles.mobileStatus} />
{sheet}
</>
)
@@ -458,14 +497,19 @@ function WeekBoard({
<Icon icon={ShoppingCart} size="inline" />
Shopping list
</Unavailable>
<Button variant="outline" className={styles.action} onClick={rebuild} disabled={swap.pending || drafting || !plan.isSuccess}>
<Button
variant="outline"
className={styles.action}
onClick={rebuild}
disabled={swap.pending || pushing || drafting || !plan.isSuccess}
>
<Icon icon={RefreshCw} size="inline" />
Rebuild week
</Button>
<Unavailable hint={PUSH_HINT} below className={styles.action}>
<Button className={styles.action} onClick={pushToCalendar} disabled={!canPush} aria-busy={pushing}>
<Icon icon={CalendarDays} size="inline" />
Push to Calendar
</Unavailable>
{pushing ? 'Pushing…' : 'Push to Calendar'}
</Button>
</div>
</div>
</header>
@@ -507,10 +551,11 @@ function WeekBoard({
)
}
// SyncStatus is the plan manager's status line: whether the plan is on
// Google Calendar and, once synced, how long ago it was pushed, kept current
// minute by minute.
function SyncStatus({ plan }: { plan: Plan }) {
// SyncStatus is the plan's status line, in the plan manager's header and
// under the Draft board's push button: whether the plan is on Google
// Calendar and, once synced, how long ago it was pushed, kept current minute
// by minute.
function SyncStatus({ plan, className }: { plan: Plan; className?: string }) {
const { status, calendar_synced_at: syncedAt } = plan
const [now, setNow] = useState(() => new Date())
useEffect(() => {
@@ -518,7 +563,7 @@ function SyncStatus({ plan }: { plan: Plan }) {
return () => clearInterval(timer)
}, [])
return (
<p className={[styles.status, status === 'synced' && styles.synced].filter(Boolean).join(' ')}>
<p className={[styles.status, status === 'synced' && styles.synced, className].filter(Boolean).join(' ')}>
{status === 'synced' && <Icon icon={Check} size="inline" />}
{syncStatuses[status]}
{status === 'synced' && syncedAt !== null && ` ${ago(syncedAt, now)}`}
@@ -526,9 +571,38 @@ function SyncStatus({ plan }: { plan: Plan }) {
)
}
// Unavailable is an action with nothing behind it yet (Push to Calendar, the
// shopping list): it stays focusable, so a tap or focus shows the tooltip
// saying why, above it or, at the top of the page, below.
// PushFailure says why Push to Calendar failed. A failure only the Google
// Calendar settings can fix links there; any other offers to push again,
// or, while the plan shown is this device's cached copy, to read it again
// from the server first.
function PushFailure({ error, cached, onRetry }: { error: Error; cached: boolean; onRetry: () => void }) {
const code = error instanceof ApiError ? error.code : null
const settings = code !== null && Object.hasOwn(settingsFailures, code) ? settingsFailures[code] : undefined
if (settings !== undefined) {
return (
<ErrorBanner>
Couldn't push to Calendar. {settings.reason}{' '}
<Link to={CALENDAR_SETTINGS} className={styles.settingsLink}>
{settings.fix}
</Link>
</ErrorBanner>
)
}
return (
<ErrorBanner onRetry={onRetry}>
Couldn't push to Calendar.{' '}
{cached
? `${code === 'plan_changed' ? 'The plan changed while it was being pushed.' : error.message} The plan shown came from this device's cache, not the server; read it again before pushing.`
: code === 'plan_changed'
? 'The plan changed while it was being pushed; push it again.'
: error.message}
</ErrorBanner>
)
}
// Unavailable is an action with nothing behind it yet (the shopping list):
// it stays focusable, so a tap or focus shows the tooltip saying why, above
// it or, at the top of the page, below.
function Unavailable({
hint,
variant = 'primary',
+198 -2
View File
@@ -1,11 +1,12 @@
import { QueryClientProvider, type QueryClient } from '@tanstack/react-query'
import { act, renderHook, waitFor } from '@testing-library/react'
import { act, render, renderHook, waitFor } from '@testing-library/react'
import type { ReactNode } from 'react'
import { MemoryRouter, Route, Routes, useNavigate, type NavigateFunction } from 'react-router'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { ApiProvider, createApiClient, createQueryClient, createVerifiedSession } from '../api/index.ts'
import { createNetworkStatus } from '../pwa/networkStatus.ts'
import { errorResponse, fakeLocation, jsonResponse, ME } from '../test/fetchStub.ts'
import { planKey, usePlan, useSwapDay, type Plan } from './api.ts'
import { planKey, usePlan, usePushToCalendar, useSwapDay, type Plan, type PushToCalendar, type SwapDay } from './api.ts'
const WEEK = '2026-10-05'
const PLAN = `/api/v1/plans/${WEEK}`
@@ -203,3 +204,198 @@ describe('useSwapDay', () => {
await act(async () => friday.send(jsonResponse(200, planBody())))
})
})
describe('week mutations', () => {
const NEXT = '2026-10-12'
const LATER = '2026-10-19'
// weekMutations lists the swaps and pushes the mutation cache holds for
// the week starting on weekStart, with their status.
function weekMutations(queryClient: QueryClient, weekStart: string) {
return queryClient
.getMutationCache()
.findAll({ mutationKey: ['plans', weekStart] })
.map((mutation) => `${String(mutation.options.mutationKey![2])} ${mutation.state.status}`)
}
it('keeps settled swaps and pushes while their week is shown, and leaves them behind once it is not, unless one is pending', async () => {
const nextPush = deferred()
stubServer({
[`GET ${PLAN}`]: () => jsonResponse(200, planBody()),
[`PUT ${FRIDAY}`]: () => jsonResponse(200, planBody({ 4: { id: 'q1', name: 'Lemon orzo', is_new: true } })),
[`POST ${PLAN}/push-calendar`]: () => errorResponse(500, 'internal'),
[`GET /api/v1/plans/${NEXT}`]: () => errorResponse(404, 'not_found'),
[`POST /api/v1/plans/${NEXT}/push-calendar`]: () => nextPush.reply,
[`GET /api/v1/plans/${LATER}`]: () => errorResponse(404, 'not_found'),
})
const api = createApiClient(fakeLocation('/plan'), createNetworkStatus(window), createVerifiedSession(localStorage))
await api.loadMe()
const queryClient = createQueryClient()
const wrapper = ({ children }: { children: ReactNode }) => (
<ApiProvider client={api}>
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
</ApiProvider>
)
const hook = renderHook(
({ week }) => ({ plan: usePlan(week), swap: useSwapDay(week), push: usePushToCalendar(week) }),
{ wrapper, initialProps: { week: WEEK } },
)
await waitFor(() => expect(hook.result.current.plan.isSuccess).toBe(true))
// A swap and a push of the week settle: both stay while it is shown,
// the push's failure speaking for the week.
act(() => hook.result.current.swap.mutate(ORZO))
await waitFor(() => expect(hook.result.current.swap.pending).toBe(false))
act(() => hook.result.current.push.mutate())
await waitFor(() => expect(hook.result.current.push.error).not.toBeNull())
expect(weekMutations(queryClient, WEEK)).toEqual(['swap success', 'push error'])
// Another week shown leaves them behind; a push sent there stays
// pending across showing a third week.
hook.rerender({ week: NEXT })
await waitFor(() => expect(hook.result.current.plan.isSuccess).toBe(true))
expect(weekMutations(queryClient, WEEK)).toEqual([])
act(() => hook.result.current.push.mutate())
hook.rerender({ week: LATER })
await waitFor(() => expect(hook.result.current.plan.isSuccess).toBe(true))
expect(weekMutations(queryClient, NEXT)).toEqual(['push pending'])
hook.rerender({ week: NEXT })
expect(hook.result.current.push.pending).toBe(true)
// Once it settles, it stays while its week is shown and is left behind
// once another is.
await act(async () => nextPush.send(errorResponse(500, 'internal')))
await waitFor(() => expect(hook.result.current.push.error).not.toBeNull())
expect(weekMutations(queryClient, NEXT)).toEqual(['push error'])
hook.rerender({ week: LATER })
expect(weekMutations(queryClient, NEXT)).toEqual([])
})
it('leaves behind what settles in a week no longer shown, unless that week still has one pending or it is the failure that speaks for it', async () => {
const friday = deferred()
const monday = deferred()
const nextPush = deferred()
const laterPush = deferred()
stubServer({
[`GET ${PLAN}`]: () => jsonResponse(200, planBody()),
[`PUT ${FRIDAY}`]: () => friday.reply,
[`PUT ${MONDAY}`]: () => monday.reply,
[`GET /api/v1/plans/${NEXT}`]: () => errorResponse(404, 'not_found'),
[`POST /api/v1/plans/${NEXT}/push-calendar`]: () => nextPush.reply,
[`GET /api/v1/plans/${LATER}`]: () => errorResponse(404, 'not_found'),
[`POST /api/v1/plans/${LATER}/push-calendar`]: () => laterPush.reply,
})
const api = createApiClient(fakeLocation('/plan'), createNetworkStatus(window), createVerifiedSession(localStorage))
await api.loadMe()
const queryClient = createQueryClient()
const wrapper = ({ children }: { children: ReactNode }) => (
<ApiProvider client={api}>
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
</ApiProvider>
)
const hook = renderHook(
({ week }) => ({ plan: usePlan(week), swap: useSwapDay(week), push: usePushToCalendar(week) }),
{ wrapper, initialProps: { week: WEEK } },
)
await waitFor(() => expect(hook.result.current.plan.isSuccess).toBe(true))
// Two swaps of the week and a push of the next are left pending, and a
// third week is shown.
act(() => hook.result.current.swap.mutate(ORZO))
act(() => hook.result.current.swap.mutate(FISH))
await waitFor(() => expect(weekMutations(queryClient, WEEK)).toEqual(['swap pending', 'swap pending']))
hook.rerender({ week: NEXT })
await waitFor(() => expect(hook.result.current.plan.isSuccess).toBe(true))
act(() => hook.result.current.push.mutate())
hook.rerender({ week: LATER })
await waitFor(() => expect(hook.result.current.plan.isSuccess).toBe(true))
expect(weekMutations(queryClient, NEXT)).toEqual(['push pending'])
// The later swap settles first: the earlier, still pending, must see it,
// so both stay.
await act(async () => monday.send(jsonResponse(200, planBody({ 0: { id: 'r1', name: 'Fish tacos' } }))))
await waitFor(() => expect(weekMutations(queryClient, WEEK)).toEqual(['swap pending', 'swap success']))
// The push succeeds while the third week is shown: it is left behind,
// and the week's pending swap is not.
await act(async () => nextPush.send(jsonResponse(200, { ...planBody(), week_start: NEXT })))
await waitFor(() => expect(weekMutations(queryClient, NEXT)).toEqual([]))
expect(weekMutations(queryClient, WEEK)).toEqual(['swap pending', 'swap success'])
// Once the earlier swap fails, the week has none pending: both are left
// behind, the failure not being the week's latest.
await act(async () => friday.send(errorResponse(409, 'dinner_not_plannable')))
await waitFor(() => expect(weekMutations(queryClient, WEEK)).toEqual([]))
// A push of the third week fails once another is shown: it stays, to be
// shown on coming back, until yet another week is.
act(() => hook.result.current.push.mutate())
hook.rerender({ week: NEXT })
await waitFor(() => expect(hook.result.current.plan.isSuccess).toBe(true))
await act(async () => laterPush.send(errorResponse(500, 'internal')))
await waitFor(() => expect(weekMutations(queryClient, LATER)).toEqual(['push error']))
hook.rerender({ week: WEEK })
expect(weekMutations(queryClient, LATER)).toEqual([])
})
it('leaves behind what settles once Plan is left for another route, and keeps what is pending', async () => {
const friday = deferred()
const monday = deferred()
const push = deferred()
stubServer({
[`GET ${PLAN}`]: () => jsonResponse(200, planBody()),
[`PUT ${FRIDAY}`]: () => friday.reply,
[`PUT ${MONDAY}`]: () => monday.reply,
[`POST ${PLAN}/push-calendar`]: () => push.reply,
})
const api = createApiClient(fakeLocation('/plan'), createNetworkStatus(window), createVerifiedSession(localStorage))
await api.loadMe()
const queryClient = createQueryClient()
let week!: { plan: ReturnType<typeof usePlan>; swap: SwapDay; push: PushToCalendar }
let navigate!: NavigateFunction
function Week() {
week = { plan: usePlan(WEEK), swap: useSwapDay(WEEK), push: usePushToCalendar(WEEK) }
return null
}
function Navigator() {
navigate = useNavigate()
return null
}
render(
<ApiProvider client={api}>
<QueryClientProvider client={queryClient}>
<MemoryRouter initialEntries={['/plan']}>
<Navigator />
<Routes>
<Route path="/plan" element={<Week />} />
<Route path="/settings" element={null} />
</Routes>
</MemoryRouter>
</QueryClientProvider>
</ApiProvider>,
)
await waitFor(() => expect(week.plan.isSuccess).toBe(true))
// Two swaps and a push of the week are left pending, and Settings is
// shown.
act(() => week.swap.mutate(ORZO))
act(() => week.swap.mutate(FISH))
act(() => week.push.mutate())
await waitFor(() => expect(weekMutations(queryClient, WEEK)).toEqual(['swap pending', 'swap pending', 'push pending']))
act(() => void navigate('/settings'))
// The swaps settle: once neither is pending they are left behind, and
// the push still pending is not.
await act(async () => monday.send(jsonResponse(200, planBody({ 0: { id: 'r1', name: 'Fish tacos' } }))))
await waitFor(() => expect(weekMutations(queryClient, WEEK)).toEqual(['swap pending', 'swap success', 'push pending']))
await act(async () => friday.send(jsonResponse(200, planBody({ 0: { id: 'r1', name: 'Fish tacos' }, 4: { id: 'q1', name: 'Lemon orzo', is_new: true } }))))
await waitFor(() => expect(weekMutations(queryClient, WEEK)).toEqual(['push pending']))
// The push succeeds: the plan as synced is recorded, and the push is
// left behind.
const synced = { ...planBody(), status: 'synced', calendar_synced_at: '2026-10-08T06:00:00Z' }
await act(async () => push.send(jsonResponse(200, synced)))
await waitFor(() => expect(weekMutations(queryClient, WEEK)).toEqual([]))
expect(queryClient.getQueryData<Plan>(planKey(WEEK))).toMatchObject({ status: 'synced', calendar_synced_at: new Date('2026-10-08T06:00:00Z') })
})
})
+166 -3
View File
@@ -1,8 +1,10 @@
import { useMutation, useMutationState, useQuery, useQueryClient } from '@tanstack/react-query'
import { useEffect } from 'react'
import { useMutation, useMutationState, useQuery, useQueryClient, type Mutation, type QueryClient } from '@tanstack/react-query'
import { ApiError, useApi, type ApiRead } from '../api/index.ts'
import { isRecord } from '../api/errors.ts'
import { METHODS, oneOf, photoId, type Method } from '../dinners/api.ts'
import { QUEST_LOG_KEY } from '../discover/api.ts'
import { noteGoogleFailure } from '../settings/calendarApi.ts'
export const PLANS_PATH = '/api/v1/plans'
@@ -176,6 +178,82 @@ function sameDay(a: PlanDay, b: PlanDay): boolean {
)
}
// weekMutation is the kind and week of a swap or push of a week the mutation
// cache keeps for it, or null for any other mutation.
function weekMutation(mutation: Mutation): { kind: 'swap' | 'push'; week: string } | null {
const key = mutation.options.mutationKey
if (key === undefined || key.length !== 3 || key[0] !== 'plans' || (key[2] !== 'swap' && key[2] !== 'push')) return null
return { kind: key[2], week: String(key[1]) }
}
// WeeksShown is what keepWeekMutations is told of the weeks shown: show
// marks a week shown until the function it returns is called.
type WeeksShown = { show: (weekStart: string) => () => void }
const weeksShown = new WeakMap<QueryClient, WeeksShown>()
// keepWeekMutations bounds the swaps and pushes the mutation cache of
// queryClient keeps, for as long as the query client lives, whatever is
// shown: it is installed on the client's own mutation cache once, the first
// time a week is shown, and is never removed, so a swap or push that settles
// after its Draft board, or the whole Plan, is gone is still collected.
//
// When a week is shown, the settled ones of every other week are removed,
// unless that week still has one pending: a pending one, and those an
// earlier pending one must see, stay across leaving its week and coming
// back. When one settles, the same is done, except that a week's latest,
// when it failed, stays until a week is next shown, so that coming straight
// back to it shows the failure. The cache holds at most the weeks shown's,
// those of weeks left pending, and one failure of each week whose last
// pending one settled since a week was last shown.
function keepWeekMutations(queryClient: QueryClient): WeeksShown {
const kept = weeksShown.get(queryClient)
if (kept !== undefined) return kept
const mutations = queryClient.getMutationCache()
// How many times each week is shown at once.
const shown = new Map<string, number>()
function sweep(settled: boolean) {
// The mutations of each kind of each week not shown, in the order sent.
const left = new Map<string, Mutation[]>()
for (const mutation of mutations.getAll()) {
const of = weekMutation(mutation)
if (of === null || shown.has(of.week)) continue
const id = `${of.kind} ${of.week}`
left.set(id, [...(left.get(id) ?? []), mutation])
}
for (const week of left.values()) {
if (week.some((mutation) => mutation.state.status === 'pending')) continue
const latest = week.at(-1)
for (const mutation of week) {
if (settled && mutation === latest && mutation.state.status === 'error') continue
mutations.remove(mutation)
}
}
}
mutations.subscribe((event) => {
if (event.type === 'updated' && weekMutation(event.mutation) !== null && event.mutation.state.status !== 'pending') sweep(true)
})
const show = (weekStart: string) => {
shown.set(weekStart, (shown.get(weekStart) ?? 0) + 1)
sweep(false)
return () => {
const times = shown.get(weekStart)! - 1
if (times === 0) shown.delete(weekStart)
else shown.set(weekStart, times)
}
}
const keeping = { show }
weeksShown.set(queryClient, keeping)
return keeping
}
// useWeekShown marks the week starting on weekStart shown while the
// component is mounted (keepWeekMutations).
function useWeekShown(weekStart: string) {
const queryClient = useQueryClient()
useEffect(() => keepWeekMutations(queryClient).show(weekStart), [queryClient, weekStart])
}
// swapKey keys the swaps of the week starting on weekStart in the mutation
// cache, where they outlive the Draft board that sent them.
function swapKey(weekStart: string) {
@@ -205,10 +283,12 @@ export type SwapDay = {
// earlier one is answered with is not written over a later one, and its
// failure is not the week's. dismiss leaves settled swaps behind; it is
// refused while one is pending, so a later swap is always in the cache for
// an earlier, pending one to see.
// an earlier, pending one to see. Settled swaps of a week no longer shown
// are left behind too (keepWeekMutations).
export function useSwapDay(weekStart: string): SwapDay {
const { apiFetch } = useApi()
const queryClient = useQueryClient()
useWeekShown(weekStart)
const key = planKey(weekStart)
const mutationKey = swapKey(weekStart)
const mutations = queryClient.getMutationCache()
@@ -224,7 +304,8 @@ export function useSwapDay(weekStart: string): SwapDay {
const isLatest = () => mutations.findAll({ mutationKey }).every((other) => other.mutationId <= mutation.mutationId)
const mutation = mutations.build<Plan, Error, Swap, { previous: PlanDay; swapped: PlanDay }>(queryClient, {
mutationKey,
// Kept until dismissed: a later swap must stay in the cache while an
// Kept until dismissed or settled in a week not shown
// (keepWeekMutations): a later swap must stay in the cache while an
// earlier one is pending.
gcTime: Infinity,
mutationFn: async ({ date, dinner }) => {
@@ -274,3 +355,85 @@ export function useSwapDay(weekStart: string): SwapDay {
dismiss,
}
}
// pushKey keys the pushes of the week starting on weekStart in the mutation
// cache, where they outlive the Draft board that sent them.
function pushKey(weekStart: string) {
return ['plans', weekStart, 'push'] as const
}
// PushToCalendar is the push of one week, as the mutation cache holds it:
// whether it is pending, and why the latest failed, if it failed.
export type PushToCalendar = {
pending: boolean
error: Error | null
mutate: () => void
reset: () => void
}
// usePushToCalendar pushes the plan of the week starting on weekStart to the
// chosen Google calendar (POST /api/v1/plans/{weekStart}/push-calendar). The
// server answers with the plan as synced, which replaces the one shown, as a
// swap's answer does. A push refused because the plan changed meanwhile
// reads the plan again, whether or not the week is shown, and stays pending
// until that read lands: nothing is pushed again before the changed plan is
// the one shown. One Google refused the grant for reads the Google Calendar
// connection again, which is now reconnect required.
//
// The week's pushes live in the mutation cache, not in the component, as its
// swaps do, so leaving the week and coming back keeps one pending. reset
// leaves settled pushes behind; it is refused while one is pending. Settled
// pushes of a week no longer shown are left behind too
// (keepWeekMutations).
export function usePushToCalendar(weekStart: string): PushToCalendar {
const { apiFetch } = useApi()
const queryClient = useQueryClient()
useWeekShown(weekStart)
const key = planKey(weekStart)
const mutationKey = pushKey(weekStart)
const mutations = queryClient.getMutationCache()
// The week's pushes, in the order sent.
const pushes = useMutationState({
filters: { mutationKey },
select: (mutation) => ({ status: mutation.state.status, error: mutation.state.error }),
})
const latest = pushes.at(-1)
function mutate() {
const mutation = mutations.build<Plan, Error, void, unknown>(queryClient, {
mutationKey,
// Kept until reset or settled in a week not shown (keepWeekMutations):
// a push pending in a week left must still be found when it is shown
// again.
gcTime: Infinity,
mutationFn: async () => {
const path = `${planPath(weekStart)}/push-calendar`
return parsePlan(`POST ${path}`, weekStart, await apiFetch<unknown>(path, { method: 'POST' }), false)
},
onSuccess: (plan) => queryClient.setQueryData<Plan>(key, plan),
onError: async (error) => {
noteGoogleFailure(queryClient, error)
if (error instanceof ApiError && error.code === 'plan_changed') {
await queryClient.invalidateQueries({ queryKey: key, refetchType: 'all' })
}
},
})
// A failure is the mutation's state, which error reports.
mutation.execute().catch(() => undefined)
}
function reset() {
const week = mutations.findAll({ mutationKey })
if (week.some((mutation) => mutation.state.status === 'pending')) {
throw new Error(`The week of ${weekStart} has a push pending, which cannot be reset.`)
}
for (const mutation of week) mutations.remove(mutation)
}
return {
pending: pushes.some((push) => push.status === 'pending'),
error: latest?.status === 'error' ? latest.error! : null,
mutate,
reset,
}
}