Repository navigation
Email token cache workflow #61
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -8,6 +8,7 @@ | |
| **/*.user | ||
| **/*.pfx | ||
| **/*.pem | ||
| **/.graph-token-cache | ||
| .aspnet | ||
| .vs | ||
| .idea | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -25,6 +25,7 @@ node_modules/ | |
| .env | ||
| .env.* | ||
| !.env.example | ||
| server/.graph-token-cache/ | ||
|
|
||
| # Build results | ||
| [Dd]ebug/ | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,297 @@ | ||
| import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; | ||
| import { useAppForm } from '@/shared/forms/formContext.tsx'; | ||
| import { z } from 'zod'; | ||
| import { HttpError } from '@/lib/api.ts'; | ||
| import { | ||
| checkDevelopmentGraph, | ||
| connectDevelopmentGraph, | ||
| developmentGraphStatusOptions, | ||
| createDevelopmentTestMeeting, | ||
| } from '@/queries/developmentGraph.ts'; | ||
|
|
||
| export function DevelopmentCalendar() { | ||
| const queryClient = useQueryClient(); | ||
| const status = useQuery(developmentGraphStatusOptions()); | ||
| const connect = useMutation({ | ||
| mutationFn: connectDevelopmentGraph, | ||
| onSuccess: ({ authorizationUrl }) => | ||
| window.location.assign(authorizationUrl), | ||
| }); | ||
| const check = useMutation({ | ||
| mutationFn: checkDevelopmentGraph, | ||
| onSuccess: () => | ||
| queryClient.invalidateQueries({ | ||
| queryKey: developmentGraphStatusOptions().queryKey, | ||
| }), | ||
| }); | ||
| const meeting = useMutation({ | ||
| mutationFn: createDevelopmentTestMeeting, | ||
| retry: false, | ||
| }); | ||
| const form = useAppForm({ | ||
| defaultValues: { recipientEmail: '' }, | ||
| onSubmit: async ({ value }) => { | ||
| if ( | ||
| !status.data?.connected || | ||
| connect.isPending || | ||
| check.isPending || | ||
| meeting.isPending | ||
| ) { | ||
| return; | ||
| } | ||
| try { | ||
| await meeting.mutateAsync(value.recipientEmail.trim()); | ||
| form.reset(); | ||
| } catch { | ||
| // Keep the entered address and show the safe API error below. | ||
| } | ||
| }, | ||
| }); | ||
| const outcome = new URLSearchParams(window.location.search).get( | ||
| 'graphConnection' | ||
| ); | ||
| const error = connect.error ?? check.error ?? status.error; | ||
| const busy = connect.isPending || check.isPending || meeting.isPending; | ||
|
|
||
| const showTestMeeting = status.data?.testMeetingEnabled === true; | ||
|
|
||
| return ( | ||
| <section | ||
| aria-labelledby="development-calendar-title" | ||
| className="mt-8 rounded-sm border border-base-300 p-6" | ||
| > | ||
| <h2 | ||
| className="text-xl font-semibold text-primary" | ||
| id="development-calendar-title" | ||
| > | ||
| {showTestMeeting ? 'Development calendar' : 'Calendar connection'} | ||
| </h2> | ||
| <p className="mt-2 text-base-content/80"> | ||
| Connect the Microsoft account whose default calendar you want to use. | ||
| This account is separate from your Booking login. | ||
| </p> | ||
| <div aria-live="polite" className="mt-4"> | ||
| {status.isPending && <p>Loading calendar connection…</p>} | ||
| {status.data && ( | ||
| <> | ||
| <p className="font-semibold"> | ||
| {status.data.connected | ||
| ? 'Microsoft authentication cached' | ||
| : 'Not connected'} | ||
| </p> | ||
| {status.data.connected && status.data.calendarEmail && ( | ||
| <p>Connected calendar: {status.data.calendarEmail}</p> | ||
| )} | ||
| {status.data.username && ( | ||
| <p>Cached Microsoft account: {status.data.username}</p> | ||
| )} | ||
| <p>{status.data.message}</p> | ||
| </> | ||
| )} | ||
| {outcome === 'connected' && ( | ||
| <p> | ||
| Calendar authentication completed. Run the read-only check to verify | ||
| access. | ||
| </p> | ||
| )} | ||
| {outcome === 'failed' && ( | ||
| <p role="alert"> | ||
| {status.data?.lastError ?? | ||
| 'Calendar authentication failed or expired. Start the connection again.'} | ||
| </p> | ||
| )} | ||
| {error && <p role="alert">{calendarErrorMessage(error)}</p>} | ||
| {check.data && ( | ||
| <div | ||
| className="whitespace-pre-line" | ||
| role={check.data.succeeded ? 'status' : 'alert'} | ||
| > | ||
| {check.data.username && ( | ||
| <p>Microsoft account used for check: {check.data.username}</p> | ||
| )} | ||
| <p>{check.data.message}</p> | ||
| </div> | ||
| )} | ||
| </div> | ||
| <div className="mt-4 flex flex-wrap gap-3"> | ||
| <button | ||
| className="btn btn-primary" | ||
| disabled={!status.data?.configured || busy} | ||
| onClick={() => connect.mutate()} | ||
| type="button" | ||
| > | ||
| {connect.isPending | ||
| ? 'Opening Microsoft sign-in…' | ||
| : showTestMeeting | ||
| ? 'Connect Development Calendar' | ||
| : 'Connect Calendar'} | ||
| </button> | ||
| <button | ||
| className="btn btn-outline" | ||
| disabled={!status.data?.connected || busy} | ||
| onClick={() => check.mutate()} | ||
| type="button" | ||
| > | ||
| {check.isPending | ||
| ? 'Checking calendar…' | ||
| : 'Run read-only connectivity check'} | ||
| </button> | ||
| </div> | ||
| {showTestMeeting && ( | ||
| <> | ||
| <form | ||
| className="mt-6 max-w-xl space-y-3" | ||
| onSubmit={(event) => { | ||
| event.preventDefault(); | ||
| if (!busy) { | ||
| void form.handleSubmit(); | ||
| } | ||
| }} | ||
| > | ||
| <p> | ||
| Create a 30-minute test meeting. Microsoft must verify the | ||
| connected calendar before creating it. The recipient will be added | ||
| as a required attendee. | ||
| </p> | ||
| <form.AppField | ||
| name="recipientEmail" | ||
| validators={{ | ||
| onChange: z | ||
| .email('Enter a valid recipient email address.') | ||
| .max(254), | ||
| }} | ||
| > | ||
| {(field) => ( | ||
| <div> | ||
| <label | ||
| className="block font-semibold" | ||
| htmlFor="test-meeting-recipient" | ||
| > | ||
| Recipient email address | ||
| </label> | ||
| <input | ||
| aria-describedby={ | ||
| !field.state.meta.isValid | ||
| ? 'test-meeting-email-error' | ||
| : undefined | ||
| } | ||
| aria-invalid={!field.state.meta.isValid || undefined} | ||
| className="input input-bordered w-full" | ||
| disabled={busy || !status.data?.connected} | ||
| id="test-meeting-recipient" | ||
| maxLength={254} | ||
| name={field.name} | ||
| onBlur={field.handleBlur} | ||
| onChange={(event) => field.handleChange(event.target.value)} | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Clear the previous meeting error when the recipient changes. After a meeting request fails, this callback updates only the field value. The previous request's error remains visible for the edited recipient. Clear the form error on edit, for example with Based on learnings, “Clear/reset the error state when the user edits the relevant field(s) or retries.”
|
||
| required | ||
| type="email" | ||
| value={field.state.value} | ||
| /> | ||
| {!field.state.meta.isValid && ( | ||
| <p | ||
| className="text-error" | ||
| id="test-meeting-email-error" | ||
| role="alert" | ||
| > | ||
| Enter a valid recipient email address. | ||
| </p> | ||
| )} | ||
| </div> | ||
| )} | ||
| </form.AppField> | ||
| <form.Subscribe | ||
| selector={(state) => [state.canSubmit, state.isSubmitting]} | ||
| > | ||
| {([canSubmit, isSubmitting]) => ( | ||
| <button | ||
| className="btn btn-primary" | ||
| disabled={ | ||
| !status.data?.connected || | ||
| busy || | ||
| !canSubmit || | ||
| isSubmitting | ||
| } | ||
| type="submit" | ||
| > | ||
| {meeting.isPending | ||
| ? 'Creating test meeting…' | ||
| : 'Create Test Meeting'} | ||
| </button> | ||
| )} | ||
| </form.Subscribe> | ||
| <div aria-live="polite"> | ||
| {meeting.isPending && ( | ||
| <p className="flex items-center gap-2" role="status"> | ||
| <span | ||
| aria-hidden="true" | ||
| className="loading loading-spinner loading-sm" | ||
| /> | ||
| Creating the event on the development calendar. Please wait… | ||
| </p> | ||
| )} | ||
| {meeting.error && ( | ||
| <p className="alert alert-error" role="alert"> | ||
| {calendarErrorMessage(meeting.error)} | ||
| </p> | ||
| )} | ||
| </div> | ||
| </form> | ||
| {meeting.data && ( | ||
| <div className="mt-4 break-words" role="status"> | ||
| <p className="font-semibold"> | ||
| Microsoft Graph successfully created the event. | ||
| </p> | ||
| <dl> | ||
| <dt>Calendar used</dt> | ||
| <dd>{meeting.data.calendarEmail}</dd> | ||
| <dt>Calendar ID</dt> | ||
| <dd>{meeting.data.calendarId}</dd> | ||
| <dt>Subject</dt> | ||
| <dd>{meeting.data.subject}</dd> | ||
| <dt>Start (Pacific Time)</dt> | ||
| <dd>{formatPacific(meeting.data.start)}</dd> | ||
| <dt>End (Pacific Time)</dt> | ||
| <dd>{formatPacific(meeting.data.end)}</dd> | ||
| <dt>Invited email address</dt> | ||
| <dd>{meeting.data.recipientEmail}</dd> | ||
| <dt>Graph event ID</dt> | ||
| <dd>{meeting.data.eventId}</dd> | ||
| </dl> | ||
| <p>{meeting.data.message}</p> | ||
| </div> | ||
| )} | ||
| </> | ||
| )} | ||
| </section> | ||
| ); | ||
| } | ||
|
|
||
| function formatPacific(value: string) { | ||
| return new Intl.DateTimeFormat('en-US', { | ||
| dateStyle: 'full', | ||
| timeStyle: 'long', | ||
| timeZone: 'America/Los_Angeles', | ||
| }).format(new Date(value)); | ||
| } | ||
|
|
||
| function calendarErrorMessage(error: unknown): string { | ||
| if (error instanceof HttpError) { | ||
| // ASP.NET routing/antiforgery failures can have an empty response body. | ||
| if (typeof error.body === 'string' && error.body.trim()) { | ||
| return error.body; | ||
| } | ||
| switch (error.status) { | ||
| case 404: | ||
| case 405: | ||
| return 'The running backend does not have the requested calendar endpoint available. Restart the backend, refresh this page, and try again. No meeting was created by this request.'; | ||
| case 400: | ||
| return 'The request was rejected. Refresh this page to renew your session verification token, confirm the recipient email address, and try again.'; | ||
| case 401: | ||
| case 403: | ||
| return 'Calendar access was denied. Sign into Booking as a site administrator and stop emulating before trying again.'; | ||
| default: | ||
| return `The calendar request failed (HTTP ${error.status}). Check the development calendar before retrying if event creation is uncertain.`; | ||
| } | ||
| } | ||
| return 'The calendar request could not be completed. Check your connection and the development calendar before retrying to avoid a duplicate meeting.'; | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,55 @@ | ||
| import { queryOptions } from '@tanstack/react-query'; | ||
| import { fetchJson } from '@/lib/api.ts'; | ||
|
|
||
| export interface DevelopmentGraphStatus { | ||
| calendarEmail: string | null; | ||
| configured: boolean; | ||
| connected: boolean; | ||
| lastError: string | null; | ||
| message: string; | ||
| testMeetingEnabled: boolean; | ||
| username: string | null; | ||
| } | ||
|
|
||
| export const developmentGraphStatusOptions = () => | ||
| queryOptions({ | ||
| gcTime: 0, | ||
| queryFn: ({ signal }) => | ||
| fetchJson<DevelopmentGraphStatus>( | ||
| '/api/development-graph/status', | ||
| { cache: 'no-store' }, | ||
| signal | ||
| ), | ||
| queryKey: ['development-graph', 'status'] as const, | ||
| retry: false, | ||
| }); | ||
|
|
||
| export const connectDevelopmentGraph = () => | ||
| fetchJson<{ authorizationUrl: string }>('/api/development-graph/connect', { | ||
| method: 'POST', | ||
| }); | ||
|
|
||
| export const checkDevelopmentGraph = () => | ||
| fetchJson<{ message: string; succeeded: boolean; username?: string }>( | ||
| '/api/development-graph/check', | ||
| { method: 'POST' } | ||
| ); | ||
|
|
||
| export interface DevelopmentTestMeeting { | ||
| calendarEmail: string; | ||
| calendarId: string; | ||
| created: boolean; | ||
| end: string; | ||
| eventId: string; | ||
| message: string; | ||
| recipientEmail: string; | ||
| start: string; | ||
| subject: string; | ||
| timeZone: string; | ||
| } | ||
|
|
||
| export const createDevelopmentTestMeeting = (recipientEmail: string) => | ||
| fetchJson<DevelopmentTestMeeting>('/api/development-graph/test-meeting', { | ||
| body: JSON.stringify({ recipientEmail }), | ||
| method: 'POST', | ||
| }); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Retain the callback error across status refreshes.
The supplied status contract removes the callback error on its first read. After another status refresh,
lastErrorbecomes null and this branch discards the specific diagnosis. The URL still reports the same failed connection. TanStack Query can refresh stale queries on window focus or network reconnection. (raw.githubusercontent.com)Retain the first non-null callback error independently of refreshed status data. Clear it when the administrator starts another connection attempt.