diff --git a/backend/src/calendar/assertOwnerAvailable.ts b/backend/src/calendar/assertOwnerAvailable.ts new file mode 100644 index 00000000..34738af0 --- /dev/null +++ b/backend/src/calendar/assertOwnerAvailable.ts @@ -0,0 +1,18 @@ +import type { DynamoDBDocumentClient } from '@aws-sdk/lib-dynamodb'; +import { formatBerlinDate, ownerCalendarOverlay } from './ownerCalendarOverlay'; + +export class OwnerAvailabilityError extends Error { + constructor(message: string, public statusCode: 409 | 503) { super(message); this.name = 'OwnerAvailabilityError'; } +} + +/** Fresh read at the last boundary before any calendar write, including retries. */ +export async function assertOwnerAvailable(client: DynamoDBDocumentClient | undefined, startIso: string, endIso: string, existingEventIds: Record = {}): Promise { + const from = formatBerlinDate(startIso), to = formatBerlinDate(endIso); + const projection = await ownerCalendarOverlay({ client, includeAll: true, excludeEventIds: existingEventIds }).project(from, to); + if (projection.connection.state !== 'connected') throw new OwnerAvailabilityError(`Cannot book: owner freebusy unavailable. ${projection.connection.reason || ''}`, 503); + const start = Date.parse(startIso), end = Date.parse(endIso); + const conflicts = projection.items.filter(item => item.startsAt && item.endsAt + ? Date.parse(item.startsAt) < end && Date.parse(item.endsAt) > start + : item.startDate <= to && item.endDate >= from); + if (conflicts.length) throw new OwnerAvailabilityError(`Cannot book: owner calendar conflict: ${conflicts.map(item => item.label).join('; ')}. Use dataops calendar day ${from} to review.`, 409); +} diff --git a/backend/src/calendar/cardInvite.ts b/backend/src/calendar/cardInvite.ts index 3cfdb79a..0ce7be3a 100644 --- a/backend/src/calendar/cardInvite.ts +++ b/backend/src/calendar/cardInvite.ts @@ -1,3 +1,4 @@ +import { assertOwnerAvailable } from './assertOwnerAvailable'; import type { DynamoDBDocumentClient } from '@aws-sdk/lib-dynamodb'; import type { Card, CardCalendarInvite, TaskStatus } from '../types'; import { getCardConsistent, updateCard, updateCardAdditive } from '../db/cards'; @@ -332,6 +333,7 @@ export async function syncCardInvite( }, deps.calendarIds), }; } + await assertOwnerAvailable(client, invite?.startIso || interval.startIso, interval.endIso, eventIds); const reserved = await updateCard(client, card.id, { expectedVersion: card.version, patch: { eventTime: pending, guestEmails: silentLumaEvent ? [] : guests }, @@ -613,8 +615,7 @@ export async function adoptEventDate( ): Promise<{ card: Card; movedTasks: number }> { if (!card.eventTime || card.eventTime.sync !== 'synced') return { card, movedTasks: 0 }; const date = todayIn(card.eventTime.timeZone, new Date(card.eventTime.startIso)); - const followed = !card.anchorDate || (previous && card.anchorDate === todayIn(previous.timeZone, new Date(previous.startIso))); - if (!followed || card.anchorDate === date) return { card, movedTasks: 0 }; + if (card.anchorDate === date) return { card, movedTasks: 0 }; const updated = await updateCardAdditive(client, card, () => ({ anchorDate: date })); const { updatedCount } = await redateCardTemplateTasks(client, { ...updated, anchorDate: date }, { reason: `Adopted event date ${date}`, diff --git a/backend/src/calendar/holdGoogleSync.ts b/backend/src/calendar/holdGoogleSync.ts index ae67a3e3..4c12fa71 100644 --- a/backend/src/calendar/holdGoogleSync.ts +++ b/backend/src/calendar/holdGoogleSync.ts @@ -1,3 +1,4 @@ +import { assertOwnerAvailable, OwnerAvailabilityError } from './assertOwnerAvailable'; /** * Google mirroring for calendar holds, per SOP * `sop.events.calendar.creating-tentative-event-on-google-calendar`. @@ -207,6 +208,7 @@ async function syncEvents( if (calendars.includes('primary') || calendars.includes(HOLD_ORGANIZER)) { return deferred('Hold calendars must name personal calendars explicitly; primary is the Orin organizer calendar.'); } + await assertOwnerAvailable(undefined, event.startIso, event.endIso, eventIds); // Stable opaque UID enables recovery after partial writes without leaking the hold id. const uid = `${createHash('sha256').update(event.eventKey).digest('hex')}@google.com`; const body = eventBody(event); @@ -281,6 +283,7 @@ async function syncEvents( } return { state: 'synced', eventIds }; } catch (error) { + if (error instanceof OwnerAvailabilityError) throw error; const reason = error instanceof Error && error.message.startsWith('Google ') ? error.message : 'Google Calendar sync could not complete; retry the hold after checking the Orin connection.'; return deferred(reason); diff --git a/backend/src/calendar/ownerAvailability.ts b/backend/src/calendar/ownerAvailability.ts new file mode 100644 index 00000000..4c557c0a --- /dev/null +++ b/backend/src/calendar/ownerAvailability.ts @@ -0,0 +1,73 @@ +import { OWNER_PERSONAL_CALENDAR } from '../identity/operatingIdentities'; + +const GOOGLE = 'https://www.googleapis.com/calendar/v3'; +export type AvailabilityEvent = { + id?: string; summary?: string; status?: string; transparency?: string; htmlLink?: string; + start?: { date?: string; dateTime?: string }; end?: { date?: string; dateTime?: string }; + calendarId?: string; +}; + +/** Only placeholders, never named lunches, meetings, routines or hard No blocks. */ +export function isSoftEvent(event: AvailabilityEvent): boolean { + return /^(lunch|lunchtime|lunch break|обед|dtc event block|datatalks\.club event|dtc event|dtc buffer)$/i.test((event.summary || '').trim()); +} + +function bounds(event: AvailabilityEvent): [number, number] { + return [Date.parse(event.start?.dateTime || `${event.start?.date}T00:00:00Z`), Date.parse(event.end?.dateTime || `${event.end?.date}T00:00:00Z`)]; +} + +/** Read every calendar on the owner's account, including hidden calendars and every page. + * Freebusy closes gaps from private/redacted events; only fully explained busy time can be softened. + */ +export async function readOwnerAvailability(run: typeof fetch, token: string, from: string, to: string): Promise { + const headers = { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' }; + async function request(path: string, body?: unknown): Promise { + const response = await run(`${GOOGLE}${path}`, { headers, signal: AbortSignal.timeout(15000), ...(body ? { method: 'POST', body: JSON.stringify(body) } : {}) }); + if (!response.ok) throw new Error(`Owner calendar availability returned HTTP ${response.status}; no time can be booked`); + return response.json(); + } + const primary = await request('/calendars/primary'); + if (primary.id?.toLowerCase() !== OWNER_PERSONAL_CALENDAR) throw new Error('Availability requires Alexey’s Google Calendar connection; the organizer connection cannot enumerate his calendars'); + const calendars = new Set([OWNER_PERSONAL_CALENDAR]); + let page: string | undefined; + do { + const data = await request(`/users/me/calendarList?showHidden=true&maxResults=250${page ? `&pageToken=${encodeURIComponent(page)}` : ''}`); + if (!Array.isArray(data.items)) throw new Error('Invalid owner calendar list; availability is unknown'); + for (const calendar of data.items) if (!calendar.deleted && calendar.id) calendars.add(calendar.id); + page = data.nextPageToken; + } while (page); + // Widen UTC bounds to include the complete Berlin dates in either DST offset. + const timeMin = new Date(Date.parse(`${from}T00:00:00Z`) - 86400000).toISOString(); + const timeMax = new Date(Date.parse(`${to}T00:00:00Z`) + 2 * 86400000).toISOString(); + const result: AvailabilityEvent[] = []; + const ids = [...calendars]; + for (let offset = 0; offset < ids.length; offset += 50) { + const group = ids.slice(offset, offset + 50); + const freebusy = await request('/freeBusy', { timeMin, timeMax, items: group.map(id => ({ id })) }); + for (const id of group) { + const availability = freebusy.calendars?.[id]; + if (!availability || availability.errors?.length || !Array.isArray(availability.busy)) throw new Error('Owner calendar freebusy is incomplete; no time can be booked'); + const events: AvailabilityEvent[] = []; + page = undefined; + do { + const query = new URLSearchParams({ timeMin, timeMax, singleEvents: 'true', maxResults: '2500', ...(page ? { pageToken: page } : {}) }); + const data = await request(`/calendars/${encodeURIComponent(id)}/events?${query}`); + if (!Array.isArray(data.items)) throw new Error('Invalid owner calendar events; availability is unknown'); + events.push(...data.items.map((event: AvailabilityEvent) => ({ ...event, calendarId: id }))); + page = data.nextPageToken; + } while (page); + result.push(...events); + for (const busy of availability.busy) { + let gaps: Array<[number, number]> = [[Date.parse(busy.start), Date.parse(busy.end)]]; + if (!gaps.every(([start, end]) => Number.isFinite(start) && Number.isFinite(end) && start < end)) throw new Error('Invalid freebusy interval; availability is unknown'); + for (const event of events) { + if (event.status === 'cancelled' || event.transparency === 'transparent') continue; + const [start, end] = bounds(event); + gaps = gaps.flatMap(([a,b]) => start >= b || end <= a || !Number.isFinite(start + end) ? [[a,b]] : [...(a < start ? [[a,start]] : []), ...(end < b ? [[end,b]] : [])]) as Array<[number,number]>; + } + result.push(...gaps.map(([start,end], i) => ({ id: `freebusy:${busy.start}:${i}`, calendarId: id, summary: 'Busy (freebusy)', start: { dateTime: new Date(start).toISOString() }, end: { dateTime: new Date(end).toISOString() } }))); + } + } + } + return result; +} diff --git a/backend/src/calendar/ownerCalendarOverlay.ts b/backend/src/calendar/ownerCalendarOverlay.ts index 88c599c9..e71babae 100644 --- a/backend/src/calendar/ownerCalendarOverlay.ts +++ b/backend/src/calendar/ownerCalendarOverlay.ts @@ -1,3 +1,4 @@ +import { readOwnerAvailability, isSoftEvent } from './ownerAvailability'; import type { DynamoDBDocumentClient } from '@aws-sdk/lib-dynamodb'; import type { CalendarOverlayConnection, CalendarOverlayItem, CalendarOverlayProjection, CalendarOverlayProvider } from './overlays'; import { @@ -23,6 +24,7 @@ export interface OwnerCalendarConfig { accountId?: string; settings?: CalendarOverlaySettings; includeAll?: boolean; + excludeEventIds?: Record; /** Berlin date the overlay counts as today; defaults to the current one. */ today?: string; /** Free contiguous block length in minutes. Default 60; workshops use 90. */ @@ -200,6 +202,7 @@ export interface DapierConnectionOption { connectionId: string; provider: string; title: string; + accountId?: string; } export interface OwnerCalendarEventContext { @@ -357,7 +360,7 @@ export function shouldFilterOwnerCalendarEvent( // Transparent (free/non-blocking) events (unless flights/conferences/vacations) if (filterTransparent && context?.transparency === 'transparent') { - if (!/(flight|conference|vacation|trip)/i.test(s)) { + if (!/(flight|conference|vacation|trip|summit)/i.test(s)) { return true; } } @@ -416,6 +419,7 @@ export async function fetchDapierConnections(config?: OwnerCalendarConfig): Prom ).map((c) => ({ connectionId: c.connection_id, provider: c.provider, + accountId: c.verified_account_id, title: `${c.connection_id}${c.verified_account_id || c.account_title ? ` (${c.verified_account_id || c.account_title})` : ''}`, })); return { connections, ...(!connections.length ? { connectionProblem: `No writable Google Calendar connections are available to agent "${config?.agent || DAPIER_AGENT}". A Dapier operator must connect Google Calendar and grant this machine identity and agent the \`use\` operation.` } : {}) }; @@ -449,7 +453,12 @@ export function ownerCalendarOverlay(config?: OwnerCalendarConfig): CalendarOver const brokerUrl = (config?.brokerUrl || DAPIER_BASE_URL).replace(/\/$/, ''); const agent = config?.agent || DAPIER_AGENT; - const connectionId = (config?.connectionId ?? activeSettings.connectionId).trim(); + let connectionId = (config?.connectionId ?? activeSettings.connectionId).trim(); + if (!config?.connectionId) { + const discovery = await fetchDapierConnections(config); + connectionId = discovery.connections.find(c => c.accountId?.toLowerCase() === OWNER_PERSONAL_CALENDAR)?.connectionId || ''; + if (!connectionId) return blank({ state: 'unavailable', reason: discovery.connectionProblem || 'Alexey’s Google Calendar connection is required to check all his calendars.' }); + } if (!connectionId) return blank({ state: 'not-configured', reason: `No Dapier calendar connection selected. ${CONNECTION_OPERATOR_HINT}` }); const { credential, problem } = await readDapierCredential(config?.brokerCredential); @@ -482,27 +491,13 @@ export function ownerCalendarOverlay(config?: OwnerCalendarConfig): CalendarOver return blank({ state: 'unavailable', reason: `Calendar connection "${connectionId}" returned no access token.` }); } - // 2. Query Google Calendar API - const timeMin = `${from}T00:00:00Z`; - const timeMax = `${to}T23:59:59Z`; - const url = `https://www.googleapis.com/calendar/v3/calendars/${encodeURIComponent(OWNER_PERSONAL_CALENDAR)}/events?timeMin=${encodeURIComponent(timeMin)}&timeMax=${encodeURIComponent(timeMax)}&singleEvents=true&orderBy=startTime&maxResults=2500`; - - let calRes: Response; + let events: import('./ownerAvailability').AvailabilityEvent[]; try { - calRes = await fetcher(url, { - headers: { Authorization: `Bearer ${tokenData.access_token}` }, - signal: AbortSignal.timeout(15000), - }); - } catch { - return blank({ state: 'unavailable', reason: 'Google Calendar could not be reached.' }); - } - - if (!calRes.ok) { - return blank({ state: 'unavailable', reason: `Google Calendar returned HTTP ${calRes.status}.` }); + events = await readOwnerAvailability(fetcher, tokenData.access_token, from, to); + } catch (error) { + return blank({ state: 'unavailable', reason: error instanceof Error ? error.message : 'Owner freebusy failed; availability is unknown.' }); } - - const calData = (await calRes.json()) as { items?: any[] }; - const events = calData.items || []; + events = events.filter(e => !e.id || !e.calendarId || config?.excludeEventIds?.[e.calendarId] !== e.id); const includeAll = Boolean(config?.includeAll); const effectiveSettings: CalendarOverlaySettings = includeAll @@ -595,7 +590,10 @@ export function ownerCalendarOverlay(config?: OwnerCalendarConfig): CalendarOver startIso, endIso, }; - if (shouldFilterOwnerCalendarEvent(event.summary, effectiveSettings, context)) continue; + // Display preferences cannot weaken scheduling policy. Hard blocks, including + // transparent all-day No/conference entries, always close the date. + if (isSoftEvent(event)) continue; + if (!isAllDay && event.transparency === 'transparent' && !/^no$/i.test(event.summary || '')) continue; const summary = (event.summary || '').trim() || '(No title)'; let startDate: string; @@ -613,6 +611,7 @@ export function ownerCalendarOverlay(config?: OwnerCalendarConfig): CalendarOver continue; } + if (startDate > to || endDate < from) continue; const slot = determineSlotType(startIso, endIso, isAllDay); const isSlotEvent = slot !== 'outside'; @@ -644,7 +643,7 @@ export function ownerCalendarOverlay(config?: OwnerCalendarConfig): CalendarOver result.push({ provider: 'owner-calendar', - id: `owner-calendar:${item.event.id}`, + id: `owner-calendar:${item.event.calendarId}:${item.event.id}`, startDate: item.startDate, endDate: item.endDate, label, @@ -665,7 +664,7 @@ export function ownerCalendarOverlay(config?: OwnerCalendarConfig): CalendarOver // are never projected as items. They only decide which slots are open. // All-day blockers (vacations, conferences, flights, etc.) close the whole day. const allDayBlockers = validEvents.filter( - (e) => e.isAllDay || e.slot === 'all-day' || (/vacation|holiday|flight|conference|trip/i.test(e.summary) && e.isSlotEvent), + (e) => e.isAllDay || e.slot === 'all-day' || (/vacation|holiday|flight|conference|trip|summit/i.test(e.summary) && e.isSlotEvent), ); // Project available slots across all weekdays in the range. @@ -696,7 +695,7 @@ export function ownerCalendarOverlay(config?: OwnerCalendarConfig): CalendarOver // Check Midday Slot (operational window 11:30–14:00, preferred start 12:30 Berlin time) if (wantMidday) { - const busy = busyIntervalsInWindow('midday', dayTimedEvents); + const busy = dayTimedEvents.map(e => ({ start: e.startDate < curDate ? '00:00' : formatBerlinTime(e.startIso!), end: e.endDate > curDate || !e.endIso ? '24:00' : formatBerlinTime(e.endIso) })); if (isWindowFreeForDuration('midday', busy, durationMinutes)) { result.push({ provider: 'owner-calendar', @@ -716,7 +715,7 @@ export function ownerCalendarOverlay(config?: OwnerCalendarConfig): CalendarOver // preferred start 17:00; 90-min workshop shape anchors at 16:30) // Per SOP: offered on Monday and Tuesday only (US guests) if (wantEvening && (dayOfWeek === 1 || dayOfWeek === 2)) { - const busy = busyIntervalsInWindow('evening', dayTimedEvents); + const busy = dayTimedEvents.map(e => ({ start: e.startDate < curDate ? '00:00' : formatBerlinTime(e.startIso!), end: e.endDate > curDate || !e.endIso ? '24:00' : formatBerlinTime(e.endIso) })); if (isWindowFreeForDuration('evening', busy, durationMinutes)) { result.push({ provider: 'owner-calendar', diff --git a/backend/src/events/guestAgreement.ts b/backend/src/events/guestAgreement.ts new file mode 100644 index 00000000..72545cbb --- /dev/null +++ b/backend/src/events/guestAgreement.ts @@ -0,0 +1,9 @@ +export interface GuestAgreement { agreedFrom?: string; agreedTo?: string } +export function validateGuestAgreement(input: GuestAgreement, requestedDate?: string): void { + for (const key of ['agreedFrom', 'agreedTo'] as const) { + const value = input[key]; + if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(value) || !Number.isFinite(Date.parse(`${value}T12:00:00Z`)) || new Date(`${value}T12:00:00Z`).toISOString().slice(0,10) !== value) throw new Error('Record the guest agreement with agreedFrom and agreedTo as real YYYY-MM-DD dates before scheduling'); + } + if (input.agreedFrom! > input.agreedTo!) throw new Error('Guest agreement dates must be in order'); + if (requestedDate && (requestedDate < input.agreedFrom! || requestedDate > input.agreedTo!)) throw new Error('Requested date is outside the guest agreement'); +} diff --git a/backend/src/events/guestIntakeAllocator.ts b/backend/src/events/guestIntakeAllocator.ts index 769e1c8b..c963a934 100644 --- a/backend/src/events/guestIntakeAllocator.ts +++ b/backend/src/events/guestIntakeAllocator.ts @@ -1,15 +1,31 @@ +import { transactWrite } from '../db/transactWrite'; import { UpdateCommand, type DynamoDBDocumentClient } from '@aws-sdk/lib-dynamodb'; import { TABLE_ARTIFACTS } from '../db/tableNames'; -const allocatorKey = { PK: 'GUESTINTAKEALLOCATOR', SK: 'GUESTINTAKEALLOCATOR' }; -/** Shared allocator lease covers availability read through durable Calendar proposal. Lambda timeout is 120s, lease 150s. */ -export async function claimGuestSlotAllocator(db: DynamoDBDocumentClient, id: string): Promise { +import { eachDayOfInterval, formatBerlinDate } from '../calendar/ownerCalendarOverlay'; +const allocatorKey = (date: string) => ({ PK: `GUESTINTAKEALLOCATOR#${date}`, SK: `GUESTINTAKEALLOCATOR#${date}` }); +export const allocationDates = (startIso: string, endIso: string) => eachDayOfInterval(formatBerlinDate(startIso), formatBerlinDate(endIso)); +/** Serialize only overlapping dates. An unrelated failed Card never owns the entire calendar. */ +export async function claimGuestSlotAllocator(db: DynamoDBDocumentClient, id: string, dates: string[]): Promise { + const unique = [...new Set(dates)].sort(); + if (!unique.length || unique.length > 3 || unique.some(date => !/^\d{4}-\d{2}-\d{2}$/.test(date))) throw new Error('A reservation lease needs one to three Berlin dates'); + const now = Date.now(); try { - await db.send(new UpdateCommand({ TableName: TABLE_ARTIFACTS, Key: allocatorKey, + await transactWrite(db, unique.map(date => ({ Update: { + TableName: TABLE_ARTIFACTS, Key: allocatorKey(date), UpdateExpression: 'SET leaseUntil = :lease, ownerId = :id', ConditionExpression: 'attribute_not_exists(leaseUntil) OR leaseUntil < :now', - ExpressionAttributeValues: { ':lease': Date.now() + 150000, ':now': Date.now(), ':id': id } })); + ExpressionAttributeValues: { ':lease': now + 150000, ':now': now, ':id': id }, + } }))); return true; - } catch (error) { if ((error as Error).name === 'ConditionalCheckFailedException') return false; throw error; } + } catch (error) { + const e = error as { name?: string; CancellationReasons?: Array<{ Code?: string }> }; + if (e.name === 'ConditionalCheckFailedException' || e.name === 'TransactionCanceledException' && e.CancellationReasons?.some(reason => reason.Code === 'ConditionalCheckFailed')) return false; + throw error; + } } -export async function releaseAllocator(db: DynamoDBDocumentClient, id: string) { - await db.send(new UpdateCommand({ TableName: TABLE_ARTIFACTS, Key: allocatorKey, UpdateExpression: 'SET leaseUntil = :zero', ConditionExpression: 'ownerId = :id', ExpressionAttributeValues: { ':zero': 0, ':id': id } })); +export async function releaseAllocator(db: DynamoDBDocumentClient, id: string, dates: string[]) { + for (const date of new Set(dates)) { + try { + await db.send(new UpdateCommand({ TableName: TABLE_ARTIFACTS, Key: allocatorKey(date), UpdateExpression: 'SET leaseUntil = :zero', ConditionExpression: 'ownerId = :id', ExpressionAttributeValues: { ':zero': 0, ':id': id } })); + } catch (error) { if ((error as Error).name !== 'ConditionalCheckFailedException') throw error; } + } } diff --git a/backend/src/events/guestIntakeCreate.ts b/backend/src/events/guestIntakeCreate.ts index 047f91c9..3c0176c9 100644 --- a/backend/src/events/guestIntakeCreate.ts +++ b/backend/src/events/guestIntakeCreate.ts @@ -1,3 +1,4 @@ +import { validateGuestAgreement } from './guestAgreement'; import { loadAssignmentPolicy } from '../db/workspaceSettings'; import { createHash } from 'node:crypto'; import type { DynamoDBDocumentClient } from '@aws-sdk/lib-dynamodb'; @@ -30,6 +31,7 @@ export async function prepareGuestIntake(db: DynamoDBDocumentClient, actorId: st if (body.time !== undefined && (typeof body.time !== 'string' || !/^([01]\d|2[0-3]):[0-5]\d$/.test(body.time))) throw new Error('time must be HH:MM'); if (body.time && !body.anchorDate) throw new Error('An explicit time requires anchorDate'); if (body.window !== undefined && (typeof body.window !== 'string' || !Object.hasOwn(template.eventPolicy?.windows || (template.base?.eventPolicy as import('./policy').EventPolicy | undefined)?.windows || {}, body.window))) throw new Error('window must name a configured event window'); + if (body.agreedFrom !== undefined || body.agreedTo !== undefined) validateGuestAgreement(body as import('./guestAgreement').GuestAgreement, body.anchorDate as string | undefined); const fingerprint = hash(JSON.stringify(canonical({ ...body, templateId: template.id, guestEmail: guest.email, guestName: guest.name }))); const creationKey = typeof body.creationKey === 'string' && body.creationKey.trim() ? body.creationKey.trim() : `auto:${fingerprint}`; if (creationKey.length > 200) throw new Error('creationKey is too long'); @@ -45,6 +47,8 @@ export async function prepareGuestIntake(db: DynamoDBDocumentClient, actorId: st status: guest.email ? 'queued' : 'contact-pending', guestEmail: guest.email, guestName: guest.name, topic: typeof body.topic === 'string' && body.topic.trim() ? body.topic.trim() : undefined, skipEmail: body.skipEmail === true, + agreedFrom: typeof body.agreedFrom === 'string' ? body.agreedFrom : undefined, + agreedTo: typeof body.agreedTo === 'string' ? body.agreedTo : undefined, requestedDate: typeof body.anchorDate === 'string' ? body.anchorDate : undefined, requestedTime: typeof body.time === 'string' ? body.time : undefined, timeZone: typeof body.timeZone === 'string' ? body.timeZone : 'Europe/Berlin', diff --git a/backend/src/events/guestIntakePortal.ts b/backend/src/events/guestIntakePortal.ts index 9c5f4b9d..df94eb5b 100644 --- a/backend/src/events/guestIntakePortal.ts +++ b/backend/src/events/guestIntakePortal.ts @@ -6,6 +6,7 @@ import { getGuestIntakeJob } from './guestIntakeStore'; import { guestEventSlots } from './guestIntakeSlots'; import { resolveCardEventPolicy, approveEvent, rescheduleEvent, retryEventOperation } from './service'; import { getEventRecord } from './store'; +import { formatBerlinDate } from '../calendar/ownerCalendarOverlay'; import { claimGuestSlotAllocator, releaseAllocator } from './guestIntakeAllocator'; import { PutCommand, ScanCommand, UpdateCommand, GetCommand } from '@aws-sdk/lib-dynamodb'; import { getSponsorDocWithAuthMaterial } from '../db/sponsorDocs'; @@ -85,6 +86,7 @@ export async function processGuestChoice(db: DynamoDBDocumentClient, item: Recor } catch (error) { if ((error as Error).name === 'ConditionalCheckFailedException') return; throw error; } let allocator = false; const owner = `choice-${token}`; + const dates = [item.choice?.match(/^slot:(\d{4}-\d{2}-\d{2}):/)?.[1] || formatBerlinDate(item.intent.proposalStartIso)]; const finish = async (status: string, error?: string) => { try { await db.send(new UpdateCommand({ TableName: TABLE_ARTIFACTS, Key: choiceKey(item.docId), @@ -104,7 +106,7 @@ export async function processGuestChoice(db: DynamoDBDocumentClient, item: Recor }; try { await assertCurrent(); - allocator = await claimGuestSlotAllocator(db, owner); + allocator = await claimGuestSlotAllocator(db, owner, dates); if (!allocator) throw new Error('A time is being reserved; try shortly'); const loaded = (await getSponsorDocWithAuthMaterial(db, item.docId))!; await applyGuestPortalTimeChoice(db, { ...loaded.doc, version: item.version }, item.intent, assertCurrent); @@ -120,7 +122,7 @@ export async function processGuestChoice(db: DynamoDBDocumentClient, item: Recor if (task) await updateTask(db, task.id, { currentTask: task, expectedVersion: task.version, patch: { comment: `Guest time choice needs attention: ${message}` }, actorId: 'guest-portal', triggerKind: 'guest-time-choice-failed' }); throw error; } else { await finish('pending', message); throw error; } - } finally { if (allocator) await releaseAllocator(db, owner); } + } finally { if (allocator) await releaseAllocator(db, owner, dates); } } /** Persist explicit guest-origin intent before provider calls; ordinary bio saves never enter here. */ diff --git a/backend/src/events/guestIntakeSlots.ts b/backend/src/events/guestIntakeSlots.ts index 62fab6e7..6f5d3865 100644 --- a/backend/src/events/guestIntakeSlots.ts +++ b/backend/src/events/guestIntakeSlots.ts @@ -1,3 +1,4 @@ +import { validateGuestAgreement } from './guestAgreement'; import type { DynamoDBDocumentClient } from '@aws-sdk/lib-dynamodb'; import { ownerCalendarOverlay, berlinToday } from '../calendar/ownerCalendarOverlay'; import { cardEventInterval } from '../calendar/cardEventTime'; @@ -15,8 +16,10 @@ export function berlinParts(iso: string) { } export interface GuestEventSlot { date: string; time: string; window: string; startIso: string; endIso: string; label: string } export async function guestEventSlots(db: DynamoDBDocumentClient, job: GuestIntakeJob, policy: EventPolicy, count = 8): Promise { - const from = job.requestedDate || addDays(berlinToday(), job.policy?.minimumNoticeDays || 0); - const to = job.requestedDate || addDays(from, 59); + if (job.policy?.enabled) validateGuestAgreement(job, job.requestedDate); + const earliest = addDays(berlinToday(), job.policy?.minimumNoticeDays || 0); + const from = job.requestedDate || (job.agreedFrom && job.agreedFrom > earliest ? job.agreedFrom : earliest); + const to = job.requestedDate || job.agreedTo || addDays(from, 59); const [overlay, busy, holds, cards, episodes] = await Promise.all([ ownerCalendarOverlay({ client: db, durationMinutes: policy.durationMinutes, window: 'any' }).project(from, to), ownerCalendarOverlay({ client: db, includeAll: true, durationMinutes: policy.durationMinutes }).project(addDays(from, -1), addDays(to, 1)), @@ -31,7 +34,7 @@ export async function guestEventSlots(db: DynamoDBDocumentClient, job: GuestInta const interval = cardEventInterval(`${day} ${job.requestedTime || policy.windows[window]}`, policy.durationMinutes, job.requestedTime ? job.timeZone || 'Europe/Berlin' : policy.timeZone); const parts = berlinParts(interval.startIso); if ([0,6].includes(new Date(`${parts.date}T12:00:00Z`).getUTCDay())) continue; - if (job.policy?.weekdays?.length && !job.policy.weekdays.includes(new Date(`${parts.date}T12:00:00Z`).getUTCDay())) continue; + if (!job.requestedDate && job.policy?.weekdays?.length && !job.policy.weekdays.includes(new Date(`${parts.date}T12:00:00Z`).getUTCDay())) continue; const start = Date.parse(interval.startIso) - policy.guests.leadMinutes * 60000, end = Date.parse(interval.endIso); if (start <= Date.now()) continue; if (!job.requestedTime && job.type === 'podcast' && !overlay.items.some(i => i.isAvailableSlot && i.startDate === day && i.slot === window)) continue; diff --git a/backend/src/events/guestIntakeStore.ts b/backend/src/events/guestIntakeStore.ts index 29ecf28e..7d0ca03e 100644 --- a/backend/src/events/guestIntakeStore.ts +++ b/backend/src/events/guestIntakeStore.ts @@ -6,6 +6,7 @@ export interface GuestIntakeJob { id: string; cardId: string; taskId: string; actorId: string; type: string; creationKey: string; fingerprint: string; status: GuestIntakeStatus; guestEmail?: string; guestName?: string; topic?: string; skipEmail: boolean; + agreedFrom?: string; agreedTo?: string; requestedDate?: string; requestedTime?: string; timeZone?: string; guestTimezone?: string; requestedWindow?: string; policy?: GuestIntakePolicy; holdId?: string; docId?: string; selectedDate?: string; selectedTime?: string; selectedWindow?: string; messageId?: string; sentAt?: string; startIso?: string; error?: string; lastReportedError?: string; retryable?: boolean; leaseUntil?: number; diff --git a/backend/src/events/guestIntakeWorker.ts b/backend/src/events/guestIntakeWorker.ts index bd8bae42..307149ac 100644 --- a/backend/src/events/guestIntakeWorker.ts +++ b/backend/src/events/guestIntakeWorker.ts @@ -1,7 +1,8 @@ import { resolveGuestAcceptanceTask } from './guestIntakeCompletion'; +import { validateGuestAgreement } from './guestAgreement'; import { makeTaskHistoryEvent } from '../routes/taskValidation'; import { resumeGuestPortalTimeChoices } from './guestIntakePortal'; -import { claimGuestSlotAllocator, releaseAllocator } from './guestIntakeAllocator'; +import { claimGuestSlotAllocator, releaseAllocator, allocationDates } from './guestIntakeAllocator'; export { claimGuestSlotAllocator } from './guestIntakeAllocator'; import { type DynamoDBDocumentClient } from '@aws-sdk/lib-dynamodb'; import { TABLE_ARTIFACTS } from '../db/tableNames'; @@ -39,10 +40,12 @@ async function recordFailure(db: DynamoDBDocumentClient, job: GuestIntakeJob, er } export async function processGuestIntake(db: DynamoDBDocumentClient, id: string): Promise { let job = await getGuestIntakeJob(db, id); + if (job && (await getTaskConsistent(db, job.taskId))?.status === 'done') return; if (!job || !APPROVED_GUEST_EVENT_TYPES.has(job.type) || ['sent', 'skipped', 'contact-pending', 'cancelled'].includes(job.status) || job.retryable === false) return; if (!await claimGuestIntakeJob(db, job)) throw new Error('Invitation is already being prepared; retry after its lease'); job = (await getGuestIntakeJob(db, id))!; let allocator = false; + let dates: string[] = []; try { const card = await getCardConsistent(db, job.cardId); if (!card || card.status === 'archived') { @@ -56,7 +59,9 @@ export async function processGuestIntake(db: DynamoDBDocumentClient, id: string) } return; } + if (card.anchorDate && job.requestedDate && card.anchorDate !== job.requestedDate) throw new Error('Invitation date differs from the Card date; reconcile the guest agreement before retrying. The old slot was not replayed.'); if (!job.guestEmail || !job.policy?.enabled) throw new Error('Guest email and enabled event intake policy are required'); + validateGuestAgreement(job, job.requestedDate); job.status = 'preparing'; delete job.error; await saveGuestIntakeJob(db, job); await projectJob(db, job); const { policy } = await resolveCardEventPolicy(db, card); @@ -75,10 +80,14 @@ export async function processGuestIntake(db: DynamoDBDocumentClient, id: string) await saveGuestIntakeJob(db, job); let event = await getEventRecord(db, `hold_${card.id}`); if (!event) { - allocator = await claimGuestSlotAllocator(db, id); - if (!allocator) throw new Error('Another invitation is reserving a time; this invitation will resume automatically'); - const slots = await guestEventSlots(db, job, policy, 1); - if (!slots.length) throw new Error('No available event time was found; update the scheduling preference on the invitation Task'); + const candidates = await guestEventSlots(db, job, policy, 1); + if (!candidates.length) throw new Error('No available event time was found inside the guest agreement'); + const candidate = candidates[0]; + dates = allocationDates(new Date(Date.parse(candidate.startIso) - policy.guests.leadMinutes * 60000).toISOString(), candidate.endIso); + allocator = await claimGuestSlotAllocator(db, id, dates); + if (!allocator) throw new Error(`Another invitation is reserving ${dates.join(', ')}; retry after its short lease`); + // Listing is advisory: refresh the chosen interval under its date lease. + const slots = await guestEventSlots(db, { ...job, requestedDate: candidate.date, requestedTime: candidate.time, timeZone: 'Europe/Berlin' }, policy, 1); const slot = slots[0]; job.selectedDate = slot.date; job.selectedTime = slot.time; job.selectedWindow = slot.window; job.startIso = slot.startIso; await saveGuestIntakeJob(db, job); // Validate the editable copy before the first guest-facing Calendar operation. @@ -88,6 +97,7 @@ export async function processGuestIntake(db: DynamoDBDocumentClient, id: string) if (result.sync.state !== 'synced') throw new Error(`Calendar invitation is pending: ${result.sync.reason || 'provider unavailable'}`); event = result.event; } else { + validateGuestAgreement(job, event.date); if (event.status !== 'proposed' && event.status !== 'approved') { job.status = 'cancelled'; job.retryable = false; job.error = 'Invitation cancelled because its linked event was released'; await saveGuestIntakeJob(db, job); await projectJob(db, job); return; @@ -107,7 +117,7 @@ export async function processGuestIntake(db: DynamoDBDocumentClient, id: string) } job.holdId = event.id; job.startIso = event.startIso; await saveGuestIntakeJob(db, job); - if (allocator) { await releaseAllocator(db, id); allocator = false; } + if (allocator) { await releaseAllocator(db, id, dates); allocator = false; } if (job.skipEmail) { job.status = 'skipped'; await saveGuestIntakeJob(db, job); await projectJob(db, job); return; } @@ -130,13 +140,14 @@ export async function processGuestIntake(db: DynamoDBDocumentClient, id: string) } job.status = 'sent'; await saveGuestIntakeJob(db, job); await projectJob(db, job); } catch (error) { await recordFailure(db, job, error); throw error; } - finally { if (allocator) await releaseAllocator(db, id); await releaseGuestIntakeLease(db, job); } + finally { if (allocator) await releaseAllocator(db, id, dates); await releaseGuestIntakeLease(db, job); } } export async function resumeGuestIntakes(db: DynamoDBDocumentClient) { const jobs = await listResumableGuestIntakes(db); const outcomes: Array<{ id: string; ok: boolean }> = []; - // Bound each scheduled invocation; unprocessed durable rows remain for the next run. - for (const job of jobs.sort((a,b) => a.updatedAt.localeCompare(b.updatedAt)).slice(0, 1)) { + // Bound each scheduled invocation while prioritizing queued work over retries so one failed job never starves others. + const priority = (j: GuestIntakeJob) => (j.status === 'queued' || j.status === 'preparing' ? 0 : j.status === 'failed' ? 1 : 2); + for (const job of jobs.sort((a,b) => priority(a) - priority(b) || a.updatedAt.localeCompare(b.updatedAt)).slice(0, 5)) { try { await processGuestIntake(db, job.id); outcomes.push({ id: job.id, ok: true }); } catch { outcomes.push({ id: job.id, ok: false }); } } diff --git a/backend/src/events/service.ts b/backend/src/events/service.ts index 259e9c7d..0b9720de 100644 --- a/backend/src/events/service.ts +++ b/backend/src/events/service.ts @@ -1,6 +1,6 @@ import { cardEventInterval } from '../calendar/cardEventTime'; import { manualCalendarPolicy } from './manualCalendarPolicy'; -import { claimGuestSlotAllocator, releaseAllocator } from './guestIntakeAllocator'; +import { claimGuestSlotAllocator, releaseAllocator, allocationDates } from './guestIntakeAllocator'; import { guestEventSlots } from './guestIntakeSlots'; import type { GuestIntakeJob } from './guestIntakeStore'; import { resolveGuestAcceptanceTask } from './guestIntakeCompletion'; @@ -428,6 +428,8 @@ export async function reconcileEventOperation( // Reload after claiming lease current = (await getEventRecord(client, eventId, operationKey))!; + const cardSnapshot = await getCardConsistent(client, current.cardId); + if (op.transition !== 'release' && (op.desired.endIso !== current.endIso || cardSnapshot?.eventTime?.startIso !== current.startIso)) throw new EventConflictError('Invitation journal differs from the Card event time; reconcile the moved invitation before retrying. The old slot was not replayed.'); const googleEventKey = current.identityGeneration === 1 ? current.id : `${current.id}:gen:${current.identityGeneration}`; @@ -1014,7 +1016,9 @@ async function explicitManualTransition(client: DynamoDBDocumentClient, transiti const time = input.time || (input.window ? policy.windows[input.window] : current?.time); if (!date || !time) throw new EventInputError('Supply --date and --time for this Calendar-only blocker'); const owner = `manual-${randomUUID()}`; - if (!await claimGuestSlotAllocator(client, owner)) throw new EventConflictError('Another event is reserving a time; retry shortly'); + const interval = cardEventInterval(`${date} ${time}`, policy.durationMinutes, input.timeZone || policy.timeZone); + const dates = allocationDates(new Date(Date.parse(interval.startIso) - policy.guests.leadMinutes * 60000).toISOString(), interval.endIso); + if (!await claimGuestSlotAllocator(client, owner, dates)) throw new EventConflictError('Another event is reserving a time; retry shortly'); try { const check = { cardId: card.id, type: 'manual-calendar-blocker', requestedDate: date, requestedTime: time, timeZone: input.timeZone || policy.timeZone } as GuestIntakeJob; const slots = await guestEventSlots(client, check, policy, 1).catch(error => { throw new EventInputError((error as Error).message); }); @@ -1022,7 +1026,7 @@ async function explicitManualTransition(client: DynamoDBDocumentClient, transiti // Normalize the explicit instant to the persisted policy zone without moving it. const parts = Object.fromEntries(new Intl.DateTimeFormat('en-GB', { timeZone: policy.timeZone, year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', hourCycle: 'h23' }).formatToParts(new Date(slots[0].startIso)).map(p => [p.type,p.value])); return await runTransition(client, transition, targetId, { ...input, date: `${parts.year}-${parts.month}-${parts.day}`, time: `${parts.hour}:${parts.minute}`, window: undefined, timeZone: policy.timeZone, manualPolicy: policy }); - } finally { await releaseAllocator(client, owner); } + } finally { await releaseAllocator(client, owner, dates); } } export async function proposeEvent( diff --git a/backend/src/router.ts b/backend/src/router.ts index af9babe4..ed511b25 100644 --- a/backend/src/router.ts +++ b/backend/src/router.ts @@ -1,3 +1,4 @@ +import { OwnerAvailabilityError } from './calendar/assertOwnerAvailable'; import { handleTuitionRoutes } from './routes/tuition'; import { handleAcademyPageviewsRoutes } from './routes/academyPageviews'; import { timingSafeEqual } from 'crypto'; @@ -586,6 +587,7 @@ async function route(event: LambdaEvent, client: DynamoDBDocumentClient): Promis // Anything else — 404 return jsonResponse(404, { error: 'Not found' }); } catch (err: unknown) { + if (err instanceof OwnerAvailabilityError) return jsonResponse(err.statusCode, { error: err.message, code: 'owner_calendar_unavailable_or_conflict' }); if (err instanceof TaskVersionConflictError) { const currentTask = await getTaskConsistent(client, err.taskId); if (!currentTask) { diff --git a/backend/src/routes/calendar.ts b/backend/src/routes/calendar.ts index 1e7861fc..ce301ac1 100644 --- a/backend/src/routes/calendar.ts +++ b/backend/src/routes/calendar.ts @@ -7,9 +7,12 @@ import { builtInHolidayGeneration,holidayMetadata,holidaySnapshot } from '../cal import { persistHolidayGeneration,readHolidayGeneration } from '../db/calendarHolidays'; import { projectCalendarOverlays } from '../calendar/overlays'; import { newsletterCalendarOverlay } from '../calendar/newsletterOverlay'; -import { berlinToday, ownerCalendarOverlay, ownerCalendarRange, fetchDapierConnections, parseDurationMinutes, parseSlotWindow, DEFAULT_CALL_DURATION_MINUTES, type SlotWindow } from '../calendar/ownerCalendarOverlay'; +import { berlinToday, eachDayOfInterval, ownerCalendarOverlay, ownerCalendarRange, fetchDapierConnections, parseDurationMinutes, parseSlotWindow, preferStartFor, DEFAULT_CALL_DURATION_MINUTES, WORKSHOP_DURATION_MINUTES, type SlotWindow } from '../calendar/ownerCalendarOverlay'; import { calendarHoldOverlay, markDuplicateCalendarHolds, suppressHeldSlots, suppressPublicEventSlots } from '../calendar/holdOverlay'; import { listCalendarHolds } from '../db/calendarHolds'; +import { listAllCards } from '../db/cards'; +import { addDays } from '../podcast/recordingSlots'; +import { cardEventInterval } from '../calendar/cardEventTime'; import { json, parseJsonEvent as parse } from '../http'; import { realDate } from '../sponsorCrm/model'; const days=(a:string,b:string)=>(Date.parse(`${b}T00:00:00Z`)-Date.parse(`${a}T00:00:00Z`))/86400000; @@ -25,11 +28,63 @@ export async function handleCalendarRoutes(path:string,method:string,event:Lambd if(method==='PUT'){const body=parse(event);if(!body||typeof body!=='object'||Array.isArray(body))return json(400,{error:'Request body is required'});const settings=await saveCalendarOverlaySettings(client,body,actor(event));return json(200,{settings});} return json(405,{error:'Method not allowed'}); } + if(path==='/api/calendar-items/next-free-day'){ + if(method!=='GET')return json(405,{error:'Method not allowed'}); + const q=event.queryStringParameters||{}; + const type=typeof q.type==='string'&&q.type.trim()?q.type.trim().toLowerCase():undefined; + const today=berlinToday(); + const rawFrom=q.from&&realDate(q.from)?q.from:today; + const from=rawFromto||days(from,to)>366)return json(400,{error:'Invalid or unbounded range'}); + let durationMinutes: number; let slotWindow: SlotWindow; + try{ + slotWindow=parseSlotWindow(q.window); + if(slotWindow==='call')return json(400,{error:"next-free-day supports window 'midday', 'evening', or 'any'"}); + const defaultDuration=type==='workshop'?WORKSHOP_DURATION_MINUTES:undefined; + durationMinutes=parseDurationMinutes(q.duration,defaultDuration); + }catch(e:any){return json(400,{error:String(e?.message||'Invalid duration or window')});} + const overlay=await ownerCalendarOverlay({client,durationMinutes,window:slotWindow}).project(from,to); + if(overlay.connection.state!=='connected')return json(503,{error:overlay.connection.reason||'The authoritative owner calendar is unavailable'}); + const [holds,entities,cards]=await Promise.all([ + listCalendarHolds(client,{from,to,activeOnly:true}), + projectCalendarEntities(client,from,to), + listAllCards(client), + ]); + const withHolds=suppressHeldSlots(overlay.items,holds); + const freeItems=suppressPublicEventSlots(withHolds,entities.map(item=>item.date)); + const overlaps=(a:number,b:number,c:number,d:number)=>ac; + const activeCards=cards.filter(c=>c.status!=='archived'&&c.eventTime); + const windowOrder:('midday'|'evening')[]=slotWindow==='any'?['midday','evening']:[slotWindow]; + const isSlotFreeOnDay=(day:string,w:'midday'|'evening')=>{ + if(!freeItems.some(i=>i.provider==='owner-calendar'&&i.isAvailableSlot&&i.startDate===day&&i.slot===w))return false; + const interval=cardEventInterval(`${day} ${preferStartFor(w,durationMinutes)}`,durationMinutes,'Europe/Berlin'); + const start=Date.parse(interval.startIso),end=Date.parse(interval.endIso); + if(start<=Date.now())return false; + return !activeCards.some(c=>overlaps(start,end,Date.parse(c.eventTime!.startIso),Date.parse(c.eventTime!.endIso))); + }; + const middayTime=preferStartFor('midday',durationMinutes),eveningTime=preferStartFor('evening',durationMinutes); + for(const day of eachDayOfInterval(from,to)){ + const availableWindows=windowOrder.filter(w=>isSlotFreeOnDay(day,w)); + if(!availableWindows.length)continue; + const chosen=availableWindows[0]; + return json(200,{ + found:true,date:day,window:chosen,time:preferStartFor(chosen,durationMinutes),durationMinutes, + ...(type?{type}:{}),from,to,availableWindows, + slots:{midday:{available:availableWindows.includes('midday'),time:middayTime},evening:{available:availableWindows.includes('evening'),time:eveningTime}}, + }); + } + return json(200,{ + found:false,date:null,window:slotWindow,time:null,durationMinutes, + ...(type?{type}:{}),from,to,availableWindows:[], + slots:{midday:{available:false,time:middayTime},evening:{available:false,time:eveningTime}}, + }); + } const r=range(event); if(path==='/api/calendar-items/overlays'){if(method!=='GET')return json(405,{error:'Method not allowed'});if(!r)return json(400,{error:'Invalid or unbounded range'});const q=event.queryStringParameters||{},includeAll=q.all==='true'||q.includeAll==='true'||(q.all!=='false'&&q.includeAll!=='false'&&r.from===r.to); let durationMinutes: number; let slotWindow: SlotWindow; try{slotWindow=parseSlotWindow((q as any).window);durationMinutes=parseDurationMinutes((q as any).duration,slotWindow==='call'?DEFAULT_CALL_DURATION_MINUTES:undefined);}catch(e:any){return json(400,{error:String(e?.message||'Invalid duration or window')});} // Past days get no open slots, so the owner's calendar is read only for a range that reaches today. - const providers=[newsletterCalendarOverlay(client)];if(ownerCalendarRange(r.from,r.to))providers.push(ownerCalendarOverlay({ client, includeAll, durationMinutes, window: slotWindow }));const holds=await listCalendarHolds(client,{from:r.from,to:r.to,activeOnly:true});providers.push(calendarHoldOverlay(holds));const projected=await projectCalendarOverlays(r.from,r.to,providers);const entities=await projectCalendarEntities(client,r.from,r.to);const withHolds=suppressHeldSlots(projected.items,holds);const withPublicEvents=suppressPublicEventSlots(withHolds,entities.map(item=>item.date));const items=markDuplicateCalendarHolds(withPublicEvents,holds,entities);return json(200,{...projected,items,durationMinutes,window:slotWindow});} + const providers=[newsletterCalendarOverlay(client)];if(ownerCalendarRange(r.from,r.to))providers.push(ownerCalendarOverlay({ client, includeAll, durationMinutes, window: slotWindow }));const holds=await listCalendarHolds(client,{from:r.from,to:r.to,activeOnly:true});providers.push(calendarHoldOverlay(holds));const projected=await projectCalendarOverlays(r.from,r.to,providers);if(projected.sources['owner-calendar'] && projected.sources['owner-calendar'].state!=='connected')return json(503,{error:projected.sources['owner-calendar'].reason||'Owner freebusy is unavailable',sources:projected.sources});const entities=await projectCalendarEntities(client,r.from,r.to);const withHolds=suppressHeldSlots(projected.items,holds);const withPublicEvents=suppressPublicEventSlots(withHolds,entities.map(item=>item.date));const items=markDuplicateCalendarHolds(withPublicEvents,holds,entities);return json(200,{...projected,items,durationMinutes,window:slotWindow});} if(path!=='/api/calendar-items')return json(404,{error:'Not found'}); if(method!=='GET')return json(405,{error:'Method not allowed'}); if(!r)return json(400,{error:'Invalid or unbounded range'}); diff --git a/backend/src/routes/cards.ts b/backend/src/routes/cards.ts index 1719c421..2fbb8271 100644 --- a/backend/src/routes/cards.ts +++ b/backend/src/routes/cards.ts @@ -1,6 +1,9 @@ +import { validateGuestAgreement } from '../events/guestAgreement'; +import { berlinParts } from '../events/guestIntakeSlots'; import { getSponsorDocWithAuthMaterial, decryptSponsorDocAccessCode } from '../db/sponsorDocs'; import { GuestInviteValidationError } from '../calendar/guestInvite'; import { getEventRecord } from '../events/store'; +import { rescheduleEvent, EventInputError, EventConflictError } from '../events/service'; import { loadGuestFirstContact } from '../events/guestFirstContact'; import { provenPreSendFailure } from '../events/guestFirstContactDelivery'; import { getTaskConsistent } from '../db/tasks'; @@ -415,12 +418,33 @@ async function handleCardRoutes( if (action === 'retry') { const task = await getTaskConsistent(client, job.taskId); const prior = task?.podcastFirstContact; + if (task?.status === 'done') return json(409, { error: 'Invitation Task is completed; existing delivery must not be replayed' }); if (job.status !== 'failed' || job.retryable !== true || (prior && prior.state !== 'sent' && !provenPreSendFailure(prior.delivery))) return json(409, { error: 'Only a proven safe preparation or pre-send failure can be retried; reconcile uncertain delivery first' }); } + const scheduling = parseObject(rawBody); + const agreedFrom = scheduling.agreedFrom ?? job.agreedFrom; + const agreedTo = scheduling.agreedTo ?? job.agreedTo; + const requestedDate = scheduling.date as string | undefined || card.anchorDate || job.requestedDate; + try { validateGuestAgreement({ agreedFrom: agreedFrom as string, agreedTo: agreedTo as string }, requestedDate); } + catch (error) { return json(422, { error: (error as Error).message }); } + if ((job.leaseUntil || 0) > Date.now()) return json(409, { error: 'Invitation worker is active; retry after its lease' }); const skipEmail = action === 'send' ? false : job.skipEmail; - await client.send(new PutCommand({ TableName: TABLE_ARTIFACTS, Item: { ...guestIntakeKey(job.id), ...job, status: 'queued', skipEmail, updatedAt: new Date().toISOString() }, + // A retry may move the requested slot, so a date the policy rejected is never replayed forever. + let retarget: { requestedDate?: string; requestedTime?: string } = {}; + if (action === 'retry' && rawBody?.trim()) { + let body: Record; + try { body = JSON.parse(rawBody); } catch { return json(400, { error: 'Invalid JSON body' }); } + if (body.date !== undefined || body.time !== undefined) { + if (typeof body.date !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(body.date)) return json(400, { error: 'date must be YYYY-MM-DD' }); + if (body.time !== undefined && (typeof body.time !== 'string' || !/^([01]\d|2[0-3]):[0-5]\d$/.test(body.time))) return json(400, { error: 'time must be HH:MM' }); + if (job.holdId) return json(409, { error: 'This invitation already owns an event; move it with cards time instead' }); + retarget = { requestedDate: body.date, requestedTime: body.time }; + } + } + await client.send(new PutCommand({ TableName: TABLE_ARTIFACTS, Item: { ...guestIntakeKey(job.id), ...job, agreedFrom, agreedTo, requestedDate, ...(card.eventTime ? { requestedTime: berlinParts(card.eventTime.startIso).time, timeZone: 'Europe/Berlin' } : {}), ...retarget, status: 'queued', skipEmail, updatedAt: new Date().toISOString() }, + ConditionExpression: '#s = :prior AND updatedAt = :updated', ExpressionAttributeNames: { '#s': 'status' }, ExpressionAttributeValues: { ':prior': job.status, ':updated': job.updatedAt } })); - const updated = await updateCardAdditive(client, card, c => ({ guestIntake: { ...c.guestIntake!, status: 'queued', skipEmail } })); + const updated = await updateCardAdditive(client, card, c => ({ ...(requestedDate ? { anchorDate: requestedDate } : {}), guestIntake: { ...c.guestIntake!, status: 'queued', skipEmail } })); return json(202, { card: updated, invitation: { status: 'queued', recipient: job.guestEmail, taskId: job.taskId } }); } @@ -1127,6 +1151,30 @@ async function handleCardTime(method: string, id: string, rawBody: string | null } catch (error) { return json(400, { error: error instanceof Error ? error.message : 'Invalid event time' }); } + // A Card whose first invitation owns an Event record moves through the Event lifecycle, so the event, + // the Card anchor and the intake job never drift apart (the Card-invite path knows nothing of the Event). + const linkedEvent = await getEventRecord(client, `hold_${card.id}`); + if (linkedEvent && (linkedEvent.status === 'proposed' || linkedEvent.status === 'approved')) { + try { + const local = Object.fromEntries(new Intl.DateTimeFormat('en-GB', { timeZone: interval.timeZone, year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', hourCycle: 'h23' }) + .formatToParts(new Date(interval.startIso)).map(p => [p.type, p.value])); + const moved = await rescheduleEvent(client, card.id, { date: `${local.year}-${local.month}-${local.day}`, time: `${local.hour}:${local.minute}`, timeZone: interval.timeZone, + durationMinutes: interval.durationMinutes, ...(guests.length ? { guestEmails: guests } : {}), actor: resolved.actor.id }); + const job = card.guestIntake ? await getGuestIntakeJob(client, card.guestIntake.jobId) : null; + // Keep the intake job on the same slot so retry never replays the superseded date. + if (job && job.status !== 'sent') { + await client.send(new PutCommand({ TableName: TABLE_ARTIFACTS, Item: { ...guestIntakeKey(job.id), ...job, requestedDate: `${local.year}-${local.month}-${local.day}`, requestedTime: `${local.hour}:${local.minute}`, + timeZone: interval.timeZone, startIso: moved.event.startIso, updatedAt: new Date().toISOString() } })); + } + const fresh = await getCardConsistent(client, card.id); + return json(moved.sync.state === 'synced' ? 200 : 502, { ...moved, card: await projectCard(new TeamDirectory(client), fresh || moved.card, undefined, await getTemplateIdByType(client)), + movedTasks: 0, ...(moved.sync.state === 'deferred' ? { error: moved.sync.reason } : {}) }); + } catch (error) { + if (error instanceof EventInputError) return json(422, { error: error.message }); + if (error instanceof EventConflictError) return json(409, { error: error.message }); + throw error; + } + } const rescheduling = Boolean( card.eventTime?.startIso && (card.eventTime.startIso !== interval.startIso || card.eventTime.endIso !== interval.endIso), diff --git a/backend/tests/calendar-holds.test.ts b/backend/tests/calendar-holds.test.ts index 98c5cadc..37638568 100644 --- a/backend/tests/calendar-holds.test.ts +++ b/backend/tests/calendar-holds.test.ts @@ -1,3 +1,4 @@ +import { installOwnerAvailabilityFixture } from './helpers/owner-availability'; import { after, before, describe, it } from "node:test"; import assert from "node:assert"; import type { DynamoDBDocumentClient } from "@aws-sdk/lib-dynamodb"; @@ -44,6 +45,7 @@ const parse = (r: any) => JSON.parse(r.body); describe("calendar holds (web parity + tentative proposal + 7d TTL)", () => { let client: DynamoDBDocumentClient; before(async () => { + installOwnerAvailabilityFixture(); const port = await startLocal(); client = await getClient(port); await createTables(client); diff --git a/backend/tests/calendar-invite-sop.test.ts b/backend/tests/calendar-invite-sop.test.ts index 069abd12..19276008 100644 --- a/backend/tests/calendar-invite-sop.test.ts +++ b/backend/tests/calendar-invite-sop.test.ts @@ -1,3 +1,4 @@ +import { installOwnerAvailabilityFixture } from './helpers/owner-availability'; import { after, before, afterEach, describe, it } from 'node:test'; import assert from 'node:assert/strict'; import { PutCommand, type DynamoDBDocumentClient } from '@aws-sdk/lib-dynamodb'; @@ -33,6 +34,7 @@ describe('calendar invite SOP contract', () => { let client: DynamoDBDocumentClient; let checklistFixture: ReturnType; before(async () => { + installOwnerAvailabilityFixture(); checklistFixture = createTaskChecklistFixture(); configureTaskChecklistStore(checklistFixture.store); client = await getClient(await startLocal()); diff --git a/backend/tests/calendar.test.ts b/backend/tests/calendar.test.ts index 39761da8..070a1762 100644 --- a/backend/tests/calendar.test.ts +++ b/backend/tests/calendar.test.ts @@ -1,4 +1,5 @@ -import { after, afterEach, before, describe, it } from "node:test"; +import { withOwnerAvailability, installOwnerAvailabilityFixture } from './helpers/owner-availability'; +import { after, afterEach, before, beforeEach, describe, it } from "node:test"; import assert from "node:assert"; import fs from "fs/promises"; import path from "path"; @@ -28,7 +29,7 @@ import { createTemplate } from "../src/db/templates"; import { createPodcastEpisode } from "../src/db/podcastEpisodes"; import { deleteCardCascade } from "../src/db/cardDeletion"; import { saveCalendarOverlaySettings } from "../src/db/calendar"; -import { setOwnerCalendarProviderClientsForTests } from "../src/calendar/ownerCalendarOverlay"; +import { setOwnerCalendarProviderClientsForTests as setOwnerCalendarClients } from "../src/calendar/ownerCalendarOverlay"; const invoke = ( method: string, pathName: string, @@ -50,11 +51,13 @@ const parse = (r: any) => JSON.parse(r.body); describe("operations calendar", () => { let client: DynamoDBDocumentClient; before(async () => { + installOwnerAvailabilityFixture(); const port = await startLocal(); client = await getClient(port); await createTables(client); }); after(stopLocal); + beforeEach(installOwnerAvailabilityFixture); afterEach(() => { process.env.SKIP_AUTH = "true"; }); @@ -442,3 +445,5 @@ describe("operations calendar", () => { assert.equal(preserved.callBufferAfterMinutes, 10); }); }); + +function setOwnerCalendarProviderClientsForTests(value: Parameters[0]) { setOwnerCalendarClients({ ...value, ...(value.fetch ? { fetch: withOwnerAvailability(value.fetch) } : {}) }); } diff --git a/backend/tests/card-calendar-invites.test.ts b/backend/tests/card-calendar-invites.test.ts index 97638e01..b71d8d05 100644 --- a/backend/tests/card-calendar-invites.test.ts +++ b/backend/tests/card-calendar-invites.test.ts @@ -1,3 +1,4 @@ +import { installOwnerAvailabilityFixture } from './helpers/owner-availability'; import { after, before, describe, it } from 'node:test'; import assert from 'node:assert'; import { createHash } from 'node:crypto'; @@ -43,6 +44,7 @@ let client: DynamoDBDocumentClient; describe('Card calendar invites (unlink + stale check + invite-task done-gate + confirm-hold auto-link)', () => { before(async () => { + installOwnerAvailabilityFixture(); const port = await startLocal(); client = await getClient(port); await createTables(client); @@ -107,6 +109,7 @@ describe('Card calendar invites (unlink + stale check + invite-task done-gate + assert.deepStrictEqual(parse(list).invites.map((i: any) => i.eventId), ['evt-a']); const google = holdGoogleProvider(); google.events.set(DTC, new Map([['manual-event', { id: 'manual-event', status: 'confirmed' }]])); + installOwnerAvailabilityFixture(); setCalendarHoldGoogleDepsForTests({ credential: 'test-machine', fetchImpl: google.fetchImpl }); try { const add = await invoke('POST', `/api/cards/${card.id}/calendar-invites`, { @@ -146,6 +149,7 @@ describe('Card calendar invites (unlink + stale check + invite-task done-gate + { eventId: 'kept', calendar: DTC }, ]); const google = holdGoogleProvider(); + installOwnerAvailabilityFixture(); setCalendarHoldGoogleDepsForTests({ credential: 'test-machine', fetchImpl: google.fetchImpl }); try { const removed = await invoke('DELETE', `/api/cards/${card.id}/calendar-invites`, { eventId: 'gone-dtc' }); @@ -195,6 +199,7 @@ describe('Card calendar invites (unlink + stale check + invite-task done-gate + google.events.set(DTC, new Map([['live-dtc', { id: 'live-dtc' }]])); google.events.set('orin@datatalks.club', new Map([['live-org', { id: 'live-org' }]])); await linkInvites(card.id, [{ eventId: 'live-org', calendar: 'orin@datatalks.club' }], ownedTime(card.id, { 'orin@datatalks.club': 'live-org' })); + installOwnerAvailabilityFixture(); setCalendarHoldGoogleDepsForTests({ credential: 'test-machine', fetchImpl: google.fetchImpl }); try { const refused = await invoke('DELETE', `/api/cards/${card.id}/calendar-invites`, { eventId: 'live-org' }); @@ -217,6 +222,7 @@ describe('Card calendar invites (unlink + stale check + invite-task done-gate + for (const calendar of [DTC, PERSONAL]) google.events.set(calendar, new Map([['same-id', { id: 'same-id' }]])); await linkInvites(card.id, [DTC, PERSONAL].map(calendar => ({ calendar, eventId: 'same-id' })), ownedTime(card.id, { [DTC]: 'same-id', [PERSONAL]: 'same-id' })); + installOwnerAvailabilityFixture(); setCalendarHoldGoogleDepsForTests({ credential: 'test-machine', fetchImpl: google.fetchImpl }); try { const res = await invoke('DELETE', `/api/cards/${card.id}/calendar-invites`, { @@ -240,6 +246,7 @@ describe('Card calendar invites (unlink + stale check + invite-task done-gate + const google = holdGoogleProvider(); google.state.failCalendar = DTC; await linkInvites(card.id, [{ eventId: 'x', calendar: DTC }]); + installOwnerAvailabilityFixture(); setCalendarHoldGoogleDepsForTests({ credential: 'test-machine', fetchImpl: google.fetchImpl }); try { const res = await invoke('DELETE', `/api/cards/${card.id}/calendar-invites`, { eventId: 'x', deleteEvent: true }); @@ -259,6 +266,7 @@ describe('Card calendar invites (unlink + stale check + invite-task done-gate + const current = (await getCardConsistent(client, card.id))!; await updateCard(client, card.id, { expectedVersion: current.version, patch: { templateId: template.id } }); const google = holdGoogleProvider(); + installOwnerAvailabilityFixture(); setCalendarHoldGoogleDepsForTests({ credential: 'test-machine', fetchImpl: google.fetchImpl }); try { const res = await invoke('POST', `/api/cards/${card.id}/time`, { at: '2026-11-09 14:30', guestEmails: ['guest@example.test'] }); @@ -282,6 +290,7 @@ describe('Card calendar invites (unlink + stale check + invite-task done-gate + { eventId: 'cancelled', calendar: DTC }, { eventId: 'deleted', calendar: PERSONAL }, ]); + installOwnerAvailabilityFixture(); setCalendarHoldGoogleDepsForTests({ credential: 'test-machine', fetchImpl: google.fetchImpl }); try { const verified = await invoke('GET', `/api/cards/${card.id}/calendar-invites`, undefined, { verify: '1' }); @@ -408,6 +417,7 @@ describe('Card calendar invites (unlink + stale check + invite-task done-gate + it('links the confirmed Google invite to the card automatically', async () => { const card = await createCard('Auto-link card'); const google = holdGoogleProvider(); + installOwnerAvailabilityFixture(); setCalendarHoldGoogleDepsForTests({ credential: 'test-machine', fetchImpl: google.fetchImpl }); try { const created = parse(await invoke('POST', '/api/calendar-holds', { @@ -473,6 +483,7 @@ describe('Card calendar invites (unlink + stale check + invite-task done-gate + }); assert.strictEqual(createdEpisode.statusCode, 201, createdEpisode.body); const google = holdGoogleProvider(); + installOwnerAvailabilityFixture(); setCalendarHoldGoogleDepsForTests({ credential: 'test-machine', fetchImpl: google.fetchImpl }); try { const created = parse(await invoke('POST', '/api/calendar-holds', { @@ -515,6 +526,7 @@ describe('Card calendar invites (unlink + stale check + invite-task done-gate + const card = parse(cardResponse).card; const google = holdGoogleProvider(); + installOwnerAvailabilityFixture(); setCalendarHoldGoogleDepsForTests({ credential: 'test-machine', fetchImpl: google.fetchImpl }); try { const created = parse(await invoke('POST', '/api/calendar-holds', { diff --git a/backend/tests/card-event-time.test.ts b/backend/tests/card-event-time.test.ts index 2cde719f..46a0cd31 100644 --- a/backend/tests/card-event-time.test.ts +++ b/backend/tests/card-event-time.test.ts @@ -1,3 +1,5 @@ +import { installOwnerAvailabilityFixture } from './helpers/owner-availability'; +installOwnerAvailabilityFixture(); import { test } from 'node:test'; import assert from 'node:assert/strict'; import { cardEventInterval } from '../src/calendar/cardEventTime'; @@ -314,6 +316,18 @@ describe('Card-owned invitation lifecycle', () => { assert.equal(third.data.taskClosure.tasks[0].outcome, 'already_closed'); }); + test('cards time repairs a mismatched anchor when setting and moving a synced invite', async () => { + google(); + const c = await card('webinar-anchor-repair'); + const assigned = await invoke('POST', `/api/cards/${c.id}/time`, { at: '2026-11-26 12:30', guestEmails: ['guest@example.test'] }); + assert.equal(assigned.code, 200, assigned.raw); + assert.equal(assigned.data.card.anchorDate, '2026-11-26'); + const moved = await invoke('POST', `/api/cards/${c.id}/time`, { at: '2027-01-11 12:30', guestEmails: ['guest@example.test'] }); + assert.equal(moved.code, 200, moved.raw); + assert.equal(moved.data.card.anchorDate, '2027-01-11'); + assert.equal(moved.data.card.eventTime.startIso, '2027-01-11T11:30:00.000Z'); + }); + test('allows moving or clearing anchorDate and eventTime when eventTime is phantom (no Event record, no live Google invites) without creating invites', async () => { const provider = google(); const c = await card('aishl-workshop'); diff --git a/backend/tests/event-service.test.ts b/backend/tests/event-service.test.ts index f509a9fe..3e2082b7 100644 --- a/backend/tests/event-service.test.ts +++ b/backend/tests/event-service.test.ts @@ -1,3 +1,5 @@ +import { installOwnerAvailabilityFixture } from './helpers/owner-availability'; +installOwnerAvailabilityFixture(); import { after, before, describe, it } from 'node:test'; import assert from 'node:assert/strict'; import type { DynamoDBDocumentClient } from '@aws-sdk/lib-dynamodb'; diff --git a/backend/tests/guest-intake-allocation.test.ts b/backend/tests/guest-intake-allocation.test.ts index 17b037a0..6cb3ff36 100644 --- a/backend/tests/guest-intake-allocation.test.ts +++ b/backend/tests/guest-intake-allocation.test.ts @@ -3,7 +3,7 @@ import { after, before, test } from 'node:test'; import { UpdateCommand, type DynamoDBDocumentClient } from '@aws-sdk/lib-dynamodb'; import { getClient } from '../src/db/client'; import { startLocal, createTables, stopLocal } from '../scripts/local-dynamodb'; -import { claimGuestSlotAllocator } from '../src/events/guestIntakeWorker'; +import { claimGuestSlotAllocator, releaseAllocator } from '../src/events/guestIntakeAllocator'; import { prepareGuestIntake } from '../src/events/guestIntakeCreate'; import { saveGuestIntakeJob } from '../src/events/guestIntakeStore'; import { createCard } from '../src/db/cards'; @@ -16,13 +16,14 @@ after(stopLocal); const template = { id: 'synthetic-template', type: 'podcast', name: 'Podcast', guestIntake: { enabled: true, emailTemplateId: 'podcast.first-contact', formTemplate: 'podcast', followUpDays: 7 } } as Template; test('two concurrent guest Card jobs cannot enter slot read/reservation together', async () => { - const results = await Promise.all(['job-one', 'job-two'].map(id => claimGuestSlotAllocator(db, id))); + const results = await Promise.all(['job-one', 'job-two'].map(id => claimGuestSlotAllocator(db, id, ['2030-12-02']))); assert.equal(results.filter(Boolean).length, 1); const winner = results[0] ? 'job-one' : 'job-two'; const loser = results[0] ? 'job-two' : 'job-one'; - assert.equal(await claimGuestSlotAllocator(db, loser), false, 'loser cannot select the same available slot while winner reserves it'); - await db.send(new UpdateCommand({ TableName: TABLE_ARTIFACTS, Key: { PK: 'GUESTINTAKEALLOCATOR', SK: 'GUESTINTAKEALLOCATOR' }, UpdateExpression: 'SET leaseUntil = :zero', ConditionExpression: 'ownerId = :winner', ExpressionAttributeValues: { ':zero': 0, ':winner': winner } })); - assert.equal(await claimGuestSlotAllocator(db, loser), true, 'next job may refresh authoritative availability only after prior durable proposal'); + assert.equal(await claimGuestSlotAllocator(db, loser, ['2030-12-02']), false, 'loser cannot select the same available slot while winner reserves it'); + assert.equal(await claimGuestSlotAllocator(db, 'unrelated-card', ['2030-12-03']), true, 'an old Card cannot lock unrelated dates'); + await releaseAllocator(db, winner, ['2030-12-02']); + assert.equal(await claimGuestSlotAllocator(db, loser, ['2030-12-02']), true, 'next job may refresh authoritative availability only after prior durable proposal'); }); test('email alone creates enabled guest intake; unapproved and disabled types do not', async () => { diff --git a/backend/tests/guest-intake-worker.test.ts b/backend/tests/guest-intake-worker.test.ts index e55bf720..65f0f729 100644 --- a/backend/tests/guest-intake-worker.test.ts +++ b/backend/tests/guest-intake-worker.test.ts @@ -1,3 +1,4 @@ +import { withOwnerAvailability } from './helpers/owner-availability'; import { rescheduleEvent, approveEvent } from '../src/events/service'; import { configureTaskChecklistStore } from '../src/taskChecklist'; import { createTaskChecklistFixture } from './helpers/task-checklist-fixture'; @@ -10,12 +11,12 @@ import { createTables, startLocal, stopLocal } from '../scripts/local-dynamodb'; import { createTemplate, getTemplate } from '../src/db/templates'; import { getCardConsistent, parkCard, resumeCard } from '../src/db/cards'; import { getTaskConsistent, updateTask, listTasksByCardConsistent } from '../src/db/tasks'; -import { getGuestIntakeJob } from '../src/events/guestIntakeStore'; +import { getGuestIntakeJob, saveGuestIntakeJob } from '../src/events/guestIntakeStore'; import { processGuestIntake, pollGuestIntakeAcceptances } from '../src/events/guestIntakeWorker'; import { getEventRecord } from '../src/events/store'; import { getSponsorDocWithAuthMaterial, updateSponsorDoc, decryptSponsorDocAccessCode } from '../src/db/sponsorDocs'; import { setCalendarHoldGoogleDepsForTests } from '../src/db/calendarHolds'; -import { setOwnerCalendarProviderClientsForTests } from '../src/calendar/ownerCalendarOverlay'; +import { setOwnerCalendarProviderClientsForTests as setOwnerCalendarClients } from '../src/calendar/ownerCalendarOverlay'; import { saveCalendarOverlaySettings } from '../src/db/calendar'; import { setSponsorDocEmailDepsForTests } from '../src/sponsorDocs/emailDelivery'; import { TABLE_USERS, TABLE_ARTIFACTS, TABLE_CARDS } from '../src/db/tableNames'; @@ -55,7 +56,7 @@ async function card(type: 'podcast'|'webinar'|'workshop', extra: Record { + const created = await card('webinar', { skipEmail: true }); + await processGuestIntake(db, created.card.guestIntake.jobId); + const job = (await getGuestIntakeJob(db, created.card.guestIntake.jobId))!; + const event = (await getEventRecord(db, job.holdId!))!; + const moved = new Date(Date.parse(event.startIso) + 7 * 86400000); + const parts = Object.fromEntries(new Intl.DateTimeFormat('en-GB', { timeZone: 'Europe/Berlin', year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', hourCycle: 'h23' }).formatToParts(moved).map(p => [p.type, p.value])); + const res = await invoke('POST', `/api/cards/${created.card.id}/time`, { at: `${parts.year}-${parts.month}-${parts.day} ${parts.hour}:${parts.minute}` }); + assert.equal(res.statusCode, 200, res.body); + const after = (await getEventRecord(db, event.id))!; + assert.equal(after.date, `${parts.year}-${parts.month}-${parts.day}`); + const card2 = (await invoke('GET', `/api/cards/${created.card.id}`)).body; + assert.equal(JSON.parse(card2).card.anchorDate, after.date); + const updated = (await getGuestIntakeJob(db, job.id))!; + assert.equal(updated.requestedDate, after.date); assert.equal(updated.requestedTime, `${parts.hour}:${parts.minute}`); +}); test('acceptance racing Gmail receipt bookkeeping leaves no waiting follow-up', async () => { const created = await card('webinar'); onMailSend = async () => { await approveEvent(db, created.card.id, { actor: 'synthetic-guest-accept', operationKey: 'accept-during-mail-send' }); }; @@ -340,7 +357,7 @@ test('first-contact Card with event hold dates Template Tasks from proposed anch templateId: template.id, guestEmail: 'synthetic-guest@example.test', creationKey: crypto.randomUUID(), - endDate: '2035-06-01', + endDate: '2035-06-01', agreedFrom: '2026-11-25', agreedTo: '2027-12-31', }); assert.equal(createdRes.statusCode, 201, createdRes.body); const createdCard = JSON.parse(createdRes.body).card; @@ -391,3 +408,70 @@ test('first-contact Card with event hold dates Template Tasks from proposed anch assert.equal(eventAfter.version, eventBefore.version); assert.deepEqual(eventAfter.googleEventIds, eventBefore.googleEventIds); }); + +function setOwnerCalendarProviderClientsForTests(value: Parameters[0]) { setOwnerCalendarClients({ ...value, ...(value.fetch ? { fetch: withOwnerAvailability(value.fetch) } : {}) }); } + +test('January agreement bounds automatic selection and rejects an earlier November request without writes', async () => { + const created = await card('podcast', { agreedFrom: '2031-01-01', agreedTo: '2031-01-31', skipEmail: true }); + await processGuestIntake(db, created.card.guestIntake.jobId); + const job = (await getGuestIntakeJob(db, created.card.guestIntake.jobId))!; + assert.ok(job.selectedDate! >= '2031-01-01' && job.selectedDate! <= '2031-01-31'); + const earlier = await card('podcast', { agreedFrom: '2031-01-01', agreedTo: '2031-01-31', skipEmail: true }); + const queued = (await getGuestIntakeJob(db, earlier.card.guestIntake.jobId))!; + queued.requestedDate = '2030-11-26'; + await saveGuestIntakeJob(db, queued); + const before = google.calls.length, beforeMails = mails; + await assert.rejects(processGuestIntake(db, queued.id), /outside the guest agreement/); + assert.equal(google.calls.length, before); assert.equal(mails, beforeMails); +}); + +test('completed invitation never replays a stale November job after its Card moves to January', async () => { + const created = await card('podcast', { skipEmail: true }); + const job = (await getGuestIntakeJob(db, created.card.guestIntake.jobId))!; + job.requestedDate = '2030-11-26'; + await saveGuestIntakeJob(db, job); + const task = (await getTaskConsistent(db, job.taskId))!; + await updateTask(db, task.id, { currentTask: task, expectedVersion: task.version, patch: { status: 'done' } }); + const before = google.calls.length, beforeMails = mails; + await processGuestIntake(db, job.id); + assert.equal(google.calls.length, before); assert.equal(mails, beforeMails); + assert.equal((await getGuestIntakeJob(db, job.id))!.status, job.status); + const retry = await invoke('POST', `/api/cards/${job.cardId}/guest-intake/retry`, {}); + assert.equal(retry.statusCode, 409, retry.body); + assert.match(JSON.parse(retry.body).error, /completed/); +}); + +test('explicit anchorDate on a free Wednesday succeeds even when podcast policy defaults weekdays to Mon/Tue', async () => { + // 2030-12-04 is a Wednesday; podcast guestIntake.weekdays is [1, 2] for auto-pick only. + const created = await card('podcast', { anchorDate: '2030-12-04', skipEmail: true }); + await processGuestIntake(db, created.card.guestIntake.jobId); + const job = (await getGuestIntakeJob(db, created.card.guestIntake.jobId))!; + assert.equal(job.status, 'skipped'); + assert.equal(job.selectedDate, '2030-12-04'); + const event = (await getEventRecord(db, job.holdId!))!; + assert.equal(event.date, '2030-12-04'); +}); + +test('GET /api/calendar-items/next-free-day honors all-day summit blockers and returns the nearest free day', async () => { + ownerEvents = [ + { id: 'evt-summit', summary: 'AI Coding Summit Berlin', transparency: 'transparent', start: { date: '2030-12-02' }, end: { date: '2030-12-03' } }, + ]; + try { + const res = await handler({ + httpMethod: 'GET', + path: '/api/calendar-items/next-free-day', + headers: { 'x-user-id': 'synthetic-actor' }, + body: null, + queryStringParameters: { type: 'podcast', window: 'midday', from: '2030-12-02', to: '2030-12-06' }, + }); + assert.equal(res.statusCode, 200, res.body); + const body = JSON.parse(res.body); + assert.equal(body.found, true); + assert.equal(body.date, '2030-12-03'); + assert.equal(body.window, 'midday'); + assert.equal(body.time, '12:30'); + assert.equal(body.durationMinutes, 60); + } finally { + ownerEvents = []; + } +}); diff --git a/backend/tests/guest-invite-builder.test.ts b/backend/tests/guest-invite-builder.test.ts index 48df65f9..58682027 100644 --- a/backend/tests/guest-invite-builder.test.ts +++ b/backend/tests/guest-invite-builder.test.ts @@ -1,3 +1,4 @@ +import { installOwnerAvailabilityFixture } from './helpers/owner-availability'; import { after, before, describe, it } from 'node:test'; import assert from 'node:assert/strict'; import type { DynamoDBDocumentClient } from '@aws-sdk/lib-dynamodb'; @@ -65,6 +66,7 @@ async function podcastCard(title = 'Podcast conversation with Julien Khaleghy') describe('shared podcast guest-invite builder (Hub intake 0d56721e)', () => { before(async () => { + installOwnerAvailabilityFixture(); checklist = createTaskChecklistFixture(); configureTaskChecklistStore(checklist.store); const port = await startLocal(); diff --git a/backend/tests/helpers/owner-availability.ts b/backend/tests/helpers/owner-availability.ts new file mode 100644 index 00000000..5dcba03a --- /dev/null +++ b/backend/tests/helpers/owner-availability.ts @@ -0,0 +1,17 @@ +import { setOwnerCalendarProviderClientsForTests } from '../../src/calendar/ownerCalendarOverlay'; +import { DAPIER_AGENT } from '../../src/calendar/dapierBroker'; +import { OWNER_PERSONAL_CALENDAR } from '../../src/identity/operatingIdentities'; +/** Protocol fixture for the owner account; event responses remain owned by each scenario. */ +export function withOwnerAvailability(run: typeof fetch, discovery = true): typeof fetch { + return async (input, init) => { + const url = String(input); + if (discovery && url.endsWith('/api/agent/connections')) return Response.json({ connections: [{ connection_id: 'owner-calendar-test', provider: 'google', agent: DAPIER_AGENT, status: 'connected', operations: ['use'], verified_account_id: OWNER_PERSONAL_CALENDAR, granted_scopes: ['https://www.googleapis.com/auth/calendar'] }] }); + if (url.endsWith('/calendars/primary')) return Response.json({ id: OWNER_PERSONAL_CALENDAR }); + if (url.includes('/users/me/calendarList')) return Response.json({ items: [{ id: OWNER_PERSONAL_CALENDAR }] }); + if (url.endsWith('/freeBusy')) return Response.json({ calendars: { [OWNER_PERSONAL_CALENDAR]: { busy: [] } } }); + return run(input, init); + }; +} +export function installOwnerAvailabilityFixture() { + setOwnerCalendarProviderClientsForTests({ readSecret: async () => 'synthetic', fetch: withOwnerAvailability(async input => Response.json(String(input).endsWith('/api/agent/token') ? { access_token: 'synthetic' } : { items: [] })) }); +} diff --git a/backend/tests/hold-google-copies.test.ts b/backend/tests/hold-google-copies.test.ts index c0f14998..bfc5c203 100644 --- a/backend/tests/hold-google-copies.test.ts +++ b/backend/tests/hold-google-copies.test.ts @@ -1,3 +1,5 @@ +import { installOwnerAvailabilityFixture } from './helpers/owner-availability'; +installOwnerAvailabilityFixture(); import { describe, it } from 'node:test'; import assert from 'node:assert/strict'; import { createHash } from 'node:crypto'; diff --git a/backend/tests/hold-google-errors.test.ts b/backend/tests/hold-google-errors.test.ts index 3fc745fb..ac295b10 100644 --- a/backend/tests/hold-google-errors.test.ts +++ b/backend/tests/hold-google-errors.test.ts @@ -1,3 +1,5 @@ +import { installOwnerAvailabilityFixture } from './helpers/owner-availability'; +installOwnerAvailabilityFixture(); import { describe, it } from 'node:test'; import assert from 'node:assert/strict'; import { createHash } from 'node:crypto'; diff --git a/backend/tests/owner-availability.test.ts b/backend/tests/owner-availability.test.ts new file mode 100644 index 00000000..e29cdec9 --- /dev/null +++ b/backend/tests/owner-availability.test.ts @@ -0,0 +1,91 @@ +import { createHoldGoogleEvents, HOLD_ORGANIZER } from '../src/calendar/holdGoogleSync'; +import { afterEach, test } from 'node:test'; +import assert from 'node:assert/strict'; +import { readOwnerAvailability, isSoftEvent } from '../src/calendar/ownerAvailability'; +import { ownerCalendarOverlay, setOwnerCalendarProviderClientsForTests } from '../src/calendar/ownerCalendarOverlay'; +import { assertOwnerAvailable } from '../src/calendar/assertOwnerAvailable'; + +import { guestEventSlots } from '../src/events/guestIntakeSlots'; +import { prepareGuestIntake } from '../src/events/guestIntakeCreate'; +import { OWNER_PERSONAL_CALENDAR as OWNER } from '../src/identity/operatingIdentities'; +import { DAPIER_AGENT } from '../src/calendar/dapierBroker'; +import type { GuestIntakeJob } from '../src/events/guestIntakeStore'; +import type { EventPolicy } from '../src/events/policy'; +import type { Template } from '../src/types'; + +const lunch = { id: 'lunch', summary: 'Lunch', start: { dateTime: '2026-11-26T12:00:00+01:00' }, end: { dateTime: '2026-11-26T13:00:00+01:00' } }; +function fixture(events: Record, options: { timeout?: boolean; freebusy?: any; paginate?: boolean } = {}) { + const calls: string[] = []; + const run: typeof fetch = async (input, init) => { + const url = new URL(String(input)); calls.push(`${init?.method || 'GET'} ${url.pathname}`); + if (url.pathname.endsWith('/api/agent/connections')) return Response.json({ connections: [{ connection_id: 'owner', verified_account_id: OWNER, provider: 'google', status: 'connected', agent: DAPIER_AGENT, operations: ['use'], granted_scopes: ['https://www.googleapis.com/auth/calendar'] }] }); + if (url.pathname.endsWith('/api/agent/token')) return Response.json({ access_token: 'synthetic' }); + if (url.pathname.endsWith('/calendars/primary')) return Response.json({ id: OWNER }); + if (url.pathname.endsWith('/users/me/calendarList')) { + if (options.paginate && !url.searchParams.has('pageToken')) return Response.json({ items: [{ id: OWNER }], nextPageToken: 'next' }); + return Response.json({ items: Object.keys(events).map(id => ({ id })) }); + } + if (url.pathname.endsWith('/freeBusy')) { + if (options.timeout) throw new DOMException('Timed out', 'TimeoutError'); + return Response.json(options.freebusy || { calendars: Object.fromEntries([OWNER, ...Object.keys(events)].map(id => [id, { busy: [] }])) }); + } + const id = decodeURIComponent(url.pathname.match(/\/calendars\/([^/]+)\/events/)?.[1] || ''); + if (id) return Response.json({ items: events[id] || [] }); + throw new Error(`Unexpected calendar write ${init?.method} ${url.pathname}`); + }; + setOwnerCalendarProviderClientsForTests({ readSecret: async () => 'synthetic', fetch: run }); + return { run, calls }; +} +afterEach(() => setOwnerCalendarProviderClientsForTests({})); + +test('named lunch on a second owner calendar blocks 12:25 booking and midday listing; bare Lunch alone is soft', async () => { + const realLunch = { ...lunch, id: 'meeting', summary: 'Lunch with Guest' }; + fixture({ [OWNER]: [lunch], secondary: [realLunch] }, { paginate: true }); + const slots = await ownerCalendarOverlay({ today: '2026-11-24' }).project('2026-11-26','2026-11-26'); + assert.equal(slots.connection.state, 'connected'); assert.equal(slots.items.length, 0); + await assert.rejects(assertOwnerAvailable(undefined, '2026-11-26T11:25:00Z', '2026-11-26T12:30:00Z'), /owner calendar conflict.*Lunch with Guest/); + fixture({ [OWNER]: [lunch] }, { freebusy: { calendars: { [OWNER]: { busy: [{ start: lunch.start.dateTime, end: lunch.end.dateTime }] } } } }); + const available = await ownerCalendarOverlay({ today: '2026-11-24' }).project('2026-11-26','2026-11-26'); + assert.ok(available.items.some(i => i.isAvailableSlot)); + await assertOwnerAvailable(undefined, '2026-11-26T11:25:00Z', '2026-11-26T12:30:00Z'); + assert.equal(isSoftEvent({ summary: 'Morning no' }), false); + assert.equal(isSoftEvent({ summary: 'No' }), false); +}); + +test('transparent all-day summit closes December 3 in both listing and booking', async () => { + fixture({ [OWNER]: [{ id: 'summit', summary: 'Summit', transparency: 'transparent', start: { date: '2026-12-03' }, end: { date: '2026-12-04' } }] }); + const slots = await ownerCalendarOverlay().project('2026-12-03','2026-12-03'); + assert.equal(slots.items.length, 0); + const day = await ownerCalendarOverlay({ includeAll: true }).project('2026-12-03','2026-12-03'); + assert.equal(day.items[0].slot, 'all-day'); + await assert.rejects(assertOwnerAvailable(undefined, '2026-12-03T11:25:00Z', '2026-12-03T12:30:00Z'), /Summit/); +}); + +test('booking refreshes freebusy after an earlier free listing; conflict sends no write', async () => { + fixture({ [OWNER]: [] }); + assert.ok((await ownerCalendarOverlay().project('2026-11-26','2026-11-26')).items.length); + const { calls } = fixture({ [OWNER]: [{ ...lunch, summary: 'New meeting' }] }); + const writerCalls: string[] = []; + await assert.rejects(createHoldGoogleEvents({ eventKey: 'synthetic', summary: 'Guest', description: '', startIso: '2026-11-26T11:25:00Z', endIso: '2026-11-26T12:30:00Z', timeZone: 'Europe/Berlin' }, { credential: 'synthetic', connectionId: 'organizer', fetchImpl: async (input, init) => { + writerCalls.push(`${init?.method || 'GET'} ${String(input)}`); + return Response.json(String(input).endsWith('/api/agent/token') ? { access_token: 'writer' } : { id: HOLD_ORGANIZER }); + } }), /Cannot book/); + assert.equal(writerCalls.length, 2, 'only token and organizer identity reads; no event write'); + assert.ok(!calls.some(c => /^(POST|PATCH|DELETE).*\/events/.test(c))); +}); + +test('unknown freebusy, timeout and per-calendar errors fail closed; an own invite is excluded only by calendar and id', async () => { + fixture({ [OWNER]: [] }, { timeout: true }); + await assert.rejects(assertOwnerAvailable(undefined, '2026-11-26T11:25:00Z', '2026-11-26T12:30:00Z'), /freebusy unavailable/); + let f = fixture({ [OWNER]: [] }, { freebusy: { calendars: { [OWNER]: { errors: [{ reason: 'forbidden' }] } } } }); + await assert.rejects(readOwnerAvailability(f.run,'synthetic','2026-11-26','2026-11-26'), /incomplete/); + fixture({ [OWNER]: [] }, { freebusy: { calendars: { [OWNER]: { busy: [{ start: '2026-11-26T11:00:00Z', end: '2026-11-26T12:00:00Z' }] } } } }); + await assert.rejects(assertOwnerAvailable(undefined, '2026-11-26T11:25:00Z', '2026-11-26T12:30:00Z'), /Busy \(freebusy\)/); + fixture({ [OWNER]: [{ ...lunch, summary: 'Own invite' }] }); + await assertOwnerAvailable(undefined, '2026-11-26T11:25:00Z', '2026-11-26T12:30:00Z', { [OWNER]: 'lunch' }); +}); + +test('missing agreement and November selection outside a January agreement fail before any data/calendar access', async () => { + await assert.rejects(guestEventSlots({} as any, { policy: { enabled: true } } as GuestIntakeJob, {} as EventPolicy), /Record the guest agreement/); + await assert.rejects(guestEventSlots({} as any, { policy: { enabled: true }, requestedDate: '2026-11-26', agreedFrom: '2027-01-01', agreedTo: '2027-01-31' } as GuestIntakeJob, {} as EventPolicy), /outside the guest agreement/); +}); diff --git a/backend/tests/owner-calendar-overlay.test.ts b/backend/tests/owner-calendar-overlay.test.ts index 72ae63e7..a9120e3a 100644 --- a/backend/tests/owner-calendar-overlay.test.ts +++ b/backend/tests/owner-calendar-overlay.test.ts @@ -1,9 +1,10 @@ +import { withOwnerAvailability } from './helpers/owner-availability'; import { describe, it } from 'node:test'; import assert from 'node:assert/strict'; import { ownerCalendarOverlay, determineSlotType, - setOwnerCalendarProviderClientsForTests, + setOwnerCalendarProviderClientsForTests as setOwnerCalendarClients, shouldFilterOwnerCalendarEvent, ownerCalendarRange, openCallStarts, @@ -14,7 +15,7 @@ import { DEFAULT_CALENDAR_OVERLAY_SETTINGS as UNSELECTED_CALENDAR_SETTINGS } fro // Every fixture range starts on or after this day, so none of it is clipped as past. const TODAY = '2026-10-01'; const DEFAULT_CALENDAR_OVERLAY_SETTINGS = { ...UNSELECTED_CALENDAR_SETTINGS, connectionId: 'google-calendar' }; -const selectedOwnerCalendarOverlay = (config: Parameters[0]) => ownerCalendarOverlay({ settings: DEFAULT_CALENDAR_OVERLAY_SETTINGS, ...config }); +const selectedOwnerCalendarOverlay = (config: Parameters[0]) => ownerCalendarOverlay({ settings: DEFAULT_CALENDAR_OVERLAY_SETTINGS, connectionId: config?.settings?.connectionId || 'google-calendar', ...config }); describe('owner calendar overlay and filtering', () => { @@ -296,12 +297,12 @@ describe('owner calendar overlay and filtering', () => { let calls = 0; setOwnerCalendarProviderClientsForTests({ fetch: async () => { calls += 1; return new Response('', { status: 403 }); } }); const missing = await ownerCalendarOverlay({ today: TODAY, brokerCredential: 'machine' }).project(TODAY, TODAY); - assert.equal(missing.connection?.state, 'not-configured'); - assert.match(missing.connection?.reason || '', /No Dapier calendar connection selected/); - assert.equal(calls, 0); + assert.equal(missing.connection?.state, 'unavailable'); + assert.match(missing.connection?.reason || '', /grant|machine credential/); + assert.equal(calls, 1); const denied = await selectedOwnerCalendarOverlay({ today: TODAY, brokerCredential: 'machine' }).project(TODAY, TODAY); assert.match(denied.connection?.reason || '', /grant.*personal-scheduler.*`use`/); - assert.equal(calls, 1); + assert.equal(calls, 2); }); it('discovers Dapier calendar connections using token', async () => { @@ -395,8 +396,8 @@ describe('owner calendar overlay and filtering', () => { const { items } = await provider.project('2026-10-01', '2026-10-31'); assert.equal(requestedConnectionId, 'work-calendar'); assert.equal(items.length, 1); - assert.equal(items[0].id, 'owner-calendar:evt-custom-1'); - assert.equal(items[0].label, '12:00–13:00 Lunch'); + assert.equal(items[0].id, 'owner-calendar:alexey.s.grigoriev@gmail.com:evt-custom-2'); + assert.match(items[0].label, /Secret Project/); }); }); @@ -534,10 +535,10 @@ describe('owner calendar overlay and filtering', () => { const { items } = await provider.project('2026-10-01', '2026-10-31'); - assert.equal(items.length, 3); + assert.equal(items.length, 4); // Event 1: Podcast (timed) - assert.equal(items[0].id, 'owner-calendar:evt-1'); + assert.equal(items[0].id, 'owner-calendar:alexey.s.grigoriev@gmail.com:evt-1'); assert.equal(items[0].startDate, '2026-10-13'); assert.equal(items[0].endDate, '2026-10-13'); assert.equal(items[0].label, '12:25–13:30 Tejas at DataTalks.Club Podcast'); @@ -546,18 +547,19 @@ describe('owner calendar overlay and filtering', () => { assert.equal(items[0].href, 'https://calendar.google.com/event?eid=evt1'); // Event 2: "No" (unavailability block, kept!) - assert.equal(items[1].id, 'owner-calendar:evt-3'); + assert.equal(items[1].id, 'owner-calendar:alexey.s.grigoriev@gmail.com:evt-3'); assert.equal(items[1].startDate, '2026-10-13'); assert.equal(items[1].label, '14:00–18:00 No'); assert.equal(items[1].category, 'Alexey'); // Event 3: Flight (all-day adjusted end date) - assert.equal(items[2].id, 'owner-calendar:evt-5'); - assert.equal(items[2].startDate, '2026-10-17'); - assert.equal(items[2].endDate, '2026-10-17'); - assert.equal(items[2].label, 'Flight to Helsinki'); + assert.equal(items[2].id, 'owner-calendar:alexey.s.grigoriev@gmail.com:evt-4'); + assert.equal(items[3].id, 'owner-calendar:alexey.s.grigoriev@gmail.com:evt-5'); + assert.equal(items[3].startDate, '2026-10-17'); + assert.equal(items[3].endDate, '2026-10-17'); + assert.equal(items[3].label, 'Flight to Helsinki'); assert.equal(items[2].category, 'Alexey'); - assert.equal(items[2].slot, 'all-day'); + assert.equal(items[3].slot, 'all-day'); assert.equal(items[2].isSlotEvent, true); }); @@ -744,10 +746,10 @@ describe('owner calendar overlay and filtering', () => { }); const { items: allItems } = await allProvider.project('2026-10-13', '2026-10-13'); assert.equal(allItems.length, 2); - assert.equal(allItems[0].id, 'owner-calendar:evt-morning'); + assert.equal(allItems[0].id, 'owner-calendar:alexey.s.grigoriev@gmail.com:evt-morning'); assert.equal(allItems[0].slot, 'outside'); assert.equal(allItems[0].isSlotEvent, false); - assert.equal(allItems[1].id, 'owner-calendar:evt-midday'); + assert.equal(allItems[1].id, 'owner-calendar:alexey.s.grigoriev@gmail.com:evt-midday'); assert.equal(allItems[1].slot, 'midday'); assert.equal(allItems[1].isSlotEvent, true); }); @@ -777,7 +779,7 @@ describe('owner calendar overlay and filtering', () => { const { items } = await provider.project('2026-10-12', '2026-10-18'); assert.deepEqual([...new Set(items.map((item) => item.startDate))], ['2026-10-14', '2026-10-15', '2026-10-16']); const googleUrl = new URL(urls.find((url) => url.includes('googleapis.com'))!); - assert.equal(googleUrl.searchParams.get('timeMin'), '2026-10-14T00:00:00Z'); + assert.equal(googleUrl.searchParams.get('timeMin'), '2026-10-13T00:00:00.000Z'); urls.length = 0; const past = await provider.project('2026-09-28', '2026-10-04'); @@ -1015,3 +1017,5 @@ describe('owner calendar overlay and filtering', () => { }); }); }); + +function setOwnerCalendarProviderClientsForTests(value: Parameters[0]) { setOwnerCalendarClients({ ...value, ...(value.fetch ? { fetch: withOwnerAvailability(value.fetch, false) } : {}) }); } diff --git a/backend/tests/podcast-episodes.test.ts b/backend/tests/podcast-episodes.test.ts index 78bfc1f4..7afd8b9d 100644 --- a/backend/tests/podcast-episodes.test.ts +++ b/backend/tests/podcast-episodes.test.ts @@ -1,3 +1,4 @@ +import { withOwnerAvailability } from './helpers/owner-availability'; import { before, after, describe, it } from "node:test"; import assert from "node:assert"; import { PutCommand, ScanCommand } from "@aws-sdk/lib-dynamodb"; @@ -480,3 +481,5 @@ describe("podcast episodes", () => { }); }); + +function setOwnerCalendarProviderClientsForTests(value: Parameters[0]) { setOwnerCalendarClients({ ...value, ...(value.fetch ? { fetch: withOwnerAvailability(value.fetch) } : {}) }); } diff --git a/cli/skill/SKILL.md b/cli/skill/SKILL.md index d64e082b..be30aaf6 100644 --- a/cli/skill/SKILL.md +++ b/cli/skill/SKILL.md @@ -343,8 +343,23 @@ dataops cards invitation CARD_ID # actual status, Task and Gmail dataops cards invitation CARD_ID --preview # read-only rendered email dataops cards invitation CARD_ID --send # first invitation only, after skip dataops cards invitation CARD_ID --retry-pre-send # guarded, proven safe recovery +dataops cards invitation CARD_ID --retry-pre-send --date D [--time HH:MM] # failed before any event: retry on a new slot ``` +Moving a guest event: `dataops cards time CARD_ID --at "YYYY-MM-DD HH:MM"` on a Card +that owns an event reschedules that event, the Card anchor date and the intake +job together, so `--retry-pre-send` never replays the superseded slot. Never +delete invites or events to realign them. + +Assigning a day is confirm-first: `dataops cards create ... --guest-email E --date D` +prints what that day holds and refuses until you pass `--confirm-day`; a day with +no free window is refused unless `--allow-busy-day`. To find the nearest free day +programmatically, call `dataops calendar next-free-day --type podcast --window midday --json` +(or `GET /api/calendar-items/next-free-day`). To check a day without +creating anything, use `dataops calendar day D --json` (`slots.midday.available`, +`slots.evening.available`, `slots.blockers`, `timeline`), which lists only items +that actually cover that date. + `--send` sends both email and the proposed calendar invite, only for a previously skipped first invitation. The worker normally resumes eligible failures; `--retry-pre-send` does not permit ambiguous delivery or resend. A queued, diff --git a/cli/src/cli.mjs b/cli/src/cli.mjs index 410124c7..fef8df94 100644 --- a/cli/src/cli.mjs +++ b/cli/src/cli.mjs @@ -117,6 +117,7 @@ export const FAMILIES = { list: calendar.list, day: calendar.day, slots: calendar.slots, + "next-free-day": calendar.nextFreeDay, propose: calendar.propose, "confirm-hold": calendar.confirmHold, "link-hold": calendar.linkHold, diff --git a/cli/src/commands/calendar.mjs b/cli/src/commands/calendar.mjs index eeef323e..781a91ad 100644 --- a/cli/src/commands/calendar.mjs +++ b/cli/src/commands/calendar.mjs @@ -18,6 +18,7 @@ Usage dataops calendar list [--from YYYY-MM-DD] [--to YYYY-MM-DD] [--type KIND] dataops calendar day [--duration MINUTES] [--window evening|midday|any] dataops calendar slots [--from YYYY-MM-DD] [--to YYYY-MM-DD] [--all] [--duration MINUTES] [--window evening|midday|any|call] + dataops calendar next-free-day [--type podcast|webinar|workshop] [--window midday|evening|any] [--duration MINUTES] [--from YYYY-MM-DD] [--to YYYY-MM-DD] dataops calendar propose --date D --window evening|midday --duration N --title T --topic TOPIC [--guest-ref EMAIL] [--document-url URL] [--card ID] [--expires-days 7] dataops calendar link-hold --card CARD_ID [--apply] [--expected-card-version N --expected-hold-version N --expected-episode-version N] dataops calendar confirm-hold [--guest-ref EMAIL] [--document-url URL] @@ -310,7 +311,11 @@ export async function day(args, io) { api.get(`/api/calendar-items?from=${dateIso}&to=${dateIso}`), ]); - const overlayItems = overlayResult.items || []; + // The provider range is padded across time zones, so an adjacent day's all-day + // event can come back; keep only items that actually cover this date. + const overlayItems = (overlayResult.items || []).filter( + (o) => !o.startDate || (o.startDate <= dateIso && (o.endDate || o.startDate) >= dateIso), + ); const events = (calendarResult.items || []).filter((item) => item.date === dateIso); const holidays = (calendarResult.holidays || []).filter( (h) => h.startDate <= dateIso && h.endDate >= dateIso, @@ -319,20 +324,22 @@ export async function day(args, io) { const calendarHolds = overlayItems.filter((o) => o.provider === "calendar-holds"); const blockers = ownerCalendarItems.filter( - (e) => e.slot === "all-day" || /vacation|holiday|flight|conference|trip/i.test(e.label), + (e) => e.slot === "all-day" || /vacation|holiday|flight|conference|trip|summit/i.test(e.label), ); const timedOwnerItems = ownerCalendarItems.filter((e) => !blockers.includes(e)); const occupancyItems = [...timedOwnerItems, ...calendarHolds]; const middayBusy = busyIntervalsForDay(occupancyItems, "midday"); const eveningBusy = busyIntervalsForDay(occupancyItems, "evening"); const publicEventBusy = events.length > 0; - const isMiddayAvailable = blockers.length === 0 && !publicEventBusy && isWindowFreeForDuration("midday", middayBusy, durationMinutes); - const isEveningAvailable = blockers.length === 0 && !publicEventBusy && isWindowFreeForDuration("evening", eveningBusy, durationMinutes); + const dow = new Date(`${dateIso}T12:00:00Z`).getUTCDay(); + const isWeekend = dow === 0 || dow === 6; + const isMiddayAvailable = !isWeekend && blockers.length === 0 && !publicEventBusy && isWindowFreeForDuration("midday", middayBusy, durationMinutes); + const isEveningAvailable = !isWeekend && blockers.length === 0 && !publicEventBusy && isWindowFreeForDuration("evening", eveningBusy, durationMinutes); const middayEvents = timedOwnerItems.filter((e) => e.slot === "midday"); const eveningEvents = timedOwnerItems.filter((e) => e.slot === "evening"); const middayHolds = calendarHolds.filter((e) => e.slot === "midday"); const eveningHolds = calendarHolds.filter((e) => e.slot === "evening"); - const publicEventConflicts = events.map((event) => event.title); + const publicEventConflicts = [...(isWeekend ? ["Weekend"] : []), ...events.map((event) => event.title)]; // Build unified timeline const timeline = []; @@ -955,3 +962,29 @@ export async function linkHold(args, io) { if (!args.json) io.print(JSON.stringify(result, null, 2)); return result; } + +/** + * Find the nearest free day honoring owner calendar blockers, holds, and events. + */ +export async function nextFreeDay(args, io) { + const window = parseSlotWindow(args.window); + if (window === "call") throw new UsageError("next-free-day supports --window midday, evening, or any."); + const type = args.type ? String(args.type).trim().toLowerCase() : undefined; + const durationMinutes = args.duration !== undefined + ? parseDurationMinutes(args.duration) + : type === "workshop" + ? 90 + : DEFAULT_SLOT_DURATION_MINUTES; + const query = new URLSearchParams({ window, duration: String(durationMinutes) }); + if (type) query.set("type", type); + if (args.from) query.set("from", String(args.from)); + if (args.to) query.set("to", String(args.to)); + const result = await client(args).get(`/api/calendar-items/next-free-day?${query}`); + if (args.json) return result; + if (result.found) { + io.print(`Next free day: ${result.date} (${result.window} ${result.time}, ${result.durationMinutes} min)`); + } else { + io.print(`No free day found between ${result.from} and ${result.to} (${result.window}, ${result.durationMinutes} min).`); + } + return result; +} diff --git a/cli/src/commands/cards.mjs b/cli/src/commands/cards.mjs index 0c12636c..d6f87109 100644 --- a/cli/src/commands/cards.mjs +++ b/cli/src/commands/cards.mjs @@ -5,6 +5,7 @@ import { calendarLabel, enc, fields, integer, isoDate, linkedCardLabel, list as import { apiFor } from "../session.mjs"; import { create as createSponsorDoc } from "./sponsorDocs.mjs"; import { findTemplate } from "./templates.mjs"; +import { day as calendarDay } from "./calendar.mjs"; export const summary = "List, inspect, create (from a Template), and move Cards"; @@ -26,14 +27,15 @@ Usage dataops cards create --template ID|TYPE|NAME [--date YYYY-MM-DD] [--title T] [--end-date YYYY-MM-DD] [--optional-groups a,b] [--count FIELD=N,...] [--stage S] [--description D] [--owner ID] [--tags a,b] [--sponsored true|false] [--guest-email EMAIL] [--guest-person ID | --guest-contact ID] [--guest-name NAME] [--topic TOPIC] [--time HH:MM] [--time-zone IANA_ZONE] - [--guest-time-zone IANA_ZONE] [--window WINDOW] [--skip-email] [--key KEY] + [--guest-time-zone IANA_ZONE] [--window WINDOW] [--agreed-from DATE --agreed-to DATE] [--skip-email] [--key KEY] Podcast, webinar and workshop guest Cards send email - and a [Proposed] calendar invite automatically. Date, title, name and topic are optional. + and a [Proposed] calendar invite automatically. Record the guest agreement with --agreed-from/--agreed-to. + No booking is made without that date/window. --skip-email prepares its event and form without contacting the guest. Reuse --key for a safe retry. --sponsored marks the event as sponsored (a deal flag; the format and its documents stay unchanged). - dataops cards invitation [--preview | --send | --retry-pre-send] [--json] + dataops cards invitation [--preview | --send | --retry-pre-send [--date D [--time HH:MM]]] [--json] Read first-invitation status; --preview renders without sending. --send sends email AND a [Proposed] calendar invite only for a previously skipped first invitation; never a resend. @@ -263,6 +265,8 @@ export async function create(args, io) { } const window = optionalString(args, "window"); if (window !== undefined) body.window = window; + if (args.agreedFrom !== undefined) body.agreedFrom = isoDate(args.agreedFrom, 'agreed-from'); + if (args.agreedTo !== undefined) body.agreedTo = isoDate(args.agreedTo, 'agreed-to'); const endDate = optionalString(args, "endDate"); if (endDate !== undefined) body.endDate = isoDate(endDate, "end-date"); const title = optionalString(args, "title"); @@ -284,6 +288,7 @@ export async function create(args, io) { } body.sponsored = args.sponsored === true || args.sponsored === "true"; } + if (hasGuest && body.anchorDate && !body.time) await confirmGuestDay(args, io, body); const result = await api.post("/api/cards", body); if (args.json) return result; io.print(`Created Card ${result.card.id} - ${result.card.title} (${result.tasks?.length ?? 0} Tasks).`); @@ -297,6 +302,30 @@ export async function create(args, io) { return result; } +/** Confirm-first assignment: show what the day holds and refuse a day without a free window unless the caller confirms it fits. */ +async function confirmGuestDay(args, io, body) { + const window = body.window === "evening" || body.window === "midday" ? body.window : "any"; + const dayArgs = { ...args, _: [body.anchorDate], date: body.anchorDate, window, json: true, duration: undefined }; + const day = await calendarDay(dayArgs, { print() {} }); + const { midday, evening, blockers } = day.slots; + const fits = window === "midday" ? midday.available : window === "evening" ? evening.available : midday.available || evening.available; + const summary = [`${body.anchorDate} (${window}): midday ${midday.available ? "free" : "busy"}, evening ${evening.available ? "free" : "busy"}${blockers.length ? `, all-day: ${blockers.join(" · ")}` : ""}`, + ...(day.timeline || []).map((item) => ` ${item.time} ${item.title} [${item.tag}]`)].join("\n"); + if (!fits && !isTrue(args.allowBusyDay)) { + throw new UsageError(`The day does not fit this guest event: +${summary} +Pick a free day (dataops calendar next-free-day or dataops calendar slots), or pass --allow-busy-day to override.`); + } + if (!isTrue(args.confirmDay)) { + throw new UsageError(`Confirm the day first; this is what ${body.anchorDate} holds: +${summary} +Re-run with --confirm-day to assign it.`); + } + if (!args.json) io.print(`Day confirmed: +${summary}`); +} +const isTrue = (value) => value === true || value === "true"; + async function write(args, io, id, change, verb) { const api = apiFor(args); const { card } = await api.get(`/api/cards/${enc(id)}`); @@ -591,7 +620,8 @@ export async function time(args, io) { if (args.guests !== undefined) body.guestEmails = csv(args.guests); const result = await apiFor(args).post(`/api/cards/${enc(id)}/time`, body); if (!args.json) { - io.print(`Event: ${result.card.eventTime.startIso} .. ${result.card.eventTime.endIso} (${result.card.eventTime.timeZone})`); + const when = result.card.eventTime || result.event; + if (when) io.print(`Event: ${when.startIso} .. ${when.endIso}${when.timeZone ? ` (${when.timeZone})` : ''}`); if (result.card.anchorDate) io.print(`Card date: ${result.card.anchorDate}${result.movedTasks ? ` (${result.movedTasks} open Tasks re-dated)` : ''}`); if (result.rescheduleTaskId) io.print(`Reschedule checklist Task: ${result.rescheduleTaskId}`); for (const invite of result.card.calendarInvites || []) { @@ -602,6 +632,19 @@ export async function time(args, io) { return result; } +/** --date/--time re-point a failed invitation that has no event yet, so a rejected slot is not replayed. */ +function retryTarget(args) { + const body = {}; + if (args.date !== undefined) body.date = isoDate(optionalString(args, "date"), "date"); + if (args.time !== undefined) { + const time = optionalString(args, "time"); + if (!/^(?:[01]\d|2[0-3]):[0-5]\d$/.test(time)) throw new UsageError("--time must be HH:MM."); + body.time = time; + } + if (body.time && !body.date) throw new UsageError("--time requires --date."); + return body; +} + export async function invitation(args, io) { const id = positional(args, 0, "dataops cards invitation [--preview | --send | --retry-pre-send]"); const modes = ["preview", "send", "retryPreSend"].filter(flag => args[flag] !== undefined && args[flag] !== false && args[flag] !== "false"); @@ -609,8 +652,11 @@ export async function invitation(args, io) { for (const flag of modes) if (args[flag] !== true && args[flag] !== "true") throw new UsageError("Invitation action options are boolean flags."); const api = apiFor(args); const route = `/api/cards/${enc(id)}/guest-intake`; - const result = args.send === true || args.send === "true" ? await api.post(`${route}/send`, {}) - : args.retryPreSend === true || args.retryPreSend === "true" ? await api.post(`${route}/retry`, {}) + const scheduling = {}; + for (const flag of ['agreedFrom', 'agreedTo']) if (args[flag] !== undefined) scheduling[flag] = isoDate(args[flag], flag); + if (Object.keys(scheduling).length && !modes.some(mode => mode === 'send' || mode === 'retryPreSend')) throw new UsageError('Agreement dates require --send or --retry-pre-send.'); + const result = args.send === true || args.send === "true" ? await api.post(`${route}/send`, scheduling) + : args.retryPreSend === true || args.retryPreSend === "true" ? await api.post(`${route}/retry`, { ...retryTarget(args), ...scheduling }) : await api.get(route, args.preview === true || args.preview === "true" ? { query: { preview: "1" } } : undefined); if (args.json) return result; const receipt = result.invitation || result.job || result.card?.guestIntake || result; diff --git a/cli/test/calendar.test.mjs b/cli/test/calendar.test.mjs index 64f396c2..2fa4ecbd 100644 --- a/cli/test/calendar.test.mjs +++ b/cli/test/calendar.test.mjs @@ -181,6 +181,18 @@ describe("Calendar CLI commands", () => { assert.match(text, /MLOps live demonstration/); }); + test("calendar day ignores an adjacent day's all-day blocker returned by the padded range", async () => { + const io = captureIo(); + globalThis.fetch = async (url) => new Response(JSON.stringify(String(url).includes("/overlays") + ? { items: [{ provider: "owner-calendar", label: "AI Coding Summit Berlin", startDate: "2026-12-04", endDate: "2026-12-04", slot: "all-day" }] } + : { items: [], holidays: [] }), { status: 200, headers: { "Content-Type": "application/json" } }); + const code = await run(["calendar", "day", "2026-12-03", "--json"], io); + assert.equal(code, 0); + const payload = JSON.parse(io.text()); + assert.deepEqual(payload.slots.blockers, []); + assert.equal(payload.slots.midday.available, true); + }); + test("calendar day --json returns structured slot availability payload", async () => { const io = captureIo(); @@ -860,3 +872,32 @@ test("link-hold previews a verified association and requires reviewed versions o assert.equal(await run(['calendar','link-hold','hold-example','--card','card-example','--apply','--expected-card-version','3','--expected-hold-version','4','--expected-episode-version','2'],captureIo()),0); assert.deepEqual(requests[1].body,{cardId:'card-example',expectedCardVersion:3,expectedHoldVersion:4,expectedEpisodeVersion:2,apply:true}); }); + +test("calendar day marks weekends as unavailable", async () => { + const io = captureIo(); + globalThis.fetch = async (url) => new Response(JSON.stringify(String(url).includes("/overlays") + ? { items: [] } + : { items: [], holidays: [] }), { status: 200, headers: { "Content-Type": "application/json" } }); + const code = await run(["calendar", "day", "2026-12-06", "--json"], io); + assert.equal(code, 0); + const payload = JSON.parse(io.text()); + assert.equal(payload.slots.midday.available, false); + assert.equal(payload.slots.evening.available, false); + assert.ok(payload.slots.midday.conflicts.includes("Weekend")); +}); + +test("calendar next-free-day queries /api/calendar-items/next-free-day with type and window", async () => { + const io = captureIo(); + const requests = []; + globalThis.fetch = async (url) => { + requests.push(String(url)); + return Response.json({ found: true, date: "2026-12-04", window: "midday", time: "12:30", durationMinutes: 60 }); + }; + const code = await run(["calendar", "next-free-day", "--type", "podcast", "--window", "midday", "--from", "2026-12-03", "--to", "2026-12-10", "--json"], io); + assert.equal(code, 0); + assert.match(requests[0], /\/api\/calendar-items\/next-free-day\?/); + assert.match(requests[0], /window=midday/); + assert.match(requests[0], /type=podcast/); + assert.match(requests[0], /duration=60/); + assert.equal(JSON.parse(io.text()).date, "2026-12-04"); +}); diff --git a/cli/test/cards-invitation.test.mjs b/cli/test/cards-invitation.test.mjs index b97f1422..5d9e7681 100644 --- a/cli/test/cards-invitation.test.mjs +++ b/cli/test/cards-invitation.test.mjs @@ -37,3 +37,10 @@ test('conflicting invitation actions fail before requests', async () => { assert.equal(await run(['cards', 'invitation', 'synthetic-card', '--send', '--preview'], captureIo()), 2); assert.equal(calls.length, 0); }); +test('retry-pre-send can re-point a failed invitation at a new date without an event', async () => { + const calls = fakePortal({ 'POST /api/cards/synthetic-card/guest-intake/retry': { invitation: { status: 'queued' } } }); + assert.equal(await run(['cards', 'invitation', 'synthetic-card', '--retry-pre-send', '--date', '2026-11-25', '--time', '12:30'], captureIo()), 0); + assert.deepEqual(calls.at(-1).body, { date: '2026-11-25', time: '12:30' }); + assert.equal(await run(['cards', 'invitation', 'synthetic-card', '--retry-pre-send', '--time', '12:30'], captureIo()), 2); + assert.equal(calls.length, 1); +}); diff --git a/cli/test/work.test.mjs b/cli/test/work.test.mjs index 57362153..56f1c841 100644 --- a/cli/test/work.test.mjs +++ b/cli/test/work.test.mjs @@ -448,9 +448,11 @@ describe("cards and templates", () => { test("guest event creation preserves explicit optional values, skip email and replay key", async () => { const calls = fakePortal({ "GET /api/templates/event-type": { template: { id: "tpl-event", type: "event-type", eventPolicy: {} } }, + "GET /api/calendar-items/overlays": { items: [] }, + "GET /api/calendar-items": { items: [], holidays: [] }, "POST /api/cards": ({ body }) => ({ card: { id: "guest-card", ...body }, tasks: [] }), }); - const command = ["cards", "create", "--template", "event-type", "--guest-email", "guest@example.test", "--guest-name", "Synthetic Guest", "--topic", "Practical workflows", "--date", "2026-12-14", "--skip-email", "--key", "same-explicit-key"]; + const command = ["cards", "create", "--template", "event-type", "--guest-email", "guest@example.test", "--guest-name", "Synthetic Guest", "--topic", "Practical workflows", "--date", "2026-12-14", "--confirm-day", "--skip-email", "--key", "same-explicit-key"]; assert.equal(await run(command, captureIo()), 0); const sent = calls.at(-1).body; assert.deepEqual(sent, { templateId: "tpl-event", guestEmail: "guest@example.test", guestName: "Synthetic Guest", topic: "Practical workflows", anchorDate: "2026-12-14", skipEmail: true, creationKey: "same-explicit-key" }); @@ -458,6 +460,27 @@ describe("cards and templates", () => { assert.deepEqual(calls.at(-1).body, sent); }); + test("guest creation with a date is confirm-first and refuses a day without a free window", async () => { + const day = (items) => ({ + "GET /api/templates/podcast": { template: { id: "tpl-event", type: "podcast" } }, + "GET /api/calendar-items/overlays": { items }, + "GET /api/calendar-items": { items: [], holidays: [] }, + "POST /api/cards": ({ body }) => ({ card: { id: "guest-card", ...body } }), + }); + const base = ["cards", "create", "--template", "podcast", "--guest-email", "guest@example.test", "--date", "2026-12-03"]; + let calls = fakePortal(day([])); + const io = captureIo(); + assert.equal(await run(base, io), 2); + assert.match(io.errors.join(" "), /Confirm the day first/); + assert.ok(!calls.some((call) => call.method === "POST")); + assert.equal(await run([...base, "--confirm-day"], captureIo()), 0); + assert.equal(calls.at(-1).method, "POST"); + calls = fakePortal(day([{ provider: "owner-calendar", label: "Summit", startDate: "2026-12-03", endDate: "2026-12-03", slot: "all-day" }])); + assert.equal(await run([...base, "--confirm-day"], captureIo()), 2); + assert.ok(!calls.some((call) => call.method === "POST")); + assert.equal(await run([...base, "--confirm-day", "--allow-busy-day"], captureIo()), 0); + }); + test("saved guest references reuse the private contact without a required date", async () => { const calls = fakePortal({ "GET /api/templates/podcast": { template: { id: "tpl-event", type: "podcast", guestIntake: { enabled: true } } },