Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
2 changes: 1 addition & 1 deletion docs/codebase-index.md
Original file line number Diff line number Diff line change
Expand Up @@ -961,7 +961,7 @@ Administrator source intake also records admission events in `document_admission

`documents`, `document_pages`, `document_images`, `document_chunks`, `document_embedding_fields`, `document_index_units`, `document_table_facts`, `document_labels`, `document_summaries`, `document_sections`, `document_memory_cards`, `document_index_quality`, `document_title_words`, `document_publication_approvals`, `document_corpus_access_state`, `document_corpus_access_snapshots`, `ingestion_jobs`, `ingestion_job_stages`, `indexing_v3_agent_jobs`, `import_batches`, `image_caption_cache`, `rag_queries`, `rag_query_misses`, `rag_aliases`, `rag_response_cache`, `rag_retrieval_logs`, `rag_visual_eval_cases`, `rag_visual_eval_runs`, `rag_answer_feedback`, `clinical_registry_records`, `clinical_registry_record_sources`, `clinical_quality_feedback_triage`, `clinical_quality_feedback_triage_events`, `medication_records`, `differential_records`, `source_review_events`, `user_favourites`, `user_favourite_sets`, `user_preferences`, `work_admin_paperwork`, `work_backups`, `work_booking_courses`, `work_course_bookings`, `work_hospitals`, `work_hospital_teams`, `work_role_grants`, `alert_reminder_times`, `alert_brief_sent`, `api_rate_limits`, `api_rate_limit_subjects`, `audit_logs`, `storage_cleanup_jobs`, `on_call_entries`, `cme_years`, `cme_requirements`, `cme_routines`, `cme_entries`, `cme_allocations`, `cme_evidence`, `cme_year_snapshots`, `cme_year_amendments`, `cme_plan_goals`, `cme_plan_goal_carries`, `cme_entry_goals`, `cme_training_periods`, `cme_training_milestones`, `cme_missed_sessions`, `cme_entry_drafts`, `calendar_feed_tokens`, `on_call_shift_imports`, `on_call_shifts`, `on_call_services`, `on_call_service_sites`, `on_call_service_members`, `on_call_service_invitations`, `on_call_service_entries`, `on_call_service_reports`, `on_call_service_orientation`, `site_content_publications`, `site_content_reconciliation_plans`, `site_content_public_records`, `site_content_sync_state`, `site_content_sync_events`, `site_content_sync_event_plans`, `site_content_sync_worker_invocations`, `site_content_releases`, `site_content_release_records`, `site_content_release_receipts`

Team modes (Roster, Admin, Teaching): `admin_leave_balances`, `admin_settings`, `extra_time_records`, `on_call_service_member_events`, `registrar_assessments`, `registrar_training_milestones`, `roster_assignments`, `roster_calendar_links`, `roster_change_agreements`, `roster_changes`, `roster_draft_assignments`, `roster_drafts`, `roster_leave`, `roster_member_roles`, `roster_open_shifts`, `roster_publication_protections`, `roster_publication_seen`, `roster_publications`, `roster_rotation_preferences`, `roster_rotation_rounds`, `roster_shift_codes`, `roster_staffing_needs`, `roster_swaps`, `roster_team_settings`, `roster_unavailability`, `teaching_attendance`, `teaching_audit_events`, `teaching_calendar_optins`, `teaching_checkin_claims`, `teaching_collection_sections`, `teaching_collections`, `teaching_display_links`, `teaching_feedback_answers`, `teaching_feedback_replied`, `teaching_group_members`, `teaching_groups`, `teaching_member_roles`, `teaching_notice_reads`, `teaching_notices`, `teaching_occurrences`, `teaching_readiness`, `teaching_resource_saves`, `teaching_resources`, `teaching_series`, `teaching_supervision_entries`, `teaching_supervision_notes`, `teaching_supervision_pairings`, `teaching_team_settings`, `teaching_week_adds`, `web_push_subscriptions`.
Team modes (Roster, Admin, Teaching): `admin_leave_balances`, `admin_settings`, `extra_time_records`, `on_call_service_member_events`, `registrar_assessments`, `registrar_training_milestones`, `roster_assignments`, `roster_calendar_links`, `roster_change_agreements`, `roster_changes`, `roster_draft_assignments`, `roster_drafts`, `roster_leave`, `roster_member_roles`, `roster_open_post_keys`, `roster_open_shifts`, `roster_publication_protections`, `roster_publication_seen`, `roster_publications`, `roster_rotation_preferences`, `roster_rotation_rounds`, `roster_shift_codes`, `roster_staffing_needs`, `roster_swaps`, `roster_team_settings`, `roster_unavailability`, `teaching_attendance`, `teaching_audit_events`, `teaching_calendar_optins`, `teaching_checkin_claims`, `teaching_collection_sections`, `teaching_collections`, `teaching_display_links`, `teaching_feedback_answers`, `teaching_feedback_replied`, `teaching_group_members`, `teaching_groups`, `teaching_member_roles`, `teaching_notice_reads`, `teaching_notices`, `teaching_occurrences`, `teaching_readiness`, `teaching_resource_saves`, `teaching_resources`, `teaching_series`, `teaching_supervision_entries`, `teaching_supervision_notes`, `teaching_supervision_pairings`, `teaching_team_settings`, `teaching_week_adds`, `web_push_subscriptions`.

Public-source control-plane tables: `public_source_policy_entries`, `public_source_activation_events`, `public_source_versions`, `public_source_upload_attempts`, `public_source_activation_guards`, `public_source_cleanup_mutation_guards`.

Expand Down
1 change: 1 addition & 0 deletions scripts/lib/cross-tenant-roster-probe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ function actionSamples(id: string, userId: string, date: string): RosterAction[]
swapId: id,
})),
{ action: "open.post", assignmentId: id },
{ action: "open.post", assignmentId: id, postKey: id },
{ action: "open.report", assignmentId: id },
...(["open.claim", "open.approve", "open.decline", "open.cancel", "open.withdraw"] as const).map((action) => ({
action,
Expand Down
8 changes: 8 additions & 0 deletions src/components/open-shifts/open-shifts-post-page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,10 @@ export function OpenShiftsPostPage() {
const [unanswered, setUnanswered] = useState<
Record<string, { readonly ids: readonly string[]; readonly at: number; readonly serviceId: string }>
>({});
// One post key per date being posted, by everything that was sent. A retry of a date whose answer was
// lost sends the same key, so the server answers with the shift that post already saved instead of saving
// a second one. A key is dropped once its date is posted; changing anything in the shift makes a new key.
const postKeys = useRef<Record<string, string>>({});
Comment thread
BigSimmo marked this conversation as resolved.
Resolved
Comment thread
BigSimmo marked this conversation as resolved.
Resolved
const [copied, setCopied] = useState(false);
// The last partial-failure report, kept on the page so closing the sheet never hides what went live.
const [report, setReport] = useState<string | null>(null);
Expand Down Expand Up @@ -255,6 +259,8 @@ export function OpenShiftsPostPage() {
attempts.push({ date: on, ok: false, message: "The times couldn't be worked out for this date." });
continue;
}
const postKey = postKeys.current[signature(on)] ?? crypto.randomUUID();
postKeys.current[signature(on)] = postKey;
const result = await postRosterAction(team.serviceId, {
action: "open.post",
startsAt: onTimes.startsAt,
Expand All @@ -264,10 +270,12 @@ export function OpenShiftsPostPage() {
siteId: site || null,
minGrade: level || null,
urgent,
postKey,
} as RosterAction);
if (result.ok) {
attempts.push({ date: on, ok: true, openShiftId: result.result.openShiftId ?? null });
nowDone[signature(on)] = result.result.openShiftId ?? "";
delete postKeys.current[signature(on)];
} else {
attempts.push({ date: on, ok: false, message: result.message });
// No answer at all: it may still have gone live, so a retry checks the team's list first. A repeat
Expand Down
4 changes: 4 additions & 0 deletions src/lib/roster/alerts/dispatch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ function resultOf(value: unknown): {
status?: string;
swapId?: string;
openShiftId?: string;
replayed?: boolean;
recipientIds?: string[];
changedUserIds?: string[];
swapsCancelled?: { requesterId?: string; counterpartyId?: string }[];
Expand All @@ -35,6 +36,9 @@ export async function dispatchRosterAlerts(client: RosterAdminClient, event: Ros
try {
const result = resultOf(event.result);
if (result.status === "cancelled" || result.status === "expired") return;
// A repeat of a post the server had already saved (the phone never heard back the first time):
// its alerts went out with the first post, so they are never sent twice.
if (result.replayed === true) return;
// The overview checks the actor's team access. G3's manager list is the
// only authority for manager alerts; active membership is checked below.
const overview = await rosterRead(client, event.actorId, event.serviceId, "overview");
Expand Down
1 change: 1 addition & 0 deletions src/lib/roster/team/demo-team-core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -420,6 +420,7 @@ export function demoRosterCommand(action: RosterAction): RosterCommandResult {
case "swap.undo":
return { ok: true, swapId: action.swapId, status: "cancelled" };
case "open.post":
// A post key is accepted and ignored: nothing is saved here, so there is nothing to post twice.
return { ok: true, openShiftId: id, status: "open" };
case "open.claim":
return { ok: true, openShiftId: action.openShiftId, status: "claimed" };
Expand Down
3 changes: 3 additions & 0 deletions src/lib/roster/team/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -391,6 +391,9 @@ const openPostSchema = z
siteId: nullableOptional(uuid),
minGrade: nullableOptional(z.enum(["intern", "resident", "registrar", "fellow", "consultant"])),
urgent: z.boolean().optional(),
// One random key per date the phone posts, sent again when it retries that date after a lost
// answer, so the retry answers with the shift already saved (roster_open_post_once).
postKey: uuid.optional(),
})
.strict()
.superRefine((value, context) => {
Expand Down
27 changes: 21 additions & 6 deletions src/lib/roster/team/repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,12 @@ export async function rosterReadTeams(client: AdminClient, actorId: string): Pro
return parsed.data.teams;
}

function withoutPostKey(payload: Record<string, unknown>): Record<string, unknown> {
const rest = { ...payload };
delete rest.postKey;
return rest;
}

/** A team write. `action` has already passed `rosterActionSchema` (or is a publish-route action). */
export async function rosterCommand(
client: AdminClient,
Expand All @@ -80,6 +86,8 @@ export async function rosterCommand(
const { action: name, ...payload } = action;
// The safe number goes through the stale check, which refuses it once anyone has saved since the editor's read.
// Taking back an open-shift request has its own function, which only the doctor who asked can call.
// A post that carries a key goes through roster_open_post_once, which answers a repeat of the same
// key with the shift already saved instead of saving another; the key itself is not part of the post.
const { data, error } =
action.action === "open.withdraw"
? await client.rpc("roster_open_withdraw", {
Expand All @@ -94,12 +102,19 @@ export async function rosterCommand(
p_expected_ids: action.expectedIds as never,
p_needs: action.needs as never,
})
: await client.rpc("roster_command", {
p_actor_id: actorId,
p_service_id: serviceId,
p_action: name,
p_payload: payload as never,
});
: action.action === "open.post" && action.postKey
? await client.rpc("roster_open_post_once", {
p_actor_id: actorId,
p_service_id: serviceId,
p_post_key: action.postKey,
p_payload: withoutPostKey(payload) as never,
})
: await client.rpc("roster_command", {
p_actor_id: actorId,
p_service_id: serviceId,
p_action: name,
p_payload: payload as never,
});
if (error) throw rosterApiError(error);
const parsed = rosterCommandResultSchema.safeParse(data);
if (!parsed.success) throw rosterUnavailable();
Expand Down
28 changes: 28 additions & 0 deletions src/lib/supabase/database.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4363,6 +4363,30 @@ export type Database = {
};
Relationships: [];
};
roster_open_post_keys: {
Row: {
created_at: string;
open_shift_id: string;
post_key: string;
posted_by: string | null;
service_id: string;
};
Insert: {
created_at?: string;
open_shift_id: string;
post_key: string;
posted_by?: string | null;
service_id: string;
};
Update: {
created_at?: string;
open_shift_id?: string;
post_key?: string;
posted_by?: string | null;
service_id?: string;
};
Relationships: [];
};
roster_open_shifts: {
Row: {
assignment_id: string | null;
Expand Down Expand Up @@ -4945,6 +4969,10 @@ export type Database = {
Args: { p_actor_id: string; p_service_id: string; p_open_shift_id: string };
Returns: Json;
};
roster_open_post_once: {
Args: { p_actor_id: string; p_service_id: string; p_post_key: string; p_payload: Json };
Returns: Json;
};
on_call_service_set_verified: {
Args: { p_service_id: string; p_actor_id: string; p_verified: boolean; p_is_demo: boolean };
Returns: Json;
Expand Down
3 changes: 2 additions & 1 deletion supabase/applied-migration-hashes.json
Original file line number Diff line number Diff line change
Expand Up @@ -312,6 +312,7 @@
"20261013170000_force_rls_control_plane.sql": "46d746dd78ed0c62489d72244ffc70b38dc08e3adb7d62ef360482dcb7214a85",
"20261013200007_managed_native_pdf_terminal_append.sql": "94ac297bad4a1f9d28fcb13d018237df081aa5b3da328073be8c9e17774bd292",
"20261014164220_validate_managed_ingestion_historical_reconciliation.sql": "8ffd75292620e82065300eb1e1d008c229545dde37826862820bfd6ea1314587",
"20261015160000_document_child_policies_check_parent_owner.sql": "71210bbc5aecdca74bee2ae32181ba2861e65017ca1a5e87995aa8e557946094"
"20261015160000_document_child_policies_check_parent_owner.sql": "71210bbc5aecdca74bee2ae32181ba2861e65017ca1a5e87995aa8e557946094",
"20261015174500_roster_open_post_once.sql": "a4edfe07497e3b833c4bedecf1b41d0d7b9fb0b73a798a71b3c17bccb9f851ff"
}
}
91 changes: 89 additions & 2 deletions supabase/drift-manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
"generated_at": "2026-10-15T15:56:45.785Z",
"generator": "scripts/generate-drift-manifest.ts",
"postgres_image": "supabase/postgres:17.6.1.127@sha256:be60aee15997daca475b710b734bc6bfe52cd544dcd7e9fd2ff58210b6747d83",
"schema_sha256": "99c313f9b394551fe2bfc44361802c9523fb5cb092721b3739b7059c7d472606",
"replay_seconds": 18,
"schema_sha256": "e561ea277c34ddec08d6b676ebcb8603c0e98b04e0ca311c9fbf4a4f49246895",
"replay_seconds": 38,
"snapshot": {
"views": [
{
Expand Down Expand Up @@ -9197,6 +9197,58 @@
"rls_forced": false,
"rls_enabled": true
},
{
"acl": [
"postgres=arwdDxtm/postgres",
"service_role=arwd/postgres"
],
"name": "roster_open_post_keys",
"columns": [
{
"name": "created_at",
"type": "timestamp with time zone",
"default": "now()",
"identity": "",
"not_null": true,
"generated": ""
},
{
"name": "open_shift_id",
"type": "uuid",
"default": null,
"identity": "",
"not_null": true,
"generated": ""
},
{
"name": "post_key",
"type": "uuid",
"default": null,
"identity": "",
"not_null": true,
"generated": ""
},
{
"name": "posted_by",
"type": "uuid",
"default": null,
"identity": "",
"not_null": false,
"generated": ""
},
{
"name": "service_id",
"type": "uuid",
"default": null,
"identity": "",
"not_null": true,
"generated": ""
}
],
"reloptions": null,
"rls_forced": false,
"rls_enabled": true
},
{
"acl": [
"postgres=arwdDxtm/postgres",
Expand Down Expand Up @@ -16009,6 +16061,18 @@
"table": "roster_member_roles",
"def_hash": "590bcff136e7af842298b48ee261e3f2"
},
{
"def": "CREATE INDEX roster_open_post_keys_open_shift_idx ON public.roster_open_post_keys USING btree (open_shift_id)",
"name": "roster_open_post_keys_open_shift_idx",
"table": "roster_open_post_keys",
"def_hash": "b6bf535bf8cb73f1cd9c8a0c01519b13"
},
{
"def": "CREATE UNIQUE INDEX roster_open_post_keys_pkey ON public.roster_open_post_keys USING btree (service_id, post_key)",
"name": "roster_open_post_keys_pkey",
"table": "roster_open_post_keys",
"def_hash": "5747b4e8b8ecd35fa92d19e91d40b72a"
},
{
"def": "CREATE UNIQUE INDEX roster_open_shifts_live_assignment_idx ON public.roster_open_shifts USING btree (assignment_id) WHERE ((status = ANY (ARRAY['reported'::text, 'open'::text, 'claimed'::text])) AND (assignment_id IS NOT NULL))",
"name": "roster_open_shifts_live_assignment_idx",
Expand Down Expand Up @@ -19931,6 +19995,14 @@
"def_hash": "3970f82d1ac917820e8f1d2d8cc9b88e",
"signature": "public.roster_on_membership_revoked()"
},
{
"acl": [
"postgres=X/postgres",
"service_role=X/postgres"
],
"def_hash": "ca06394dd5c4556e65af5a771fc47841",
"signature": "public.roster_open_post_once(uuid,uuid,uuid,jsonb)"
},
{
"acl": [
"postgres=X/postgres"
Expand Down Expand Up @@ -23647,6 +23719,21 @@
"name": "roster_member_roles_service_id_user_id_fkey",
"table": "roster_member_roles"
},
{
"def": "FOREIGN KEY (open_shift_id) REFERENCES public.roster_open_shifts(id) ON DELETE CASCADE",
"name": "roster_open_post_keys_open_shift_id_fkey",
"table": "roster_open_post_keys"
},
{
"def": "PRIMARY KEY (service_id, post_key)",
"name": "roster_open_post_keys_pkey",
"table": "roster_open_post_keys"
},
{
"def": "FOREIGN KEY (service_id) REFERENCES public.on_call_services(id) ON DELETE CASCADE",
"name": "roster_open_post_keys_service_id_fkey",
"table": "roster_open_post_keys"
},
{
"def": "FOREIGN KEY (assignment_id) REFERENCES public.roster_assignments(id) ON DELETE CASCADE",
"name": "roster_open_shifts_assignment_id_fkey",
Expand Down
Loading
Loading