Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
65a6a11
Guest intake: keep event, anchor and job in sync; confirm-first day a…
alexeygrigorev Nov 24, 2026
ea4b7d7
Drop retry assertion that precedes the status gate
alexeygrigorev Nov 24, 2026
ea46d18
Guest intake: allow explicit free weekdays, prioritize queued jobs, a…
alexeygrigorev Nov 24, 2026
3bb5cbc
Check owner calendar availability and bound guest scheduling to agree…
alexeygrigorev Nov 24, 2026
d3195e5
Integrate existing intake recovery and confirm-first scheduling fixes…
alexeygrigorev Nov 24, 2026
9ffbecf
Recheck owner availability before calendar writes and synchronize anc…
alexeygrigorev Nov 24, 2026
4c3b123
Merge main into guest-intake desync fix
alexeygrigorev Nov 25, 2026
873eb18
Fix tests and listing/availability interplay after merging main into …
alexeygrigorev Nov 25, 2026
d1c502f
Fix owner availability mock import in podcast episode tests
alexeygrigorev Nov 26, 2026
f3285cc
Merge current main into guest intake availability fix
alexeygrigorev Nov 26, 2026
0890efb
Keep intake retries on the normalized rescheduled event date
alexeygrigorev Nov 26, 2026
88b803b
Merge remote-tracking branch 'origin/main' into triage/520-f3432aa8
alexeygrigorev Nov 26, 2026
21aecf7
Merge remote-tracking branch 'origin/main' into triage/520-f3432aa8
alexeygrigorev Nov 27, 2026
0d1adb6
test(calendar): pin the clock in the owner-availability cases
alexeygrigorev Nov 27, 2026
e3c4906
test(e2e): confirm the podcast slot on the card instead of booking an…
alexeygrigorev Nov 27, 2026
c89e05a
test(e2e): assert newsletter card fields from the issue API
alexeygrigorev Nov 27, 2026
5347835
test(e2e): stub the calendar overlays in the mobile-width route sweep
alexeygrigorev Nov 27, 2026
81d90d6
Merge main into guest-intake desync fix
alexeygrigorev Nov 27, 2026
b9f4f07
test(e2e): stub the calendar overlays in the top-level surfaces sweep
alexeygrigorev Nov 27, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions backend/e2e/frontend-module-characterization.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,11 @@ test.describe("pre-refactor frontend module characterization", () => {
test("retained top-level surfaces keep canonical route, title, marker, and primary interaction", async ({ browser }) => {
const context = await ownedContext(browser, { width: 1440, height: 900 });
const page = await context.newPage();
// Overlays are fail-closed on the owner's calendar (503 without a broker); see
// the mobile-width sweep below.
await page.route("**/api/calendar-items/overlays*", (route) =>
route.fulfill({ json: { items: [], sources: {} } }),
);
const errors = observeErrors(page);
const routes = [
["/tasks", "Work Queue", ".ops-work-queue"],
Expand Down Expand Up @@ -296,6 +301,12 @@ test.describe("pre-refactor frontend module characterization", () => {
test("all retained routes avoid page overflow and runtime errors at mobile width", async ({ browser }) => {
const context = await ownedContext(browser, { width: 390, height: 844 });
const page = await context.newPage();
// The overlays endpoint is fail-closed on the owner's calendar (503 without a
// broker), which this server does not have; this test is about layout and
// runtime errors, not calendar data.
await page.route("**/api/calendar-items/overlays*", (route) =>
route.fulfill({ json: { items: [], sources: {} } }),
);
const errors = observeErrors(page);
const routes = [
"/",
Expand Down
7 changes: 3 additions & 4 deletions backend/e2e/newsletter-issue-cards.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,10 +48,9 @@ test('a far-future issue shows when its card comes and creates it on request', a
const saved = await (await request.get(`/api/newsletter-issues/${issue.id}`)).json();
expect(saved.cardId).toBeTruthy();

const overlays = await (await request.get('/api/calendar-items/overlays', { params: { from: publicationDate, to: publicationDate } })).json();
const item = overlays.items.find((overlay) => overlay.id === issue.id);
expect(item.newsletter.cardId).toBe(saved.cardId);
expect(item.newsletter.cardDueDate).toBeNull();
// The calendar overlay is fail-closed on the owner's calendar, which this server
// does not have; the issue API carries the same card fields.
expect(saved.cardDueDate).toBeNull();
} finally {
await context.close();
}
Expand Down
10 changes: 6 additions & 4 deletions backend/e2e/podcast-guest-form.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -304,12 +304,14 @@ test.describe("podcast guest materials form", () => {
const createdCard = await api(`/api/podcast-episodes/${episode.id}/card`, {});
const cardId = createdCard.card?.id || createdCard.episode?.cardId;
expect(cardId).toBeTruthy();
const timeRes = await fetch(`${server.baseURL}/api/cards/${cardId}/time`, {
method: "POST",
// Confirm the slot on the Card directly: POST /time now re-checks the owner's
// calendar before writing an invite, and this server has no calendar broker.
const timeRes = await fetch(`${server.baseURL}/api/cards/${cardId}`, {
method: "PUT",
headers: { "content-type": "application/json" },
body: JSON.stringify({
at: "2026-12-15 18:00",
guestEmails: ["confirmed-guest@example.test"],
expectedVersion: createdCard.card?.version ?? 1,
eventTime: { at: "2026-12-15 18:00" },
}),
});
const timePayload = await timeRes.json();
Expand Down
21 changes: 21 additions & 0 deletions backend/src/calendar/assertOwnerAvailable.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
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'; }
}

/** The day the availability read counts as today; the owner calendar is read from that day onward. Defaults to the current one. */
export type OwnerAvailabilityClock = { today?: string; now?: Date };

/** 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<string,string> = {}, clock: OwnerAvailabilityClock = {}): Promise<void> {
const from = formatBerlinDate(startIso), to = formatBerlinDate(endIso);
const projection = await ownerCalendarOverlay({ client, includeAll: true, excludeEventIds: existingEventIds, today: clock.today, now: clock.now }).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);
}
5 changes: 3 additions & 2 deletions backend/src/calendar/cardInvite.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -341,6 +342,7 @@ export async function syncCardInvite(
}, deps.calendarIds),
};
}
await assertOwnerAvailable(client, invite?.startIso || interval.startIso, interval.endIso, { ...eventIds, ...listingCopyIds, ...publicCopyIds });
const reserved = await updateCard(client, card.id, {
expectedVersion: card.version,
patch: { eventTime: pending, guestEmails: silentLumaEvent ? [] : guests },
Expand Down Expand Up @@ -671,8 +673,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}`,
Expand Down
5 changes: 5 additions & 0 deletions backend/src/calendar/holdGoogleSync.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { assertOwnerAvailable, OwnerAvailabilityError, type OwnerAvailabilityClock } from './assertOwnerAvailable';
/**
* Google mirroring for calendar holds, per SOP
* `sop.events.calendar.creating-tentative-event-on-google-calendar`.
Expand Down Expand Up @@ -52,6 +53,8 @@ export interface HoldGoogleDeps {
calendarIds?: string[];
/** Override Google sendUpdates on organizer cancellation (e.g. 'none' on tentative TTL expiry so no guest email is ever sent). */
sendUpdates?: 'all' | 'none';
/** Pinned clock for the owner-availability check (tests); defaults to the current day. */
clock?: OwnerAvailabilityClock;
}

export type HoldGoogleResult =
Expand Down Expand Up @@ -207,6 +210,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, deps.clock);
// 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);
Expand Down Expand Up @@ -281,6 +285,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);
Expand Down
73 changes: 73 additions & 0 deletions backend/src/calendar/ownerAvailability.ts
Original file line number Diff line number Diff line change
@@ -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<AvailabilityEvent[]> {
const headers = { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' };
async function request(path: string, body?: unknown): Promise<any> {
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<string>([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;
}
Loading