From 32c519b389d47a1fe8130135ce36ab567f08aa04 Mon Sep 17 00:00:00 2001 From: Musa Kaleem <131704022+Musa-Kal@users.noreply.github.com> Date: Sun, 22 Nov 2026 18:22:21 -0500 Subject: [PATCH 01/21] feat(core): add quick poll limits Co-authored-by: Ferrin <177692050+Ferrin-Y@users.noreply.github.com> Co-authored-by: noorelmosrati <182049385+noorelmosrati@users.noreply.github.com> --- packages/core/src/index.ts | 1 + packages/core/src/quick-polls/index.ts | 14 +++++++++ packages/core/src/quick-polls/limits.test.ts | 33 ++++++++++++++++++++ packages/core/src/quick-polls/limits.ts | 26 +++++++++++++++ 4 files changed, 74 insertions(+) create mode 100644 packages/core/src/quick-polls/index.ts create mode 100644 packages/core/src/quick-polls/limits.test.ts create mode 100644 packages/core/src/quick-polls/limits.ts diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index fe9c6f6a..2a143418 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -13,6 +13,7 @@ export * from './money' export * from './payments' export * from './people' export * from './portability' +export * from './quick-polls' export * from './receipts' export * from './recurrence' export * from './roles' diff --git a/packages/core/src/quick-polls/index.ts b/packages/core/src/quick-polls/index.ts new file mode 100644 index 00000000..09a709be --- /dev/null +++ b/packages/core/src/quick-polls/index.ts @@ -0,0 +1,14 @@ +export { + isQuickPollTtl, + QUICK_POLL_DEFAULT_PEOPLE, + QUICK_POLL_MAX_DAYS, + QUICK_POLL_MAX_PEOPLE, + QUICK_POLL_MIN_PEOPLE, + QUICK_POLL_NAME_MAX, + QUICK_POLL_SLOT_MINUTES, + QUICK_POLL_TITLE_MAX, + QUICK_POLL_TTLS, + quickPollWindowFits, + type QuickPollSlotMinutes, + type QuickPollTtl, +} from './limits' diff --git a/packages/core/src/quick-polls/limits.test.ts b/packages/core/src/quick-polls/limits.test.ts new file mode 100644 index 00000000..bb990e95 --- /dev/null +++ b/packages/core/src/quick-polls/limits.test.ts @@ -0,0 +1,33 @@ +import { describe, expect, it } from 'vitest' +import { + isQuickPollTtl, + QUICK_POLL_DEFAULT_PEOPLE, + QUICK_POLL_MAX_PEOPLE, + QUICK_POLL_MIN_PEOPLE, + quickPollWindowFits, +} from './index' + +// Same cases as supabase/tests/36_quick_polls.test.sql. +describe('quick poll limits', () => { + it('takes 2 to 15 people, 10 by default', () => { + expect([QUICK_POLL_MIN_PEOPLE, QUICK_POLL_DEFAULT_PEOPLE, QUICK_POLL_MAX_PEOPLE]).toEqual([ + 2, 10, 15, + ]) + }) + + it('lasts 24 hours or 7 days', () => { + expect(isQuickPollTtl('24h')).toBe(true) + expect(isQuickPollTtl('7d')).toBe(true) + expect(isQuickPollTtl('30d')).toBe(false) + expect(isQuickPollTtl(null)).toBe(false) + }) + + it('covers 1 to 14 days, both ends included', () => { + expect(quickPollWindowFits('2026-06-01', '2026-06-01')).toBe(true) + expect(quickPollWindowFits('2026-06-01', '2026-06-14')).toBe(true) + expect(quickPollWindowFits('2026-06-01', '2026-06-15')).toBe(false) + expect(quickPollWindowFits('2026-06-02', '2026-06-01')).toBe(false) + expect(quickPollWindowFits('2026-03-25', '2026-04-07')).toBe(true) + expect(quickPollWindowFits('nope', '2026-06-01')).toBe(false) + }) +}) diff --git a/packages/core/src/quick-polls/limits.ts b/packages/core/src/quick-polls/limits.ts new file mode 100644 index 00000000..d6939fe4 --- /dev/null +++ b/packages/core/src/quick-polls/limits.ts @@ -0,0 +1,26 @@ +/** + * Limits for quick polls (ADR 22). The database enforces the same numbers in + * `public.create_quick_poll` and the `public.quick_polls` checks; change both together. + */ +export const QUICK_POLL_MIN_PEOPLE = 2 +export const QUICK_POLL_MAX_PEOPLE = 15 +export const QUICK_POLL_DEFAULT_PEOPLE = 10 +/** Days a poll's window may cover, first and last day included. */ +export const QUICK_POLL_MAX_DAYS = 14 +export const QUICK_POLL_TITLE_MAX = 80 +export const QUICK_POLL_NAME_MAX = 40 +export const QUICK_POLL_TTLS = ['24h', '7d'] as const +export type QuickPollTtl = (typeof QUICK_POLL_TTLS)[number] +export const QUICK_POLL_SLOT_MINUTES = [30, 60] as const +export type QuickPollSlotMinutes = (typeof QUICK_POLL_SLOT_MINUTES)[number] + +export function isQuickPollTtl(value: unknown): value is QuickPollTtl { + return QUICK_POLL_TTLS.some((ttl) => ttl === value) +} + +/** True when the days from `windowStart` to `windowEnd` (`YYYY-MM-DD`, both included) fit a poll. */ +export function quickPollWindowFits(windowStart: string, windowEnd: string): boolean { + const days = + (Date.parse(`${windowEnd}T00:00:00Z`) - Date.parse(`${windowStart}T00:00:00Z`)) / 86_400_000 + 1 + return Number.isInteger(days) && days >= 1 && days <= QUICK_POLL_MAX_DAYS +} From ed86fab799a0773ab66037f9c298c5ae7eaeddf1 Mon Sep 17 00:00:00 2001 From: Musa Kaleem <131704022+Musa-Kal@users.noreply.github.com> Date: Sun, 22 Nov 2026 18:31:05 -0500 Subject: [PATCH 02/21] feat(db): add quick polls tables, RPCs and purge job Co-authored-by: Ferrin <177692050+Ferrin-Y@users.noreply.github.com> Co-authored-by: noorelmosrati <182049385+noorelmosrati@users.noreply.github.com> --- packages/api/src/database.types.ts | 166 +++++ .../migrations/20261122232215_quick_polls.sql | 593 +++++++++++++++ supabase/schema/current.sql | 690 ++++++++++++++++-- supabase/tests/01_schema.test.sql | 20 +- supabase/tests/36_quick_polls.test.sql | 462 ++++++++++++ 5 files changed, 1870 insertions(+), 61 deletions(-) create mode 100644 supabase/migrations/20261122232215_quick_polls.sql create mode 100644 supabase/tests/36_quick_polls.test.sql diff --git a/packages/api/src/database.types.ts b/packages/api/src/database.types.ts index ed8c4b92..79b0bccd 100644 --- a/packages/api/src/database.types.ts +++ b/packages/api/src/database.types.ts @@ -1585,6 +1585,136 @@ export type Database = { }, ] } + quick_poll_answers: { + Row: { + created_at: string + display_name: string | null + id: string + poll_id: string + saves: number + saves_window_start: string + seat: number + token_hash: string + updated_at: string + } + ComputedFields: never + Insert: { + created_at?: string + display_name?: string | null + id?: string + poll_id: string + saves?: number + saves_window_start?: string + seat: number + token_hash: string + updated_at?: string + } + Update: { + created_at?: string + display_name?: string | null + id?: string + poll_id?: string + saves?: number + saves_window_start?: string + seat?: number + token_hash?: string + updated_at?: string + } + Relationships: [ + { + foreignKeyName: 'quick_poll_answers_poll_id_fkey' + columns: ['poll_id'] + isOneToOne: false + referencedRelation: 'quick_polls' + referencedColumns: ['id'] + }, + ] + } + quick_poll_slots: { + Row: { + answer_id: string + level: Database['public']['Enums']['availability_level'] + slot_start: string + } + ComputedFields: never + Insert: { + answer_id: string + level?: Database['public']['Enums']['availability_level'] + slot_start: string + } + Update: { + answer_id?: string + level?: Database['public']['Enums']['availability_level'] + slot_start?: string + } + Relationships: [ + { + foreignKeyName: 'quick_poll_slots_answer_id_fkey' + columns: ['answer_id'] + isOneToOne: false + referencedRelation: 'quick_poll_answers' + referencedColumns: ['id'] + }, + ] + } + quick_polls: { + Row: { + closed_at: string | null + code: string + created_at: string + creator_token_hash: string + day_end_minute: number + day_start_minute: number + duration_minutes: number + expires_at: string + id: string + max_people: number + names_required: boolean + slot_minutes: number + timezone: string + title: string | null + window_end: string + window_start: string + } + ComputedFields: never + Insert: { + closed_at?: string | null + code?: string + created_at?: string + creator_token_hash: string + day_end_minute: number + day_start_minute: number + duration_minutes: number + expires_at: string + id?: string + max_people?: number + names_required?: boolean + slot_minutes?: number + timezone: string + title?: string | null + window_end: string + window_start: string + } + Update: { + closed_at?: string | null + code?: string + created_at?: string + creator_token_hash?: string + day_end_minute?: number + day_start_minute?: number + duration_minutes?: number + expires_at?: string + id?: string + max_people?: number + names_required?: boolean + slot_minutes?: number + timezone?: string + title?: string | null + window_end?: string + window_start?: string + } + Relationships: [] + } recurring_expenses: { Row: { active: boolean @@ -1891,6 +2021,7 @@ export type Database = { } } clear_mfa_recovery_codes: { Args: Record; Returns: number } + close_quick_poll: { Args: { code: string; token: string }; Returns: undefined } create_expense: { Args: { payload: Json } Returns: { @@ -2128,6 +2259,14 @@ export type Database = { } } create_mfa_recovery_codes: { Args: Record; Returns: string[] } + create_quick_poll: { + Args: { payload: Json } + Returns: { + code: string + creator_token: string + expires_at: string + }[] + } delete_expense: { Args: { id: string } Returns: { @@ -2163,6 +2302,7 @@ export type Database = { } delete_group: { Args: { group_id: string }; Returns: undefined } delete_my_account: { Args: Record; Returns: undefined } + delete_quick_poll: { Args: { code: string; token: string }; Returns: undefined } delete_settlement: { Args: { id: string } Returns: { @@ -2412,6 +2552,25 @@ export type Database = { } notify_mfa_recovered: { Args: { target: string }; Returns: undefined } orphan_receipts: { Args: { max_count?: number }; Returns: string[] } + quick_poll_preview: { + Args: { code: string; token?: string } + Returns: { + answers: Json + day_end_minute: number + day_start_minute: number + duration_minutes: number + expires_at: string + is_creator: boolean + max_people: number + names_required: boolean + slot_minutes: number + status: string + timezone: string + title: string + window_end: string + window_start: string + }[] + } record_mfa_recover_attempt: { Args: { target: string }; Returns: boolean } remind_debt: { Args: { group_id: string; note?: string; user_id: string } @@ -2667,6 +2826,13 @@ export type Database = { Args: { category: string; email?: boolean; push?: boolean } Returns: undefined } + set_quick_poll_availability: { + Args: { code: string; name: string; slots: Json; token: string } + Returns: { + answer_token: string + saved: number + }[] + } settle_all: { Args: { group_id: string; note?: string; settled_on?: string } Returns: { diff --git a/supabase/migrations/20261122232215_quick_polls.sql b/supabase/migrations/20261122232215_quick_polls.sql new file mode 100644 index 00000000..7c4c146c --- /dev/null +++ b/supabase/migrations/20261122232215_quick_polls.sql @@ -0,0 +1,593 @@ +-- Quick polls (ADR 22). Anyone, signed in or not, makes an availability poll, shares its link, +-- and everyone who opens it adds their times and sees everyone else's. No group, no event, no +-- auth user: +-- +-- quick_polls one row per poll: its code, grid, expiry and the sha256 of the +-- creator's token (the browser keeps the token) +-- quick_poll_answers one row per browser that answered, with a seat number (1, 2, +-- 3...) and, when the poll asks for names, a name; a token hash too +-- quick_poll_slots the slots each answer painted, same shape as public.availability +-- private.quick_poll_creates when polls were made and by which client (sha256 of the first +-- x-forwarded-for entry), kept an hour, for the create rate limit +-- +-- Clients never touch the tables (RLS on, no policies, no grants). Everything goes through five +-- security definer RPCs that anon and authenticated may call. A poll's status has one owner, +-- private.quick_poll_status. The slot grid rule has one owner too: the body of +-- private.event_slots (as in 20261113170311_guest_links.sql, live in schema/current.sql) moves +-- into private.grid_slots, and event_slots now hands its event's grid to it. +-- The limits match packages/core/src/quick-polls/limits.ts. + +-- Grid rule --------------------------------------------------------------------------------------- + +-- Parses and checks a slots payload against a grid: the same rules as public.set_availability and +-- buildSlots in packages/core. Returns [{slot_start, level}]. +create or replace function private.grid_slots( + timezone text, + window_start date, + window_end date, + day_start_minute int, + day_end_minute int, + slot_minutes int, + slots jsonb +) +returns jsonb +language plpgsql +stable +set search_path = '' +as $$ +declare + parsed jsonb; +begin + if slots is null or jsonb_typeof(slots) <> 'array' then + raise exception using message = 'invalid_slots', detail = 'Availability is not valid', errcode = '22023'; + end if; + if jsonb_array_length(slots) > 5000 then + raise exception using message = 'invalid_slots', detail = 'Too many slots', errcode = '22023'; + end if; + + begin + select coalesce(jsonb_agg(jsonb_build_object('slot_start', x.slot_start, 'level', x.level)), '[]'::jsonb) + into parsed + from ( + select + (e.elem ->> 'slot_start')::timestamptz as slot_start, + coalesce((e.elem ->> 'level')::public.availability_level, 'yes') as level + from jsonb_array_elements(slots) as e (elem) + ) x; + exception + when invalid_text_representation or invalid_datetime_format or datetime_field_overflow then + raise exception using message = 'invalid_slots', detail = 'Availability is not valid', errcode = '22023'; + end; + + if exists ( + select 1 + from jsonb_to_recordset(parsed) as s (slot_start timestamptz, level public.availability_level) + cross join lateral ( + select (s.slot_start at time zone grid_slots.timezone) as local_ts + ) l + cross join lateral ( + select + l.local_ts::date as day, + (extract(hour from l.local_ts) * 60 + extract(minute from l.local_ts))::int as minute, + extract(second from l.local_ts) as sec + ) t + where s.slot_start is null + or t.day < grid_slots.window_start + or t.day > grid_slots.window_end + or t.sec <> 0 + or t.minute < grid_slots.day_start_minute + or t.minute + grid_slots.slot_minutes > grid_slots.day_end_minute + or (t.minute - grid_slots.day_start_minute) % grid_slots.slot_minutes <> 0 + ) then + raise exception using message = 'invalid_slot', detail = 'Some times are outside the grid', errcode = '22023'; + end if; + + if (select count(*) from jsonb_array_elements(parsed)) <> ( + select count(distinct (s.slot_start)) + from jsonb_to_recordset(parsed) as s (slot_start timestamptz, level public.availability_level) + ) then + raise exception using message = 'duplicate_slot', detail = 'A time appears twice', errcode = '22023'; + end if; + + return parsed; +end; +$$; + +revoke execute on function private.grid_slots(text, date, date, int, int, int, jsonb) from public, anon, authenticated; + +create or replace function private.event_slots(ev public.events, slots jsonb) +returns jsonb +language sql +stable +set search_path = '' +as $$ + select private.grid_slots( + ev.timezone, ev.window_start, ev.window_end, ev.day_start_minute, ev.day_end_minute, ev.slot_minutes, slots + ); +$$; + +-- Tables ------------------------------------------------------------------------------------------ + +create table public.quick_polls ( + id uuid primary key default gen_random_uuid(), + code text not null unique default private.random_code(12), + title text check (char_length(title) between 1 and 80), + timezone text not null check (private.is_time_zone(timezone)), + window_start date not null, + window_end date not null, + day_start_minute int not null check (day_start_minute between 0 and 1439), + day_end_minute int not null check (day_end_minute between 1 and 1440), + slot_minutes int not null default 30 check (slot_minutes in (30, 60)), + duration_minutes int not null check (duration_minutes between 15 and 1440), + names_required boolean not null default true, + max_people int not null default 10 check (max_people between 2 and 15), + creator_token_hash bytea not null, + expires_at timestamptz not null, + closed_at timestamptz, + created_at timestamptz not null default now(), + check (window_end >= window_start and window_end - window_start <= 13), + check (day_end_minute - day_start_minute >= slot_minutes) +); + +comment on table public.quick_polls is + 'Availability polls made without an account (ADR 22). Only the quick poll RPCs read or write them; creator_token_hash is sha256 of the token the creator''s browser keeps.'; + +create index quick_polls_expires_at_idx on public.quick_polls (expires_at); + +create table public.quick_poll_answers ( + id uuid primary key default gen_random_uuid(), + poll_id uuid not null references public.quick_polls (id) on delete cascade, + seat int not null check (seat >= 1), + display_name text check (char_length(display_name) between 1 and 40), + token_hash bytea not null, + saves int not null default 1, + saves_window_start timestamptz not null default now(), + created_at timestamptz not null default now(), + updated_at timestamptz not null default now(), + unique (poll_id, seat), + unique (poll_id, token_hash) +); + +comment on table public.quick_poll_answers is + 'One answer per browser per quick poll. seat numbers the answers 1, 2, 3 in order; display_name is null when the poll does not ask for names. token_hash is sha256 of the browser''s token.'; +comment on column public.quick_poll_answers.saves is + 'Saves since saves_window_start: the per answer rate limit in set_quick_poll_availability.'; + +create table public.quick_poll_slots ( + answer_id uuid not null references public.quick_poll_answers (id) on delete cascade, + slot_start timestamptz not null, + level public.availability_level not null default 'yes', + primary key (answer_id, slot_start) +); + +revoke all on public.quick_polls from anon, authenticated; +revoke all on public.quick_poll_answers from anon, authenticated; +revoke all on public.quick_poll_slots from anon, authenticated; + +grant all on public.quick_polls to service_role; +grant all on public.quick_poll_answers to service_role; +grant all on public.quick_poll_slots to service_role; + +alter table public.quick_polls enable row level security; +alter table public.quick_poll_answers enable row level security; +alter table public.quick_poll_slots enable row level security; + +create table private.quick_poll_creates ( + creator_hash bytea, + created_at timestamptz not null default now() +); + +create index quick_poll_creates_created_at_idx on private.quick_poll_creates (created_at); +create index quick_poll_creates_creator_idx on private.quick_poll_creates (creator_hash, created_at); + +comment on table private.quick_poll_creates is + 'One row per quick poll made, kept an hour, for the create rate limit. creator_hash is sha256 of the first x-forwarded-for entry, null without one. Deleting a poll leaves its row here.'; + +revoke all on table private.quick_poll_creates from public, anon, authenticated; + +-- Helpers ----------------------------------------------------------------------------------------- + +-- sha256 of a browser token, or null for one that cannot be ours (missing, too short, too long). +create or replace function private.quick_poll_token_hash(token text) +returns bytea +language sql +immutable +set search_path = '' +as $$ + select case when char_length(token) between 16 and 200 then sha256(convert_to(token, 'UTF8')) end; +$$; + +-- The one place a quick poll's status is decided, first match wins: +-- expired expires_at has passed +-- closed the creator closed it +-- full every seat is taken and the visitor has not answered +-- open otherwise +create or replace function private.quick_poll_status(poll public.quick_polls, answered boolean) +returns text +language sql +stable +set search_path = '' +as $$ + select case + when poll.expires_at <= now() then 'expired' + when poll.closed_at is not null then 'closed' + when not coalesce(answered, false) + and (select count(*) from public.quick_poll_answers a where a.poll_id = poll.id) >= poll.max_people + then 'full' + else 'open' + end; +$$; + +-- Deletes expired polls (their answers and slots go with them) and create log rows past the hour. +create or replace function private.purge_quick_polls() +returns integer +language plpgsql +security definer +set search_path = '' +as $$ +declare + n int; +begin + delete from public.quick_polls q where q.expires_at <= now(); + get diagnostics n = row_count; + delete from private.quick_poll_creates c where c.created_at <= now() - interval '1 hour'; + return n; +end; +$$; + +revoke execute on function private.quick_poll_token_hash(text) from public, anon, authenticated; +revoke execute on function private.quick_poll_status(public.quick_polls, boolean) from public, anon, authenticated; +revoke execute on function private.purge_quick_polls() from public, anon, authenticated; + +select cron.schedule('purge-quick-polls', '25 * * * *', $$select private.purge_quick_polls()$$); + +-- RPCs, all anon-callable ------------------------------------------------------------------------- + +-- Makes a poll and returns its code and the creator's token, which is also the creator's answer +-- token. payload keys: title (optional, cleaned like guest names, blank means none), timezone, +-- window_start, window_end (1 to 14 days, both included, not all in the past), day_start_minute, +-- day_end_minute (at least one slot apart), duration_minutes (15 to 1440), slot_minutes (30 or +-- 60, default 30), ttl ('24h' or '7d'), names_required (default true), max_people (2 to 15, +-- default 10). +-- Rate limits: 5 polls an hour per client (sha256 of the first x-forwarded-for entry, when there is +-- one) and 200 an hour in all. An advisory lock serializes the counts. +create or replace function public.create_quick_poll(payload jsonb) +returns table (code text, creator_token text, expires_at timestamptz) +language plpgsql +security definer +set search_path = '' +as $$ +#variable_conflict use_column +declare + p jsonb := create_quick_poll.payload; + v_title text; + v_timezone text; + v_window_start date; + v_window_end date; + v_day_start int; + v_day_end int; + v_duration int; + v_slot int; + v_ttl text; + v_names boolean; + v_max int; + headers json; + client bytea; + token text := private.random_code(24); + poll public.quick_polls; +begin + if p is null or jsonb_typeof(p) <> 'object' then + raise exception using message = 'invalid_quick_poll', detail = 'Poll settings are not valid', errcode = '22023'; + end if; + + begin + v_title := nullif(private.clean_guest_name(p ->> 'title'), ''); + v_timezone := p ->> 'timezone'; + v_window_start := (p ->> 'window_start')::date; + v_window_end := (p ->> 'window_end')::date; + v_day_start := (p ->> 'day_start_minute')::int; + v_day_end := (p ->> 'day_end_minute')::int; + v_duration := (p ->> 'duration_minutes')::int; + v_slot := coalesce((p ->> 'slot_minutes')::int, 30); + v_ttl := p ->> 'ttl'; + v_names := coalesce((p ->> 'names_required')::boolean, true); + v_max := coalesce((p ->> 'max_people')::int, 10); + exception + when invalid_text_representation or invalid_datetime_format or datetime_field_overflow + or numeric_value_out_of_range then + raise exception using message = 'invalid_quick_poll', detail = 'Poll settings are not valid', errcode = '22023'; + end; + + if char_length(v_title) > 80 then + raise exception using message = 'invalid_quick_poll_title', detail = 'Titles are up to 80 characters', errcode = '22023'; + end if; + if v_timezone is null or not private.is_time_zone(v_timezone) then + raise exception using message = 'invalid_quick_poll_timezone', detail = 'That time zone is not known', errcode = '22023'; + end if; + if v_window_start is null or v_window_end is null + or v_window_end < v_window_start + or v_window_end - v_window_start > 13 + or v_window_end < (now() at time zone v_timezone)::date then + raise exception using message = 'invalid_quick_poll_window', detail = 'Polls cover 1 to 14 days, not all in the past', errcode = '22023'; + end if; + if v_slot not in (30, 60) then + raise exception using message = 'invalid_quick_poll_slot_minutes', detail = 'Slots are 30 or 60 minutes', errcode = '22023'; + end if; + if v_day_start is null or v_day_end is null + or v_day_start not between 0 and 1439 + or v_day_end not between 1 and 1440 + or v_day_end - v_day_start < v_slot then + raise exception using message = 'invalid_quick_poll_hours', detail = 'The day must end at least one slot after it starts', errcode = '22023'; + end if; + if v_duration is null or v_duration not between 15 and 1440 then + raise exception using message = 'invalid_quick_poll_duration', detail = 'Plans last 15 minutes to 24 hours', errcode = '22023'; + end if; + if v_ttl is null or v_ttl not in ('24h', '7d') then + raise exception using message = 'invalid_quick_poll_ttl', detail = 'Polls last 24 hours or 7 days', errcode = '22023'; + end if; + if v_max not between 2 and 15 then + raise exception using message = 'invalid_quick_poll_people', detail = 'A poll takes 2 to 15 people', errcode = '22023'; + end if; + + -- PostgREST passes the request headers; the first x-forwarded-for entry is the client address + -- (Supabase "Securing your API"). Only its hash is kept, and only for an hour. + headers := nullif(current_setting('request.headers', true), '')::json; + client := sha256(convert_to(nullif(btrim(split_part(headers ->> 'x-forwarded-for', ',', 1)), ''), 'UTF8')); + + perform pg_advisory_xact_lock(hashtextextended('create_quick_poll', 0)); + if client is not null and ( + select count(*) from private.quick_poll_creates c + where c.creator_hash = client and c.created_at > now() - interval '1 hour' + ) >= 5 then + raise exception using message = 'quick_poll_rate_limited', detail = 'Too many polls from here, try again in an hour', errcode = '23514'; + end if; + if ( + select count(*) from private.quick_poll_creates c where c.created_at > now() - interval '1 hour' + ) >= 200 then + raise exception using message = 'quick_poll_rate_limited', detail = 'Too many polls right now, try again later', errcode = '23514'; + end if; + insert into private.quick_poll_creates (creator_hash) values (client); + + insert into public.quick_polls ( + title, timezone, window_start, window_end, day_start_minute, day_end_minute, slot_minutes, + duration_minutes, names_required, max_people, creator_token_hash, expires_at + ) + values ( + v_title, v_timezone, v_window_start, v_window_end, v_day_start, v_day_end, v_slot, + v_duration, v_names, v_max, sha256(convert_to(token, 'UTF8')), + now() + case v_ttl when '24h' then interval '24 hours' else interval '7 days' end + ) + returning * into poll; + + return query select poll.code, token, poll.expires_at; +end; +$$; + +revoke execute on function public.create_quick_poll(jsonb) from public; +grant execute on function public.create_quick_poll(jsonb) to anon, authenticated, service_role; + +-- What a poll link shows. status comes from private.quick_poll_status. An expired poll shows its +-- status only; open, full and closed show the poll, whether the visitor made it, and every answer: +-- answers is [{seat, name, mine, slots: [{slot_start, level}]}] by seat, name null when the poll +-- does not ask for names, never ids or hashes. +create or replace function public.quick_poll_preview(code text, token text default null) +returns table ( + status text, + title text, + timezone text, + window_start date, + window_end date, + day_start_minute int, + day_end_minute int, + slot_minutes int, + duration_minutes int, + names_required boolean, + max_people int, + expires_at timestamptz, + is_creator boolean, + answers jsonb +) +language plpgsql +stable +security definer +set search_path = '' +as $$ +#variable_conflict use_column +declare + poll public.quick_polls; + hashed bytea := private.quick_poll_token_hash(quick_poll_preview.token); + my_id uuid; + st text; +begin + select * into poll from public.quick_polls q where q.code = quick_poll_preview.code; + if poll.id is null then + raise exception using message = 'quick_poll_not_found', detail = 'This poll is not valid', errcode = 'PT404'; + end if; + select a.id into my_id from public.quick_poll_answers a where a.poll_id = poll.id and a.token_hash = hashed; + st := private.quick_poll_status(poll, my_id is not null); + + if st = 'expired' then + return query select st, null::text, null::text, null::date, null::date, null::int, null::int, + null::int, null::int, null::boolean, null::int, null::timestamptz, null::boolean, null::jsonb; + return; + end if; + + return query select + st, + poll.title, + poll.timezone, + poll.window_start, + poll.window_end, + poll.day_start_minute, + poll.day_end_minute, + poll.slot_minutes, + poll.duration_minutes, + poll.names_required, + poll.max_people, + poll.expires_at, + coalesce(hashed = poll.creator_token_hash, false), + ( + select coalesce(jsonb_agg(jsonb_build_object( + 'seat', a.seat, + 'name', case when poll.names_required then a.display_name end, + 'mine', a.id is not distinct from my_id, + 'slots', ( + select coalesce(jsonb_agg(jsonb_build_object('slot_start', s.slot_start, 'level', s.level) order by s.slot_start), '[]'::jsonb) + from public.quick_poll_slots s + where s.answer_id = a.id + ) + ) order by a.seat), '[]'::jsonb) + from public.quick_poll_answers a + where a.poll_id = poll.id + ); +end; +$$; + +revoke execute on function public.quick_poll_preview(text, text) from public; +grant execute on function public.quick_poll_preview(text, text) to anon, authenticated, service_role; + +-- Adds or replaces an answer. A token this poll does not know makes a new answer, if there is a +-- seat, and returns a fresh token for the browser to keep; a known token edits its answer. The +-- creator's token (from create_quick_poll) makes the creator's answer under that same token. The +-- poll row lock serializes seats and the cap. +-- Limits: names 1 to 40 characters once cleaned when the poll asks for names (ignored and stored +-- as null when it does not), a new answer needs at least one slot, 60 saves per answer per hour, +-- max_people answers per poll (an answer already in can still edit a full poll). +create or replace function public.set_quick_poll_availability(code text, name text, token text, slots jsonb) +returns table (answer_token text, saved int) +language plpgsql +security definer +set search_path = '' +as $$ +#variable_conflict use_column +declare + poll public.quick_polls; + me public.quick_poll_answers; + hashed bytea := private.quick_poll_token_hash(set_quick_poll_availability.token); + clean_name text; + parsed jsonb; + fresh_token text; + n int; +begin + select * into poll from public.quick_polls q where q.code = set_quick_poll_availability.code for update; + if poll.id is null then + raise exception using message = 'quick_poll_not_found', detail = 'This poll is not valid', errcode = 'PT404'; + end if; + select * into me from public.quick_poll_answers a where a.poll_id = poll.id and a.token_hash = hashed; + + case private.quick_poll_status(poll, me.id is not null) + when 'expired' then + raise exception using message = 'quick_poll_expired', detail = 'This poll has ended', errcode = '23514'; + when 'closed' then + raise exception using message = 'quick_poll_closed', detail = 'This poll is closed', errcode = '23514'; + when 'full' then + raise exception using message = 'quick_poll_full', detail = 'This poll is full', errcode = '23514'; + else + null; + end case; + + if poll.names_required then + clean_name := private.clean_guest_name(set_quick_poll_availability.name); + if char_length(clean_name) not between 1 and 40 then + raise exception using message = 'invalid_quick_poll_name', detail = 'Names are 1 to 40 characters', errcode = '22023'; + end if; + end if; + + parsed := private.grid_slots( + poll.timezone, poll.window_start, poll.window_end, poll.day_start_minute, poll.day_end_minute, + poll.slot_minutes, set_quick_poll_availability.slots + ); + + if me.id is null then + if jsonb_array_length(parsed) = 0 then + raise exception using message = 'quick_poll_slots_required', detail = 'Pick at least one time', errcode = '22023'; + end if; + if hashed is distinct from poll.creator_token_hash then + fresh_token := private.random_code(24); + hashed := sha256(convert_to(fresh_token, 'UTF8')); + end if; + -- Answers only ever go with their poll, so the next seat is never one used before. + insert into public.quick_poll_answers (poll_id, seat, display_name, token_hash) + values ( + poll.id, + coalesce((select max(a.seat) from public.quick_poll_answers a where a.poll_id = poll.id), 0) + 1, + clean_name, + hashed + ) + returning * into me; + elsif me.saves_window_start > now() - interval '1 hour' then + if me.saves >= 60 then + raise exception using message = 'quick_poll_rate_limited', detail = 'Too many saves, try again later', errcode = '23514'; + end if; + update public.quick_poll_answers a + set saves = a.saves + 1, display_name = clean_name, updated_at = now() + where a.id = me.id; + else + update public.quick_poll_answers a + set saves = 1, saves_window_start = now(), display_name = clean_name, updated_at = now() + where a.id = me.id; + end if; + + delete from public.quick_poll_slots s where s.answer_id = me.id; + insert into public.quick_poll_slots (answer_id, slot_start, level) + select me.id, s.slot_start, s.level + from jsonb_to_recordset(parsed) as s (slot_start timestamptz, level public.availability_level); + get diagnostics n = row_count; + + return query select coalesce(fresh_token, set_quick_poll_availability.token), n; +end; +$$; + +revoke execute on function public.set_quick_poll_availability(text, text, text, jsonb) from public; +grant execute on function public.set_quick_poll_availability(text, text, text, jsonb) to anon, authenticated, service_role; + +-- The creator stops new answers and edits. Results stay readable until the poll expires. Running +-- it again changes nothing. +create or replace function public.close_quick_poll(code text, token text) +returns void +language plpgsql +security definer +set search_path = '' +as $$ +#variable_conflict use_column +declare + poll public.quick_polls; +begin + select * into poll from public.quick_polls q where q.code = close_quick_poll.code for update; + if poll.id is null then + raise exception using message = 'quick_poll_not_found', detail = 'This poll is not valid', errcode = 'PT404'; + end if; + if private.quick_poll_token_hash(close_quick_poll.token) is distinct from poll.creator_token_hash then + raise exception using message = 'not_allowed', detail = 'Only whoever made the poll can close it', errcode = '42501'; + end if; + update public.quick_polls q set closed_at = coalesce(q.closed_at, now()) where q.id = poll.id; +end; +$$; + +revoke execute on function public.close_quick_poll(text, text) from public; +grant execute on function public.close_quick_poll(text, text) to anon, authenticated, service_role; + +-- The creator deletes the poll, its answers and their slots now. +create or replace function public.delete_quick_poll(code text, token text) +returns void +language plpgsql +security definer +set search_path = '' +as $$ +#variable_conflict use_column +declare + poll public.quick_polls; +begin + select * into poll from public.quick_polls q where q.code = delete_quick_poll.code for update; + if poll.id is null then + raise exception using message = 'quick_poll_not_found', detail = 'This poll is not valid', errcode = 'PT404'; + end if; + if private.quick_poll_token_hash(delete_quick_poll.token) is distinct from poll.creator_token_hash then + raise exception using message = 'not_allowed', detail = 'Only whoever made the poll can delete it', errcode = '42501'; + end if; + delete from public.quick_polls q where q.id = poll.id; +end; +$$; + +revoke execute on function public.delete_quick_poll(text, text) from public; +grant execute on function public.delete_quick_poll(text, text) to anon, authenticated, service_role; diff --git a/supabase/schema/current.sql b/supabase/schema/current.sql index 94492211..5d3ebe1a 100644 --- a/supabase/schema/current.sql +++ b/supabase/schema/current.sql @@ -1331,65 +1331,12 @@ COMMENT ON COLUMN "public"."events"."reminder_sent_at" IS 'Set by the hourly rem CREATE OR REPLACE FUNCTION "private"."event_slots"("ev" "public"."events", "slots" "jsonb") RETURNS "jsonb" - LANGUAGE "plpgsql" STABLE + LANGUAGE "sql" STABLE SET "search_path" TO '' AS $$ -declare - parsed jsonb; -begin - if slots is null or jsonb_typeof(slots) <> 'array' then - raise exception using message = 'invalid_slots', detail = 'Availability is not valid', errcode = '22023'; - end if; - if jsonb_array_length(slots) > 5000 then - raise exception using message = 'invalid_slots', detail = 'Too many slots', errcode = '22023'; - end if; - - begin - select coalesce(jsonb_agg(jsonb_build_object('slot_start', x.slot_start, 'level', x.level)), '[]'::jsonb) - into parsed - from ( - select - (e.elem ->> 'slot_start')::timestamptz as slot_start, - coalesce((e.elem ->> 'level')::public.availability_level, 'yes') as level - from jsonb_array_elements(slots) as e (elem) - ) x; - exception - when invalid_text_representation or invalid_datetime_format or datetime_field_overflow then - raise exception using message = 'invalid_slots', detail = 'Availability is not valid', errcode = '22023'; - end; - - if exists ( - select 1 - from jsonb_to_recordset(parsed) as s (slot_start timestamptz, level public.availability_level) - cross join lateral ( - select (s.slot_start at time zone ev.timezone) as local_ts - ) l - cross join lateral ( - select - l.local_ts::date as day, - (extract(hour from l.local_ts) * 60 + extract(minute from l.local_ts))::int as minute, - extract(second from l.local_ts) as sec - ) t - where s.slot_start is null - or t.day < ev.window_start - or t.day > ev.window_end - or t.sec <> 0 - or t.minute < ev.day_start_minute - or t.minute + ev.slot_minutes > ev.day_end_minute - or (t.minute - ev.day_start_minute) % ev.slot_minutes <> 0 - ) then - raise exception using message = 'invalid_slot', detail = 'Some times are outside this event''s grid', errcode = '22023'; - end if; - - if (select count(*) from jsonb_array_elements(parsed)) <> ( - select count(distinct (s.slot_start)) - from jsonb_to_recordset(parsed) as s (slot_start timestamptz, level public.availability_level) - ) then - raise exception using message = 'duplicate_slot', detail = 'A time appears twice', errcode = '22023'; - end if; - - return parsed; -end; + select private.grid_slots( + ev.timezone, ev.window_start, ev.window_end, ev.day_start_minute, ev.day_end_minute, ev.slot_minutes, slots + ); $$; @@ -2089,6 +2036,72 @@ $$; ALTER FUNCTION "private"."fx_rate"("from_currency" character, "to_currency" character, "on_day" "date") OWNER TO "postgres"; +CREATE OR REPLACE FUNCTION "private"."grid_slots"("timezone" "text", "window_start" "date", "window_end" "date", "day_start_minute" integer, "day_end_minute" integer, "slot_minutes" integer, "slots" "jsonb") RETURNS "jsonb" + LANGUAGE "plpgsql" STABLE + SET "search_path" TO '' + AS $$ +declare + parsed jsonb; +begin + if slots is null or jsonb_typeof(slots) <> 'array' then + raise exception using message = 'invalid_slots', detail = 'Availability is not valid', errcode = '22023'; + end if; + if jsonb_array_length(slots) > 5000 then + raise exception using message = 'invalid_slots', detail = 'Too many slots', errcode = '22023'; + end if; + + begin + select coalesce(jsonb_agg(jsonb_build_object('slot_start', x.slot_start, 'level', x.level)), '[]'::jsonb) + into parsed + from ( + select + (e.elem ->> 'slot_start')::timestamptz as slot_start, + coalesce((e.elem ->> 'level')::public.availability_level, 'yes') as level + from jsonb_array_elements(slots) as e (elem) + ) x; + exception + when invalid_text_representation or invalid_datetime_format or datetime_field_overflow then + raise exception using message = 'invalid_slots', detail = 'Availability is not valid', errcode = '22023'; + end; + + if exists ( + select 1 + from jsonb_to_recordset(parsed) as s (slot_start timestamptz, level public.availability_level) + cross join lateral ( + select (s.slot_start at time zone grid_slots.timezone) as local_ts + ) l + cross join lateral ( + select + l.local_ts::date as day, + (extract(hour from l.local_ts) * 60 + extract(minute from l.local_ts))::int as minute, + extract(second from l.local_ts) as sec + ) t + where s.slot_start is null + or t.day < grid_slots.window_start + or t.day > grid_slots.window_end + or t.sec <> 0 + or t.minute < grid_slots.day_start_minute + or t.minute + grid_slots.slot_minutes > grid_slots.day_end_minute + or (t.minute - grid_slots.day_start_minute) % grid_slots.slot_minutes <> 0 + ) then + raise exception using message = 'invalid_slot', detail = 'Some times are outside the grid', errcode = '22023'; + end if; + + if (select count(*) from jsonb_array_elements(parsed)) <> ( + select count(distinct (s.slot_start)) + from jsonb_to_recordset(parsed) as s (slot_start timestamptz, level public.availability_level) + ) then + raise exception using message = 'duplicate_slot', detail = 'A time appears twice', errcode = '22023'; + end if; + + return parsed; +end; +$$; + + +ALTER FUNCTION "private"."grid_slots"("timezone" "text", "window_start" "date", "window_end" "date", "day_start_minute" integer, "day_end_minute" integer, "slot_minutes" integer, "slots" "jsonb") OWNER TO "postgres"; + + CREATE OR REPLACE FUNCTION "private"."group_debts"("gid" "uuid") RETURNS TABLE("from_user" "uuid", "to_user" "uuid", "amount_cents" bigint) LANGUAGE "plpgsql" STABLE SECURITY DEFINER SET "search_path" TO '' @@ -3698,6 +3711,24 @@ $$; ALTER FUNCTION "private"."purge_deleted_groups"("keep" interval) OWNER TO "postgres"; +CREATE OR REPLACE FUNCTION "private"."purge_quick_polls"() RETURNS integer + LANGUAGE "plpgsql" SECURITY DEFINER + SET "search_path" TO '' + AS $$ +declare + n int; +begin + delete from public.quick_polls q where q.expires_at <= now(); + get diagnostics n = row_count; + delete from private.quick_poll_creates c where c.created_at <= now() - interval '1 hour'; + return n; +end; +$$; + + +ALTER FUNCTION "private"."purge_quick_polls"() OWNER TO "postgres"; + + CREATE OR REPLACE FUNCTION "private"."push_notification"() RETURNS "trigger" LANGUAGE "plpgsql" SECURITY DEFINER SET "search_path" TO '' @@ -3752,6 +3783,71 @@ $$; ALTER FUNCTION "private"."random_code"("bytes" integer) OWNER TO "postgres"; +CREATE TABLE IF NOT EXISTS "public"."quick_polls" ( + "id" "uuid" DEFAULT "gen_random_uuid"() NOT NULL, + "code" "text" DEFAULT "private"."random_code"(12) NOT NULL, + "title" "text", + "timezone" "text" NOT NULL, + "window_start" "date" NOT NULL, + "window_end" "date" NOT NULL, + "day_start_minute" integer NOT NULL, + "day_end_minute" integer NOT NULL, + "slot_minutes" integer DEFAULT 30 NOT NULL, + "duration_minutes" integer NOT NULL, + "names_required" boolean DEFAULT true NOT NULL, + "max_people" integer DEFAULT 10 NOT NULL, + "creator_token_hash" "bytea" NOT NULL, + "expires_at" timestamp with time zone NOT NULL, + "closed_at" timestamp with time zone, + "created_at" timestamp with time zone DEFAULT "now"() NOT NULL, + CONSTRAINT "quick_polls_check" CHECK ((("window_end" >= "window_start") AND (("window_end" - "window_start") <= 13))), + CONSTRAINT "quick_polls_check1" CHECK ((("day_end_minute" - "day_start_minute") >= "slot_minutes")), + CONSTRAINT "quick_polls_day_end_minute_check" CHECK ((("day_end_minute" >= 1) AND ("day_end_minute" <= 1440))), + CONSTRAINT "quick_polls_day_start_minute_check" CHECK ((("day_start_minute" >= 0) AND ("day_start_minute" <= 1439))), + CONSTRAINT "quick_polls_duration_minutes_check" CHECK ((("duration_minutes" >= 15) AND ("duration_minutes" <= 1440))), + CONSTRAINT "quick_polls_max_people_check" CHECK ((("max_people" >= 2) AND ("max_people" <= 15))), + CONSTRAINT "quick_polls_slot_minutes_check" CHECK (("slot_minutes" = ANY (ARRAY[30, 60]))), + CONSTRAINT "quick_polls_timezone_check" CHECK ("private"."is_time_zone"("timezone")), + CONSTRAINT "quick_polls_title_check" CHECK ((("char_length"("title") >= 1) AND ("char_length"("title") <= 80))) +); + + +ALTER TABLE "public"."quick_polls" OWNER TO "postgres"; + + +COMMENT ON TABLE "public"."quick_polls" IS 'Availability polls made without an account (ADR 22). Only the quick poll RPCs read or write them; creator_token_hash is sha256 of the token the creator''s browser keeps.'; + + + +CREATE OR REPLACE FUNCTION "private"."quick_poll_status"("poll" "public"."quick_polls", "answered" boolean) RETURNS "text" + LANGUAGE "sql" STABLE + SET "search_path" TO '' + AS $$ + select case + when poll.expires_at <= now() then 'expired' + when poll.closed_at is not null then 'closed' + when not coalesce(answered, false) + and (select count(*) from public.quick_poll_answers a where a.poll_id = poll.id) >= poll.max_people + then 'full' + else 'open' + end; +$$; + + +ALTER FUNCTION "private"."quick_poll_status"("poll" "public"."quick_polls", "answered" boolean) OWNER TO "postgres"; + + +CREATE OR REPLACE FUNCTION "private"."quick_poll_token_hash"("token" "text") RETURNS "bytea" + LANGUAGE "sql" IMMUTABLE + SET "search_path" TO '' + AS $$ + select case when char_length(token) between 16 and 200 then sha256(convert_to(token, 'UTF8')) end; +$$; + + +ALTER FUNCTION "private"."quick_poll_token_hash"("token" "text") OWNER TO "postgres"; + + CREATE OR REPLACE FUNCTION "private"."receipt_content_type"("file_path" "text") RETURNS "text" LANGUAGE "sql" STABLE SECURITY DEFINER SET "search_path" TO '' @@ -5992,6 +6088,29 @@ $$; ALTER FUNCTION "public"."clear_mfa_recovery_codes"() OWNER TO "postgres"; +CREATE OR REPLACE FUNCTION "public"."close_quick_poll"("code" "text", "token" "text") RETURNS "void" + LANGUAGE "plpgsql" SECURITY DEFINER + SET "search_path" TO '' + AS $$ +#variable_conflict use_column +declare + poll public.quick_polls; +begin + select * into poll from public.quick_polls q where q.code = close_quick_poll.code for update; + if poll.id is null then + raise exception using message = 'quick_poll_not_found', detail = 'This poll is not valid', errcode = 'PT404'; + end if; + if private.quick_poll_token_hash(close_quick_poll.token) is distinct from poll.creator_token_hash then + raise exception using message = 'not_allowed', detail = 'Only whoever made the poll can close it', errcode = '42501'; + end if; + update public.quick_polls q set closed_at = coalesce(q.closed_at, now()) where q.id = poll.id; +end; +$$; + + +ALTER FUNCTION "public"."close_quick_poll"("code" "text", "token" "text") OWNER TO "postgres"; + + CREATE OR REPLACE FUNCTION "public"."create_expense"("payload" "jsonb") RETURNS "public"."expenses" LANGUAGE "sql" SECURITY DEFINER SET "search_path" TO '' @@ -6439,6 +6558,120 @@ $$; ALTER FUNCTION "public"."create_mfa_recovery_codes"() OWNER TO "postgres"; +CREATE OR REPLACE FUNCTION "public"."create_quick_poll"("payload" "jsonb") RETURNS TABLE("code" "text", "creator_token" "text", "expires_at" timestamp with time zone) + LANGUAGE "plpgsql" SECURITY DEFINER + SET "search_path" TO '' + AS $$ +#variable_conflict use_column +declare + p jsonb := create_quick_poll.payload; + v_title text; + v_timezone text; + v_window_start date; + v_window_end date; + v_day_start int; + v_day_end int; + v_duration int; + v_slot int; + v_ttl text; + v_names boolean; + v_max int; + headers json; + client bytea; + token text := private.random_code(24); + poll public.quick_polls; +begin + if p is null or jsonb_typeof(p) <> 'object' then + raise exception using message = 'invalid_quick_poll', detail = 'Poll settings are not valid', errcode = '22023'; + end if; + + begin + v_title := nullif(private.clean_guest_name(p ->> 'title'), ''); + v_timezone := p ->> 'timezone'; + v_window_start := (p ->> 'window_start')::date; + v_window_end := (p ->> 'window_end')::date; + v_day_start := (p ->> 'day_start_minute')::int; + v_day_end := (p ->> 'day_end_minute')::int; + v_duration := (p ->> 'duration_minutes')::int; + v_slot := coalesce((p ->> 'slot_minutes')::int, 30); + v_ttl := p ->> 'ttl'; + v_names := coalesce((p ->> 'names_required')::boolean, true); + v_max := coalesce((p ->> 'max_people')::int, 10); + exception + when invalid_text_representation or invalid_datetime_format or datetime_field_overflow + or numeric_value_out_of_range then + raise exception using message = 'invalid_quick_poll', detail = 'Poll settings are not valid', errcode = '22023'; + end; + + if char_length(v_title) > 80 then + raise exception using message = 'invalid_quick_poll_title', detail = 'Titles are up to 80 characters', errcode = '22023'; + end if; + if v_timezone is null or not private.is_time_zone(v_timezone) then + raise exception using message = 'invalid_quick_poll_timezone', detail = 'That time zone is not known', errcode = '22023'; + end if; + if v_window_start is null or v_window_end is null + or v_window_end < v_window_start + or v_window_end - v_window_start > 13 + or v_window_end < (now() at time zone v_timezone)::date then + raise exception using message = 'invalid_quick_poll_window', detail = 'Polls cover 1 to 14 days, not all in the past', errcode = '22023'; + end if; + if v_slot not in (30, 60) then + raise exception using message = 'invalid_quick_poll_slot_minutes', detail = 'Slots are 30 or 60 minutes', errcode = '22023'; + end if; + if v_day_start is null or v_day_end is null + or v_day_start not between 0 and 1439 + or v_day_end not between 1 and 1440 + or v_day_end - v_day_start < v_slot then + raise exception using message = 'invalid_quick_poll_hours', detail = 'The day must end at least one slot after it starts', errcode = '22023'; + end if; + if v_duration is null or v_duration not between 15 and 1440 then + raise exception using message = 'invalid_quick_poll_duration', detail = 'Plans last 15 minutes to 24 hours', errcode = '22023'; + end if; + if v_ttl is null or v_ttl not in ('24h', '7d') then + raise exception using message = 'invalid_quick_poll_ttl', detail = 'Polls last 24 hours or 7 days', errcode = '22023'; + end if; + if v_max not between 2 and 15 then + raise exception using message = 'invalid_quick_poll_people', detail = 'A poll takes 2 to 15 people', errcode = '22023'; + end if; + + -- PostgREST passes the request headers; the first x-forwarded-for entry is the client address + -- (Supabase "Securing your API"). Only its hash is kept, and only for an hour. + headers := nullif(current_setting('request.headers', true), '')::json; + client := sha256(convert_to(nullif(btrim(split_part(headers ->> 'x-forwarded-for', ',', 1)), ''), 'UTF8')); + + perform pg_advisory_xact_lock(hashtextextended('create_quick_poll', 0)); + if client is not null and ( + select count(*) from private.quick_poll_creates c + where c.creator_hash = client and c.created_at > now() - interval '1 hour' + ) >= 5 then + raise exception using message = 'quick_poll_rate_limited', detail = 'Too many polls from here, try again in an hour', errcode = '23514'; + end if; + if ( + select count(*) from private.quick_poll_creates c where c.created_at > now() - interval '1 hour' + ) >= 200 then + raise exception using message = 'quick_poll_rate_limited', detail = 'Too many polls right now, try again later', errcode = '23514'; + end if; + insert into private.quick_poll_creates (creator_hash) values (client); + + insert into public.quick_polls ( + title, timezone, window_start, window_end, day_start_minute, day_end_minute, slot_minutes, + duration_minutes, names_required, max_people, creator_token_hash, expires_at + ) + values ( + v_title, v_timezone, v_window_start, v_window_end, v_day_start, v_day_end, v_slot, + v_duration, v_names, v_max, sha256(convert_to(token, 'UTF8')), + now() + case v_ttl when '24h' then interval '24 hours' else interval '7 days' end + ) + returning * into poll; + + return query select poll.code, token, poll.expires_at; +end; +$$; + + +ALTER FUNCTION "public"."create_quick_poll"("payload" "jsonb") OWNER TO "postgres"; + + CREATE OR REPLACE FUNCTION "public"."delete_expense"("id" "uuid") RETURNS "public"."expenses" LANGUAGE "plpgsql" SECURITY DEFINER SET "search_path" TO '' @@ -6608,6 +6841,29 @@ $$; ALTER FUNCTION "public"."delete_my_account"() OWNER TO "postgres"; +CREATE OR REPLACE FUNCTION "public"."delete_quick_poll"("code" "text", "token" "text") RETURNS "void" + LANGUAGE "plpgsql" SECURITY DEFINER + SET "search_path" TO '' + AS $$ +#variable_conflict use_column +declare + poll public.quick_polls; +begin + select * into poll from public.quick_polls q where q.code = delete_quick_poll.code for update; + if poll.id is null then + raise exception using message = 'quick_poll_not_found', detail = 'This poll is not valid', errcode = 'PT404'; + end if; + if private.quick_poll_token_hash(delete_quick_poll.token) is distinct from poll.creator_token_hash then + raise exception using message = 'not_allowed', detail = 'Only whoever made the poll can delete it', errcode = '42501'; + end if; + delete from public.quick_polls q where q.id = poll.id; +end; +$$; + + +ALTER FUNCTION "public"."delete_quick_poll"("code" "text", "token" "text") OWNER TO "postgres"; + + CREATE TABLE IF NOT EXISTS "public"."settlements" ( "id" "uuid" DEFAULT "gen_random_uuid"() NOT NULL, "group_id" "uuid" NOT NULL, @@ -8293,6 +8549,65 @@ $$; ALTER FUNCTION "public"."orphan_receipts"("max_count" integer) OWNER TO "postgres"; +CREATE OR REPLACE FUNCTION "public"."quick_poll_preview"("code" "text", "token" "text" DEFAULT NULL::"text") RETURNS TABLE("status" "text", "title" "text", "timezone" "text", "window_start" "date", "window_end" "date", "day_start_minute" integer, "day_end_minute" integer, "slot_minutes" integer, "duration_minutes" integer, "names_required" boolean, "max_people" integer, "expires_at" timestamp with time zone, "is_creator" boolean, "answers" "jsonb") + LANGUAGE "plpgsql" STABLE SECURITY DEFINER + SET "search_path" TO '' + AS $$ +#variable_conflict use_column +declare + poll public.quick_polls; + hashed bytea := private.quick_poll_token_hash(quick_poll_preview.token); + my_id uuid; + st text; +begin + select * into poll from public.quick_polls q where q.code = quick_poll_preview.code; + if poll.id is null then + raise exception using message = 'quick_poll_not_found', detail = 'This poll is not valid', errcode = 'PT404'; + end if; + select a.id into my_id from public.quick_poll_answers a where a.poll_id = poll.id and a.token_hash = hashed; + st := private.quick_poll_status(poll, my_id is not null); + + if st = 'expired' then + return query select st, null::text, null::text, null::date, null::date, null::int, null::int, + null::int, null::int, null::boolean, null::int, null::timestamptz, null::boolean, null::jsonb; + return; + end if; + + return query select + st, + poll.title, + poll.timezone, + poll.window_start, + poll.window_end, + poll.day_start_minute, + poll.day_end_minute, + poll.slot_minutes, + poll.duration_minutes, + poll.names_required, + poll.max_people, + poll.expires_at, + coalesce(hashed = poll.creator_token_hash, false), + ( + select coalesce(jsonb_agg(jsonb_build_object( + 'seat', a.seat, + 'name', case when poll.names_required then a.display_name end, + 'mine', a.id is not distinct from my_id, + 'slots', ( + select coalesce(jsonb_agg(jsonb_build_object('slot_start', s.slot_start, 'level', s.level) order by s.slot_start), '[]'::jsonb) + from public.quick_poll_slots s + where s.answer_id = a.id + ) + ) order by a.seat), '[]'::jsonb) + from public.quick_poll_answers a + where a.poll_id = poll.id + ); +end; +$$; + + +ALTER FUNCTION "public"."quick_poll_preview"("code" "text", "token" "text") OWNER TO "postgres"; + + CREATE OR REPLACE FUNCTION "public"."record_mfa_recover_attempt"("target" "uuid") RETURNS boolean LANGUAGE "plpgsql" SECURITY DEFINER SET "search_path" TO '' @@ -9562,6 +9877,93 @@ $$; ALTER FUNCTION "public"."set_notification_pref"("category" "text", "push" boolean, "email" boolean) OWNER TO "postgres"; +CREATE OR REPLACE FUNCTION "public"."set_quick_poll_availability"("code" "text", "name" "text", "token" "text", "slots" "jsonb") RETURNS TABLE("answer_token" "text", "saved" integer) + LANGUAGE "plpgsql" SECURITY DEFINER + SET "search_path" TO '' + AS $$ +#variable_conflict use_column +declare + poll public.quick_polls; + me public.quick_poll_answers; + hashed bytea := private.quick_poll_token_hash(set_quick_poll_availability.token); + clean_name text; + parsed jsonb; + fresh_token text; + n int; +begin + select * into poll from public.quick_polls q where q.code = set_quick_poll_availability.code for update; + if poll.id is null then + raise exception using message = 'quick_poll_not_found', detail = 'This poll is not valid', errcode = 'PT404'; + end if; + select * into me from public.quick_poll_answers a where a.poll_id = poll.id and a.token_hash = hashed; + + case private.quick_poll_status(poll, me.id is not null) + when 'expired' then + raise exception using message = 'quick_poll_expired', detail = 'This poll has ended', errcode = '23514'; + when 'closed' then + raise exception using message = 'quick_poll_closed', detail = 'This poll is closed', errcode = '23514'; + when 'full' then + raise exception using message = 'quick_poll_full', detail = 'This poll is full', errcode = '23514'; + else + null; + end case; + + if poll.names_required then + clean_name := private.clean_guest_name(set_quick_poll_availability.name); + if char_length(clean_name) not between 1 and 40 then + raise exception using message = 'invalid_quick_poll_name', detail = 'Names are 1 to 40 characters', errcode = '22023'; + end if; + end if; + + parsed := private.grid_slots( + poll.timezone, poll.window_start, poll.window_end, poll.day_start_minute, poll.day_end_minute, + poll.slot_minutes, set_quick_poll_availability.slots + ); + + if me.id is null then + if jsonb_array_length(parsed) = 0 then + raise exception using message = 'quick_poll_slots_required', detail = 'Pick at least one time', errcode = '22023'; + end if; + if hashed is distinct from poll.creator_token_hash then + fresh_token := private.random_code(24); + hashed := sha256(convert_to(fresh_token, 'UTF8')); + end if; + -- Answers only ever go with their poll, so the next seat is never one used before. + insert into public.quick_poll_answers (poll_id, seat, display_name, token_hash) + values ( + poll.id, + coalesce((select max(a.seat) from public.quick_poll_answers a where a.poll_id = poll.id), 0) + 1, + clean_name, + hashed + ) + returning * into me; + elsif me.saves_window_start > now() - interval '1 hour' then + if me.saves >= 60 then + raise exception using message = 'quick_poll_rate_limited', detail = 'Too many saves, try again later', errcode = '23514'; + end if; + update public.quick_poll_answers a + set saves = a.saves + 1, display_name = clean_name, updated_at = now() + where a.id = me.id; + else + update public.quick_poll_answers a + set saves = 1, saves_window_start = now(), display_name = clean_name, updated_at = now() + where a.id = me.id; + end if; + + delete from public.quick_poll_slots s where s.answer_id = me.id; + insert into public.quick_poll_slots (answer_id, slot_start, level) + select me.id, s.slot_start, s.level + from jsonb_to_recordset(parsed) as s (slot_start timestamptz, level public.availability_level); + get diagnostics n = row_count; + + return query select coalesce(fresh_token, set_quick_poll_availability.token), n; +end; +$$; + + +ALTER FUNCTION "public"."set_quick_poll_availability"("code" "text", "name" "text", "token" "text", "slots" "jsonb") OWNER TO "postgres"; + + CREATE OR REPLACE FUNCTION "public"."settle_all"("group_id" "uuid", "settled_on" "date" DEFAULT NULL::"date", "note" "text" DEFAULT NULL::"text") RETURNS SETOF "public"."settlements" LANGUAGE "plpgsql" SECURITY DEFINER SET "search_path" TO '' @@ -10828,6 +11230,19 @@ COMMENT ON TABLE "private"."notification_types" IS 'Which setting governs each n +CREATE TABLE IF NOT EXISTS "private"."quick_poll_creates" ( + "creator_hash" "bytea", + "created_at" timestamp with time zone DEFAULT "now"() NOT NULL +); + + +ALTER TABLE "private"."quick_poll_creates" OWNER TO "postgres"; + + +COMMENT ON TABLE "private"."quick_poll_creates" IS 'One row per quick poll made, kept an hour, for the create rate limit. creator_hash is sha256 of the first x-forwarded-for entry, null without one. Deleting a poll leaves its row here.'; + + + CREATE TABLE IF NOT EXISTS "private"."recurring_heads_ups" ( "recurring_id" "uuid" NOT NULL, "posts_on" "date" NOT NULL, @@ -11477,6 +11892,42 @@ CREATE TABLE IF NOT EXISTS "public"."push_tokens" ( ALTER TABLE "public"."push_tokens" OWNER TO "postgres"; +CREATE TABLE IF NOT EXISTS "public"."quick_poll_answers" ( + "id" "uuid" DEFAULT "gen_random_uuid"() NOT NULL, + "poll_id" "uuid" NOT NULL, + "seat" integer NOT NULL, + "display_name" "text", + "token_hash" "bytea" NOT NULL, + "saves" integer DEFAULT 1 NOT NULL, + "saves_window_start" timestamp with time zone DEFAULT "now"() NOT NULL, + "created_at" timestamp with time zone DEFAULT "now"() NOT NULL, + "updated_at" timestamp with time zone DEFAULT "now"() NOT NULL, + CONSTRAINT "quick_poll_answers_display_name_check" CHECK ((("char_length"("display_name") >= 1) AND ("char_length"("display_name") <= 40))), + CONSTRAINT "quick_poll_answers_seat_check" CHECK (("seat" >= 1)) +); + + +ALTER TABLE "public"."quick_poll_answers" OWNER TO "postgres"; + + +COMMENT ON TABLE "public"."quick_poll_answers" IS 'One answer per browser per quick poll. seat numbers the answers 1, 2, 3 in order; display_name is null when the poll does not ask for names. token_hash is sha256 of the browser''s token.'; + + + +COMMENT ON COLUMN "public"."quick_poll_answers"."saves" IS 'Saves since saves_window_start: the per answer rate limit in set_quick_poll_availability.'; + + + +CREATE TABLE IF NOT EXISTS "public"."quick_poll_slots" ( + "answer_id" "uuid" NOT NULL, + "slot_start" timestamp with time zone NOT NULL, + "level" "public"."availability_level" DEFAULT 'yes'::"public"."availability_level" NOT NULL +); + + +ALTER TABLE "public"."quick_poll_slots" OWNER TO "postgres"; + + CREATE TABLE IF NOT EXISTS "public"."reports" ( "id" "uuid" DEFAULT "gen_random_uuid"() NOT NULL, "reporter_id" "uuid" DEFAULT "auth"."uid"() NOT NULL, @@ -11787,6 +12238,36 @@ ALTER TABLE ONLY "public"."push_tokens" +ALTER TABLE ONLY "public"."quick_poll_answers" + ADD CONSTRAINT "quick_poll_answers_pkey" PRIMARY KEY ("id"); + + + +ALTER TABLE ONLY "public"."quick_poll_answers" + ADD CONSTRAINT "quick_poll_answers_poll_id_seat_key" UNIQUE ("poll_id", "seat"); + + + +ALTER TABLE ONLY "public"."quick_poll_answers" + ADD CONSTRAINT "quick_poll_answers_poll_id_token_hash_key" UNIQUE ("poll_id", "token_hash"); + + + +ALTER TABLE ONLY "public"."quick_poll_slots" + ADD CONSTRAINT "quick_poll_slots_pkey" PRIMARY KEY ("answer_id", "slot_start"); + + + +ALTER TABLE ONLY "public"."quick_polls" + ADD CONSTRAINT "quick_polls_code_key" UNIQUE ("code"); + + + +ALTER TABLE ONLY "public"."quick_polls" + ADD CONSTRAINT "quick_polls_pkey" PRIMARY KEY ("id"); + + + ALTER TABLE ONLY "public"."recurring_expenses" ADD CONSTRAINT "recurring_expenses_pkey" PRIMARY KEY ("id"); @@ -11846,6 +12327,14 @@ CREATE INDEX "notification_types_category_idx" ON "private"."notification_types" +CREATE INDEX "quick_poll_creates_created_at_idx" ON "private"."quick_poll_creates" USING "btree" ("created_at"); + + + +CREATE INDEX "quick_poll_creates_creator_idx" ON "private"."quick_poll_creates" USING "btree" ("creator_hash", "created_at"); + + + CREATE INDEX "recurring_heads_ups_user_id_idx" ON "private"."recurring_heads_ups" USING "btree" ("user_id"); @@ -12098,6 +12587,10 @@ CREATE INDEX "profiles_placeholder_idx" ON "public"."profiles" USING "btree" ("i +CREATE INDEX "quick_polls_expires_at_idx" ON "public"."quick_polls" USING "btree" ("expires_at"); + + + CREATE INDEX "recurring_expenses_created_by_idx" ON "public"."recurring_expenses" USING "btree" ("created_by"); @@ -12833,6 +13326,16 @@ ALTER TABLE ONLY "public"."push_tokens" +ALTER TABLE ONLY "public"."quick_poll_answers" + ADD CONSTRAINT "quick_poll_answers_poll_id_fkey" FOREIGN KEY ("poll_id") REFERENCES "public"."quick_polls"("id") ON DELETE CASCADE; + + + +ALTER TABLE ONLY "public"."quick_poll_slots" + ADD CONSTRAINT "quick_poll_slots_answer_id_fkey" FOREIGN KEY ("answer_id") REFERENCES "public"."quick_poll_answers"("id") ON DELETE CASCADE; + + + ALTER TABLE ONLY "public"."recurring_expenses" ADD CONSTRAINT "recurring_expenses_created_by_fkey" FOREIGN KEY ("created_by") REFERENCES "public"."profiles"("id") ON DELETE SET NULL; @@ -13310,6 +13813,15 @@ CREATE POLICY "push_tokens: update own" ON "public"."push_tokens" FOR UPDATE TO +ALTER TABLE "public"."quick_poll_answers" ENABLE ROW LEVEL SECURITY; + + +ALTER TABLE "public"."quick_poll_slots" ENABLE ROW LEVEL SECURITY; + + +ALTER TABLE "public"."quick_polls" ENABLE ROW LEVEL SECURITY; + + ALTER TABLE "public"."recurring_expenses" ENABLE ROW LEVEL SECURITY; @@ -13576,6 +14088,10 @@ REVOKE ALL ON FUNCTION "private"."freeze_blocked_direct_money"() FROM PUBLIC; +REVOKE ALL ON FUNCTION "private"."grid_slots"("timezone" "text", "window_start" "date", "window_end" "date", "day_start_minute" integer, "day_end_minute" integer, "slot_minutes" integer, "slots" "jsonb") FROM PUBLIC; + + + REVOKE ALL ON FUNCTION "private"."group_debts"("gid" "uuid") FROM PUBLIC; @@ -13807,6 +14323,10 @@ REVOKE ALL ON FUNCTION "private"."purge_deleted_groups"("keep" interval) FROM PU +REVOKE ALL ON FUNCTION "private"."purge_quick_polls"() FROM PUBLIC; + + + REVOKE ALL ON FUNCTION "private"."push_notification"() FROM PUBLIC; @@ -13815,6 +14335,18 @@ REVOKE ALL ON FUNCTION "private"."queue_email"() FROM PUBLIC; +GRANT ALL ON TABLE "public"."quick_polls" TO "service_role"; + + + +REVOKE ALL ON FUNCTION "private"."quick_poll_status"("poll" "public"."quick_polls", "answered" boolean) FROM PUBLIC; + + + +REVOKE ALL ON FUNCTION "private"."quick_poll_token_hash"("token" "text") FROM PUBLIC; + + + REVOKE ALL ON FUNCTION "private"."receipt_content_type"("file_path" "text") FROM PUBLIC; @@ -14046,6 +14578,13 @@ GRANT ALL ON FUNCTION "public"."clear_mfa_recovery_codes"() TO "service_role"; +REVOKE ALL ON FUNCTION "public"."close_quick_poll"("code" "text", "token" "text") FROM PUBLIC; +GRANT ALL ON FUNCTION "public"."close_quick_poll"("code" "text", "token" "text") TO "anon"; +GRANT ALL ON FUNCTION "public"."close_quick_poll"("code" "text", "token" "text") TO "authenticated"; +GRANT ALL ON FUNCTION "public"."close_quick_poll"("code" "text", "token" "text") TO "service_role"; + + + REVOKE ALL ON FUNCTION "public"."create_expense"("payload" "jsonb") FROM PUBLIC; GRANT ALL ON FUNCTION "public"."create_expense"("payload" "jsonb") TO "authenticated"; GRANT ALL ON FUNCTION "public"."create_expense"("payload" "jsonb") TO "service_role"; @@ -14203,6 +14742,13 @@ GRANT ALL ON FUNCTION "public"."create_mfa_recovery_codes"() TO "service_role"; +REVOKE ALL ON FUNCTION "public"."create_quick_poll"("payload" "jsonb") FROM PUBLIC; +GRANT ALL ON FUNCTION "public"."create_quick_poll"("payload" "jsonb") TO "anon"; +GRANT ALL ON FUNCTION "public"."create_quick_poll"("payload" "jsonb") TO "authenticated"; +GRANT ALL ON FUNCTION "public"."create_quick_poll"("payload" "jsonb") TO "service_role"; + + + REVOKE ALL ON FUNCTION "public"."delete_expense"("id" "uuid") FROM PUBLIC; GRANT ALL ON FUNCTION "public"."delete_expense"("id" "uuid") TO "authenticated"; GRANT ALL ON FUNCTION "public"."delete_expense"("id" "uuid") TO "service_role"; @@ -14221,6 +14767,13 @@ GRANT ALL ON FUNCTION "public"."delete_my_account"() TO "service_role"; +REVOKE ALL ON FUNCTION "public"."delete_quick_poll"("code" "text", "token" "text") FROM PUBLIC; +GRANT ALL ON FUNCTION "public"."delete_quick_poll"("code" "text", "token" "text") TO "anon"; +GRANT ALL ON FUNCTION "public"."delete_quick_poll"("code" "text", "token" "text") TO "authenticated"; +GRANT ALL ON FUNCTION "public"."delete_quick_poll"("code" "text", "token" "text") TO "service_role"; + + + GRANT ALL ON TABLE "public"."settlements" TO "service_role"; GRANT SELECT ON TABLE "public"."settlements" TO "authenticated"; @@ -14382,6 +14935,13 @@ GRANT ALL ON FUNCTION "public"."orphan_receipts"("max_count" integer) TO "servic +REVOKE ALL ON FUNCTION "public"."quick_poll_preview"("code" "text", "token" "text") FROM PUBLIC; +GRANT ALL ON FUNCTION "public"."quick_poll_preview"("code" "text", "token" "text") TO "anon"; +GRANT ALL ON FUNCTION "public"."quick_poll_preview"("code" "text", "token" "text") TO "authenticated"; +GRANT ALL ON FUNCTION "public"."quick_poll_preview"("code" "text", "token" "text") TO "service_role"; + + + REVOKE ALL ON FUNCTION "public"."record_mfa_recover_attempt"("target" "uuid") FROM PUBLIC; GRANT ALL ON FUNCTION "public"."record_mfa_recover_attempt"("target" "uuid") TO "service_role"; @@ -14604,6 +15164,13 @@ GRANT ALL ON FUNCTION "public"."set_notification_pref"("category" "text", "push" +REVOKE ALL ON FUNCTION "public"."set_quick_poll_availability"("code" "text", "name" "text", "token" "text", "slots" "jsonb") FROM PUBLIC; +GRANT ALL ON FUNCTION "public"."set_quick_poll_availability"("code" "text", "name" "text", "token" "text", "slots" "jsonb") TO "anon"; +GRANT ALL ON FUNCTION "public"."set_quick_poll_availability"("code" "text", "name" "text", "token" "text", "slots" "jsonb") TO "authenticated"; +GRANT ALL ON FUNCTION "public"."set_quick_poll_availability"("code" "text", "name" "text", "token" "text", "slots" "jsonb") TO "service_role"; + + + REVOKE ALL ON FUNCTION "public"."settle_all"("group_id" "uuid", "settled_on" "date", "note" "text") FROM PUBLIC; GRANT ALL ON FUNCTION "public"."settle_all"("group_id" "uuid", "settled_on" "date", "note" "text") TO "authenticated"; GRANT ALL ON FUNCTION "public"."settle_all"("group_id" "uuid", "settled_on" "date", "note" "text") TO "service_role"; @@ -15001,6 +15568,14 @@ GRANT SELECT,INSERT,DELETE,UPDATE ON TABLE "public"."push_tokens" TO "authentica +GRANT ALL ON TABLE "public"."quick_poll_answers" TO "service_role"; + + + +GRANT ALL ON TABLE "public"."quick_poll_slots" TO "service_role"; + + + GRANT ALL ON TABLE "public"."reports" TO "service_role"; GRANT SELECT,INSERT ON TABLE "public"."reports" TO "authenticated"; @@ -15059,5 +15634,6 @@ ALTER PUBLICATION "supabase_realtime" ADD TABLE ONLY "public"."settlements"; -- cron purge-deleted-groups '20 3 * * *': select private.purge_deleted_groups() -- cron purge-import-batches '*/15 * * * *': delete from private.import_batches where created_at < now() - interval '1 hour' -- cron purge-invite-sends '20 3 * * *': delete from private.invite_sends where sent_at < now() - interval '7 days' +-- cron purge-quick-polls '25 * * * *': select private.purge_quick_polls() -- cron receipts-sweep '40 3 * * *': select private.invoke_edge_function('receipts-sweep') -- cron recurring-heads-up '5,35 * * * *': select private.send_recurring_heads_ups() diff --git a/supabase/tests/01_schema.test.sql b/supabase/tests/01_schema.test.sql index 55a1cd05..8ed305b7 100644 --- a/supabase/tests/01_schema.test.sql +++ b/supabase/tests/01_schema.test.sql @@ -10,7 +10,7 @@ -- new cron job -> a cron.job check -- Count the assertions and update plan(N); finish() fails when it is off. begin; -select plan(132); +select plan(138); select tables_are('public', array[ 'profiles', 'friendships', 'blocks', 'reports', @@ -22,7 +22,8 @@ select tables_are('public', array[ 'activity', 'comments', 'notifications', 'push_tokens', 'app_config', 'calendar_feed_tokens', 'notification_prefs', 'event_guest_links', 'event_guests', 'event_guest_availability', - 'placeholders', 'friend_invites', 'group_whiteboards' + 'placeholders', 'friend_invites', 'group_whiteboards', + 'quick_polls', 'quick_poll_answers', 'quick_poll_slots' ], 'public has exactly the documented tables'); select views_are('public', array['group_balances', 'expense_ledger'], 'public has the balances and ledger views'); @@ -142,6 +143,11 @@ select has_function('public', 'revoke_guest_link', array['uuid'], 'revoke_guest_ select has_function('public', 'remove_guest_answer', array['uuid'], 'remove_guest_answer(guest_id)'); select has_function('public', 'guest_link_preview', array['text', 'text'], 'guest_link_preview(code, token)'); select has_function('public', 'set_guest_availability', array['text', 'text', 'text', 'jsonb'], 'set_guest_availability(code, name, token, slots)'); +select has_function('public', 'create_quick_poll', array['jsonb'], 'create_quick_poll(payload)'); +select has_function('public', 'quick_poll_preview', array['text', 'text'], 'quick_poll_preview(code, token)'); +select has_function('public', 'set_quick_poll_availability', array['text', 'text', 'text', 'jsonb'], 'set_quick_poll_availability(code, name, token, slots)'); +select has_function('public', 'close_quick_poll', array['text', 'text'], 'close_quick_poll(code, token)'); +select has_function('public', 'delete_quick_poll', array['text', 'text'], 'delete_quick_poll(code, token)'); select is( (select count(*)::int from pg_proc p @@ -155,8 +161,10 @@ select is( (select array_agg(p.proname::text order by p.proname) from pg_proc p where p.pronamespace = 'public'::regnamespace and p.prokind = 'f' and has_function_privilege('anon', p.oid, 'execute')), - array['email_unsubscribe', 'friend_invite_preview', 'guest_link_preview', 'invite_preview', 'invite_preview_v2', 'set_guest_availability'], - 'anon can only execute the invite previews, email_unsubscribe and the guest link RPCs' + array['close_quick_poll', 'create_quick_poll', 'delete_quick_poll', 'email_unsubscribe', 'friend_invite_preview', + 'guest_link_preview', 'invite_preview', 'invite_preview_v2', 'quick_poll_preview', 'set_guest_availability', + 'set_quick_poll_availability'], + 'anon can only execute the invite previews, email_unsubscribe, the guest link and the quick poll RPCs' ); -- Not found is PT404 (HTTP 404). P0002 reaches clients as HTTP 500; old migration files still @@ -275,6 +283,10 @@ select ok( exists (select 1 from cron.job where jobname = 'receipts-sweep' and schedule = '40 3 * * *'), 'orphaned receipt files are swept daily' ); +select ok( + exists (select 1 from cron.job where jobname = 'purge-quick-polls' and schedule = '25 * * * *'), + 'expired quick polls are purged hourly' +); -- Grants: clients never write money tables directly. select ok(not has_table_privilege('authenticated', 'public.expenses', 'insert'), 'no direct expense inserts'); diff --git a/supabase/tests/36_quick_polls.test.sql b/supabase/tests/36_quick_polls.test.sql new file mode 100644 index 00000000..f8d8e7db --- /dev/null +++ b/supabase/tests/36_quick_polls.test.sql @@ -0,0 +1,462 @@ +-- Quick polls (ADR 22): nobody reads or writes the tables directly; creating a poll and its +-- checks; names on and off; seats and the people cap; the creator token doubling as the creator's +-- answer token; the preview per status; closing, expiry and deleting; the hourly purge; and the +-- save and create rate limits (the same limits as packages/core quick-polls). +begin; +select plan(80); + +select tests.create_user('alice'); + +-- Grid cell `days` from today at hh:mm UTC as a slot object, yes unless a level is given. +create function pg_temp.slot(days int, hhmm text, level text default 'yes') returns jsonb +language sql immutable as $$ + select jsonb_build_object('slot_start', ((current_date + days) + hhmm::time) at time zone 'UTC', 'level', level) +$$; +grant execute on function pg_temp.slot(int, text, text) to authenticated, anon; + +-- A valid create payload: two days from tomorrow, 10:00 to 12:00 UTC, an hour long, 7 days. +create function pg_temp.payload(extra jsonb default '{}') returns jsonb +language sql stable as $$ + select jsonb_build_object( + 'title', 'Board games', 'timezone', 'UTC', + 'window_start', current_date + 1, 'window_end', current_date + 2, + 'day_start_minute', 600, 'day_end_minute', 720, 'duration_minutes', 60, 'ttl', '7d' + ) || extra +$$; +grant execute on function pg_temp.payload(jsonb) to authenticated, anon; + +-- Polls by name (code and creator token) and answer tokens by who. +create temp table polls (name text primary key, code text, creator text); +grant all on polls to anon, authenticated; +create function pg_temp.code(name text) returns text language sql stable as $$ + select p.code from polls p where p.name = $1 +$$; +create function pg_temp.creator(name text) returns text language sql stable as $$ + select p.creator from polls p where p.name = $1 +$$; +create temp table tok (who text primary key, token text); +grant all on tok to anon, authenticated; +create function pg_temp.tok(who text) returns text language sql stable as $$ + select t.token from tok t where t.who = $1 +$$; +grant execute on function pg_temp.code(text), pg_temp.creator(text), pg_temp.tok(text) to authenticated, anon; + +-- Nobody touches the tables ----------------------------------------------------------------------- + +select tests.login_anon(); +select throws_ok($$ select * from public.quick_polls $$, '42501', null, 'anon cannot read polls'); +select throws_ok($$ select * from public.quick_poll_answers $$, '42501', null, 'anon cannot read answers'); +select throws_ok($$ select * from public.quick_poll_slots $$, '42501', null, 'anon cannot read slots'); +select throws_ok( + $$ insert into public.quick_polls (timezone, window_start, window_end, day_start_minute, day_end_minute, duration_minutes, creator_token_hash, expires_at) + values ('UTC', current_date, current_date, 600, 720, 60, '\x00', now() + interval '1 day') $$, + '42501', null, 'anon cannot write polls' +); +select throws_ok($$ select private.purge_quick_polls() $$, '42501', null, 'anon cannot run the purge'); + +select tests.login('alice'); +select throws_ok($$ select * from public.quick_polls $$, '42501', null, 'signed in users cannot read polls'); +select throws_ok($$ select * from public.quick_poll_answers $$, '42501', null, 'signed in users cannot read answers'); +select throws_ok($$ select * from public.quick_poll_slots $$, '42501', null, 'signed in users cannot read slots'); +select throws_ok( + $$ delete from public.quick_poll_answers $$, + '42501', null, 'signed in users cannot write answers' +); +select lives_ok( + $$ insert into polls select 'alice', q.code, q.creator_token from public.create_quick_poll(pg_temp.payload()) q $$, + 'signed in users can make a poll too' +); + +-- Creating a poll --------------------------------------------------------------------------------- + +select tests.login_anon(); +select throws_ok($$ select public.create_quick_poll('[]') $$, '22023', 'invalid_quick_poll', 'the payload is an object'); +select throws_ok( + $$ select public.create_quick_poll(pg_temp.payload('{"max_people": "lots"}')) $$, + '22023', 'invalid_quick_poll', 'numbers are numbers' +); +select throws_ok( + $$ select public.create_quick_poll(pg_temp.payload('{"ttl": "30d"}')) $$, + '22023', 'invalid_quick_poll_ttl', 'polls last 24h or 7d, not 30d' +); +select throws_ok( + $$ select public.create_quick_poll(pg_temp.payload() - 'ttl') $$, + '22023', 'invalid_quick_poll_ttl', 'a poll needs a ttl' +); +select throws_ok( + $$ select public.create_quick_poll(pg_temp.payload('{"max_people": 16}')) $$, + '22023', 'invalid_quick_poll_people', 'a poll takes at most 15 people' +); +select throws_ok( + $$ select public.create_quick_poll(pg_temp.payload('{"max_people": 1}')) $$, + '22023', 'invalid_quick_poll_people', 'a poll takes at least 2 people' +); +select throws_ok( + $$ select public.create_quick_poll(pg_temp.payload(jsonb_build_object('window_end', current_date + 15))) $$, + '22023', 'invalid_quick_poll_window', 'a window covers at most 14 days' +); +select throws_ok( + $$ select public.create_quick_poll(pg_temp.payload(jsonb_build_object('window_end', current_date))) $$, + '22023', 'invalid_quick_poll_window', 'a window ends on or after its start' +); +select throws_ok( + $$ select public.create_quick_poll(pg_temp.payload(jsonb_build_object('window_start', current_date - 3, 'window_end', current_date - 1))) $$, + '22023', 'invalid_quick_poll_window', 'a window is not all in the past' +); +select throws_ok( + $$ select public.create_quick_poll(pg_temp.payload(jsonb_build_object('title', repeat('a', 81)))) $$, + '22023', 'invalid_quick_poll_title', 'titles are up to 80 characters' +); +select throws_ok( + $$ select public.create_quick_poll(pg_temp.payload('{"timezone": "Mars/Olympus"}')) $$, + '22023', 'invalid_quick_poll_timezone', 'the time zone must exist' +); +select throws_ok( + $$ select public.create_quick_poll(pg_temp.payload('{"slot_minutes": 15}')) $$, + '22023', 'invalid_quick_poll_slot_minutes', 'slots are 30 or 60 minutes' +); +select throws_ok( + $$ select public.create_quick_poll(pg_temp.payload('{"day_end_minute": 620}')) $$, + '22023', 'invalid_quick_poll_hours', 'the day holds at least one slot' +); +select throws_ok( + $$ select public.create_quick_poll(pg_temp.payload('{"duration_minutes": 10}')) $$, + '22023', 'invalid_quick_poll_duration', 'plans last at least 15 minutes' +); + +select lives_ok( + $$ insert into polls select 'big', q.code, q.creator_token + from public.create_quick_poll(pg_temp.payload(jsonb_build_object('max_people', 15, 'window_start', current_date, 'window_end', current_date + 13, 'title', ' Board' || chr(8203) || ' night '))) q $$, + '15 people and a 14 day window are fine' +); +select lives_ok( + $$ insert into polls select 'plain', q.code, q.creator_token + from public.create_quick_poll(pg_temp.payload('{"title": " ", "ttl": "24h"}') - 'slot_minutes' - 'max_people' - 'names_required') q $$, + 'a blank title is no title' +); +reset role; +select results_eq( + $$ select title, max_people, window_end - window_start from public.quick_polls where code = pg_temp.code('big') $$, + $$ values ('Board night'::text, 15, 13) $$, + 'the title is cleaned like a guest name, 15 people and 14 days are kept' +); +select results_eq( + $$ select title, max_people, slot_minutes, names_required, expires_at, closed_at + from public.quick_polls where code = pg_temp.code('plain') $$, + $$ values (null::text, 10, 30, true, now() + interval '24 hours', null::timestamptz) $$, + 'defaults: no title, 10 people, 30 minute slots, names asked; 24h lasts 24 hours' +); +select is( + (select expires_at from public.quick_polls where code = pg_temp.code('big')), + now() + interval '7 days', + 'a 7d poll lasts 7 days' +); +select ok(char_length(pg_temp.code('big')) >= 16, 'codes are long enough not to guess'); +select is( + (select creator_token_hash from public.quick_polls where code = pg_temp.code('big')), + sha256(convert_to(pg_temp.creator('big'), 'UTF8')), + 'only the hash of the creator token is kept' +); + +-- Names on: seats, the cap, the creator token -------------------------------------------------- + +select tests.login_anon(); +insert into polls select 'names', q.code, q.creator_token +from public.create_quick_poll(pg_temp.payload('{"max_people": 3}')) q; + +select results_eq( + $$ select status, title, timezone, window_start, window_end, day_start_minute, day_end_minute, slot_minutes, + duration_minutes, names_required, max_people, is_creator, answers + from public.quick_poll_preview(pg_temp.code('names')) $$, + $$ values ('open', 'Board games', 'UTC', current_date + 1, current_date + 2, 600, 720, 30, 60, true, 3, false, '[]'::jsonb) $$, + 'an open poll shows its grid and no answers yet' +); +select is( + (select is_creator from public.quick_poll_preview(pg_temp.code('names'), pg_temp.creator('names'))), + true, + 'the creator token marks the creator' +); +select throws_ok( + $$ select * from public.quick_poll_preview('not-a-real-code') $$, + 'PT404', 'quick_poll_not_found', 'unknown codes are not found' +); +select throws_ok( + format($$ select * from public.set_quick_poll_availability(%L, ' ', null, %L) $$, + pg_temp.code('names'), jsonb_build_array(pg_temp.slot(1, '10:00'))), + '22023', 'invalid_quick_poll_name', 'a poll with names needs a name' +); +select throws_ok( + format($$ select * from public.set_quick_poll_availability(%L, 'Ana', null, '[]') $$, pg_temp.code('names')), + '22023', 'quick_poll_slots_required', 'a new answer picks at least one time' +); +select throws_ok( + format($$ select * from public.set_quick_poll_availability(%L, 'Ana', null, %L) $$, + pg_temp.code('names'), jsonb_build_array(pg_temp.slot(1, '12:00'))), + '22023', 'invalid_slot', 'times outside the grid are refused' +); +select throws_ok( + format($$ select * from public.set_quick_poll_availability(%L, 'Ana', null, '{"no": 1}') $$, pg_temp.code('names')), + '22023', 'invalid_slots', 'slots are a list' +); + +insert into tok select 'ana', s.answer_token +from public.set_quick_poll_availability(pg_temp.code('names'), 'Ana', null, + jsonb_build_array(pg_temp.slot(1, '10:00'), pg_temp.slot(1, '10:30', 'maybe'))) s; +insert into tok select 'cy', s.answer_token +from public.set_quick_poll_availability(pg_temp.code('names'), 'Cy', pg_temp.creator('names'), + jsonb_build_array(pg_temp.slot(2, '11:00'))) s; +insert into tok select 'ben', s.answer_token +from public.set_quick_poll_availability(pg_temp.code('names'), 'Ben', 'not-a-token-this-poll-knows', + jsonb_build_array(pg_temp.slot(2, '11:30'))) s; + +select is(pg_temp.tok('cy'), pg_temp.creator('names'), 'the creator answers under their creator token'); +select isnt(pg_temp.tok('ben'), 'not-a-token-this-poll-knows', 'an unknown token gets a fresh one'); +select ok(char_length(pg_temp.tok('ana')) >= 16, 'a new answer gets a long token'); + +reset role; +select results_eq( + $$ select a.seat, a.display_name, a.token_hash = p.creator_token_hash + from public.quick_poll_answers a join public.quick_polls p on p.id = a.poll_id + where p.code = pg_temp.code('names') order by a.seat $$, + $$ values (1, 'Ana'::text, false), (2, 'Cy', true), (3, 'Ben', false) $$, + 'seats go 1, 2, 3 in order; the creator''s answer keeps the creator token hash' +); + +select tests.login_anon(); +select is( + (select status from public.quick_poll_preview(pg_temp.code('names'))), + 'full', + 'three of three seats taken: full for someone new' +); +select is( + (select jsonb_array_length(answers) from public.quick_poll_preview(pg_temp.code('names'))), + 3, + 'a full poll still shows its answers' +); +select throws_ok( + format($$ select * from public.set_quick_poll_availability(%L, 'Dee', null, %L) $$, + pg_temp.code('names'), jsonb_build_array(pg_temp.slot(1, '10:00'))), + '23514', 'quick_poll_full', 'a full poll takes no new answers' +); +select is( + (select s.saved from public.set_quick_poll_availability(pg_temp.code('names'), 'Ana B', pg_temp.tok('ana'), + jsonb_build_array(pg_temp.slot(1, '10:00'))) s), + 1, + 'someone already in can edit a full poll' +); +select results_eq( + $$ select status, answers -> 0 from public.quick_poll_preview(pg_temp.code('names'), pg_temp.tok('ana')) $$, + $$ values ('open', jsonb_build_object('seat', 1, 'name', 'Ana B', 'mine', true, 'slots', jsonb_build_array(pg_temp.slot(1, '10:00')))) $$, + 'their own answer is marked mine, with their new name and times' +); +select results_eq( + $$ select answers -> 1, answers -> 2 -> 'mine' from public.quick_poll_preview(pg_temp.code('names'), pg_temp.tok('ana')) $$, + $$ values (jsonb_build_object('seat', 2, 'name', 'Cy', 'mine', false, 'slots', jsonb_build_array(pg_temp.slot(2, '11:00'))), 'false'::jsonb) $$, + 'other answers are not mine' +); +select is( + (select array(select jsonb_object_keys(answers -> 0) order by 1) from public.quick_poll_preview(pg_temp.code('names'))), + array['mine', 'name', 'seat', 'slots'], + 'answers carry no ids or hashes' +); + +-- Names off --------------------------------------------------------------------------------------- + +insert into polls select 'nameless', q.code, q.creator_token +from public.create_quick_poll(pg_temp.payload('{"names_required": false, "max_people": 2, "slot_minutes": 60}')) q; +select lives_ok( + format($$ insert into tok select 'n1', s.answer_token from public.set_quick_poll_availability(%L, null, null, %L) s $$, + pg_temp.code('nameless'), jsonb_build_array(pg_temp.slot(1, '10:00'))), + 'a poll without names takes an answer with no name' +); +select lives_ok( + format($$ insert into tok select 'n2', s.answer_token from public.set_quick_poll_availability(%L, 'Ignored', null, %L) s $$, + pg_temp.code('nameless'), jsonb_build_array(pg_temp.slot(1, '11:00'))), + 'and ignores a name it is given' +); +select throws_ok( + format($$ select * from public.set_quick_poll_availability(%L, null, %L, %L) $$, + pg_temp.code('nameless'), pg_temp.tok('n1'), jsonb_build_array(pg_temp.slot(1, '10:30'))), + '22023', 'invalid_slot', 'an hour grid refuses half hours' +); +select results_eq( + $$ select a ->> 'seat', a -> 'name' from public.quick_poll_preview(pg_temp.code('nameless')) p, + jsonb_array_elements(p.answers) a $$, + $$ values ('1', 'null'::jsonb), ('2', 'null'::jsonb) $$, + 'answers are seats 1 and 2 with null names' +); +reset role; +select is( + (select count(*)::int from public.quick_poll_answers a join public.quick_polls p on p.id = a.poll_id + where p.code = pg_temp.code('nameless') and a.display_name is null), + 2, + 'no name is stored' +); + +-- Closing and expiry ------------------------------------------------------------------------------ + +select tests.login_anon(); +select throws_ok( + format($$ select public.close_quick_poll(%L, %L) $$, pg_temp.code('names'), pg_temp.tok('ana')), + '42501', 'not_allowed', 'only the creator can close a poll' +); +select throws_ok( + format($$ select public.close_quick_poll(%L, null) $$, pg_temp.code('names')), + '42501', 'not_allowed', 'closing needs a token' +); +select throws_ok( + format($$ select public.close_quick_poll('not-a-real-code', %L) $$, pg_temp.creator('names')), + 'PT404', 'quick_poll_not_found', 'closing an unknown poll is not found' +); +select lives_ok( + format($$ select public.close_quick_poll(%L, %L) $$, pg_temp.code('names'), pg_temp.creator('names')), + 'the creator closes the poll' +); +select lives_ok( + format($$ select public.close_quick_poll(%L, %L) $$, pg_temp.code('names'), pg_temp.creator('names')), + 'closing again changes nothing' +); +select throws_ok( + format($$ select * from public.set_quick_poll_availability(%L, 'Ana', %L, %L) $$, + pg_temp.code('names'), pg_temp.tok('ana'), jsonb_build_array(pg_temp.slot(1, '10:00'))), + '23514', 'quick_poll_closed', 'a closed poll takes no edits' +); +select results_eq( + $$ select status, jsonb_array_length(answers), is_creator + from public.quick_poll_preview(pg_temp.code('names'), pg_temp.creator('names')) $$, + $$ values ('closed', 3, true) $$, + 'a closed poll still shows its results' +); + +reset role; +update public.quick_polls set expires_at = now() - interval '1 second' +where code in (pg_temp.code('names'), pg_temp.code('nameless')); +select tests.login_anon(); +select throws_ok( + format($$ select * from public.set_quick_poll_availability(%L, null, %L, %L) $$, + pg_temp.code('nameless'), pg_temp.tok('n1'), jsonb_build_array(pg_temp.slot(1, '10:00'))), + '23514', 'quick_poll_expired', 'an expired poll takes no edits' +); +select results_eq( + $$ select * from public.quick_poll_preview(pg_temp.code('nameless'), pg_temp.creator('nameless')) $$, + $$ values ('expired', null::text, null::text, null::date, null::date, null::int, null::int, null::int, + null::int, null::boolean, null::int, null::timestamptz, null::boolean, null::jsonb) $$, + 'an expired poll shows its status only' +); +select is( + (select status from public.quick_poll_preview(pg_temp.code('names'))), + 'expired', + 'expired wins over closed' +); + +-- Deleting ---------------------------------------------------------------------------------------- + +insert into polls select 'gone', q.code, q.creator_token from public.create_quick_poll(pg_temp.payload()) q; +insert into tok select 'g1', s.answer_token +from public.set_quick_poll_availability(pg_temp.code('gone'), 'Gil', null, jsonb_build_array(pg_temp.slot(1, '10:00'))) s; +reset role; +select tests.remember('gone', (select id from public.quick_polls where code = pg_temp.code('gone'))); +select tests.login_anon(); +select throws_ok( + format($$ select public.delete_quick_poll(%L, %L) $$, pg_temp.code('gone'), pg_temp.tok('g1')), + '42501', 'not_allowed', 'only the creator can delete a poll' +); +select lives_ok( + format($$ select public.delete_quick_poll(%L, %L) $$, pg_temp.code('gone'), pg_temp.creator('gone')), + 'the creator deletes the poll' +); +select throws_ok( + format($$ select * from public.quick_poll_preview(%L) $$, pg_temp.code('gone')), + 'PT404', 'quick_poll_not_found', 'a deleted poll is not found' +); +reset role; +select is( + (select count(*)::int from public.quick_poll_answers a where a.poll_id = tests.id('gone')), + 0, + 'its answers went with it' +); + +-- Purge ------------------------------------------------------------------------------------------- + +insert into private.quick_poll_creates (created_at) values (now() - interval '2 hours'); +select tests.remember('names', (select id from public.quick_polls where code = pg_temp.code('names'))); +select is(private.purge_quick_polls(), 2, 'the purge deletes the two expired polls'); +select results_eq( + $$ select count(*)::int from public.quick_polls where code in (pg_temp.code('names'), pg_temp.code('nameless')) $$, + $$ values (0) $$, + 'expired polls are gone' +); +select is( + (select count(*)::int from public.quick_poll_slots s + where not exists (select 1 from public.quick_poll_answers a where a.id = s.answer_id)) + + (select count(*)::int from public.quick_poll_answers a where a.poll_id = tests.id('names')), + 0, + 'their answers and slots are gone' +); +select is( + (select count(*)::int from public.quick_polls where code in (pg_temp.code('big'), pg_temp.code('plain'))), + 2, + 'live polls stay' +); +select is( + (select count(*)::int from private.quick_poll_creates where created_at <= now() - interval '1 hour'), + 0, + 'create log rows past the hour go too' +); + +-- Save rate limit --------------------------------------------------------------------------------- + +select tests.login_anon(); +insert into tok select 'r1', s.answer_token +from public.set_quick_poll_availability(pg_temp.code('big'), 'Rae', null, jsonb_build_array(pg_temp.slot(1, '10:00'))) s; +reset role; +update public.quick_poll_answers set saves = 60 where token_hash = sha256(convert_to(pg_temp.tok('r1'), 'UTF8')); +select tests.login_anon(); +select throws_ok( + format($$ select * from public.set_quick_poll_availability(%L, 'Rae', %L, %L) $$, + pg_temp.code('big'), pg_temp.tok('r1'), jsonb_build_array(pg_temp.slot(1, '10:00'))), + '23514', 'quick_poll_rate_limited', '60 saves an hour per answer' +); +reset role; +update public.quick_poll_answers set saves_window_start = now() - interval '61 minutes' +where token_hash = sha256(convert_to(pg_temp.tok('r1'), 'UTF8')); +select tests.login_anon(); +select lives_ok( + format($$ select * from public.set_quick_poll_availability(%L, 'Rae', %L, %L) $$, + pg_temp.code('big'), pg_temp.tok('r1'), jsonb_build_array(pg_temp.slot(1, '10:00'))), + 'a new hour, new saves' +); + +-- Create rate limit ------------------------------------------------------------------------------- + +-- PostgREST hands the request headers over as request.headers. +select set_config('request.headers', '{"x-forwarded-for": "198.51.100.7, 10.0.0.1"}', true); +insert into polls select 'rl' || g, q.code, q.creator_token +-- The payload names g so each row makes its own poll. +from generate_series(1, 5) g, lateral public.create_quick_poll(pg_temp.payload(jsonb_build_object('title', 'Poll ' || g))) q; +select lives_ok( + format($$ select public.delete_quick_poll(%L, %L) $$, pg_temp.code('rl1'), pg_temp.creator('rl1')), + 'deleting one of them' +); +select throws_ok( + $$ select public.create_quick_poll(pg_temp.payload()) $$, + '23514', 'quick_poll_rate_limited', 'five polls an hour per client, deleted ones included' +); +select set_config('request.headers', '{"x-forwarded-for": "198.51.100.8, 10.0.0.1"}', true); +select lives_ok($$ select public.create_quick_poll(pg_temp.payload()) $$, 'the client is the first x-forwarded-for entry'); +reset role; +select is( + (select count(*)::int from private.quick_poll_creates where creator_hash = sha256(convert_to('198.51.100.7', 'UTF8'))), + 5, + 'the log keeps the hash of the client address' +); +insert into private.quick_poll_creates (creator_hash) select null from generate_series(1, 200); +select tests.login_anon(); +select set_config('request.headers', '{"x-forwarded-for": "198.51.100.9"}', true); +select throws_ok( + $$ select public.create_quick_poll(pg_temp.payload()) $$, + '23514', 'quick_poll_rate_limited', 'no more than 200 polls an hour in all' +); + +select * from finish(); +rollback; From f6f97fdc5d0cafebc41e87ca9d08a21c31dc0e76 Mon Sep 17 00:00:00 2001 From: Musa Kaleem <131704022+Musa-Kal@users.noreply.github.com> Date: Sun, 22 Nov 2026 18:31:05 -0500 Subject: [PATCH 03/21] feat(api): add quick poll queries and mutations Co-authored-by: Ferrin <177692050+Ferrin-Y@users.noreply.github.com> Co-authored-by: noorelmosrati <182049385+noorelmosrati@users.noreply.github.com> --- packages/api/src/index.ts | 1 + packages/api/src/quick-polls.test.ts | 269 +++++++++++++++++++++++++++ packages/api/src/quick-polls.ts | 228 +++++++++++++++++++++++ 3 files changed, 498 insertions(+) create mode 100644 packages/api/src/quick-polls.test.ts create mode 100644 packages/api/src/quick-polls.ts diff --git a/packages/api/src/index.ts b/packages/api/src/index.ts index 50afe948..0f764e5f 100644 --- a/packages/api/src/index.ts +++ b/packages/api/src/index.ts @@ -23,6 +23,7 @@ export * from './attachments' export * from './payments' export * from './insights' export * from './plans' +export * from './quick-polls' export * from './me' export * from './notification-prefs' export * from './account' diff --git a/packages/api/src/quick-polls.test.ts b/packages/api/src/quick-polls.test.ts new file mode 100644 index 00000000..14b36a35 --- /dev/null +++ b/packages/api/src/quick-polls.test.ts @@ -0,0 +1,269 @@ +import { describe, expect, it } from 'vitest' +import { PlanError } from './plans' +import { + closeQuickPoll, + createQuickPoll, + deleteQuickPoll, + fetchQuickPollPreview, + quickPollKeys, + quickPollQueries, + setQuickPollAvailability, +} from './quick-polls' +import { fakeSupabase } from './testing/fake-supabase' + +const answers = [ + { + seat: 1, + name: 'Ana', + mine: true, + slots: [ + { slot_start: '2026-06-01T08:00:00+00:00', level: 'yes' }, + { slot_start: '2026-06-01T08:30:00+00:00', level: 'maybe' }, + ], + }, + { seat: 2, name: 'Ben', mine: false, slots: [] }, +] + +const openRow = { + status: 'open', + title: 'Board games', + timezone: 'Europe/Berlin', + window_start: '2026-06-01', + window_end: '2026-06-03', + day_start_minute: 600, + day_end_minute: 720, + slot_minutes: 30, + duration_minutes: 60, + names_required: true, + max_people: 10, + expires_at: '2026-06-08T10:00:00+00:00', + is_creator: false, + answers, +} + +const expiredRow = Object.fromEntries( + Object.keys(openRow).map((key) => [key, key === 'status' ? 'expired' : null]), +) + +describe('fetchQuickPollPreview', () => { + it('reads an open poll with its grid and every answer', async () => { + const fake = fakeSupabase().respond('rpc:quick_poll_preview', { data: [openRow] }) + + expect(await fetchQuickPollPreview(fake.client, 'abc', 'tok')).toEqual({ + status: 'open', + poll: { + title: 'Board games', + grid: { + windowStart: '2026-06-01', + windowEnd: '2026-06-03', + dayStartMinute: 600, + dayEndMinute: 720, + slotMinutes: 30, + timeZone: 'Europe/Berlin', + }, + durationMinutes: 60, + namesRequired: true, + maxPeople: 10, + expiresAt: '2026-06-08T10:00:00+00:00', + }, + answers, + isCreator: false, + }) + expect(fake.rpcArgs('quick_poll_preview')).toEqual([{ code: 'abc', token: 'tok' }]) + }) + + it('leaves out a missing token and keeps a missing title and names null', async () => { + const row = { + ...openRow, + status: 'closed', + title: null, + names_required: false, + is_creator: true, + answers: [{ seat: 1, name: null, mine: false, slots: [] }], + } + const fake = fakeSupabase().respond('rpc:quick_poll_preview', { data: [row] }) + + const view = await fetchQuickPollPreview(fake.client, 'abc', null) + + expect(fake.rpcArgs('quick_poll_preview')).toEqual([{ code: 'abc' }]) + expect(view).toMatchObject({ + status: 'closed', + poll: { title: null, namesRequired: false }, + answers: [{ seat: 1, name: null, mine: false, slots: [] }], + isCreator: true, + }) + }) + + it('shows nothing but the status for an expired poll, or a status it does not know', async () => { + const fake = fakeSupabase().respond('rpc:quick_poll_preview', { data: [expiredRow] }) + expect(await fetchQuickPollPreview(fake.client, 'abc', null)).toEqual({ status: 'expired' }) + + const odd = fakeSupabase().respond('rpc:quick_poll_preview', { + data: [{ ...openRow, status: 'something-new' }], + }) + expect(await fetchQuickPollPreview(odd.client, 'abc', null)).toEqual({ status: 'expired' }) + }) + + it('reads odd answers defensively', async () => { + const row = { + ...openRow, + answers: [null, { seat: 'x', name: 3, mine: 'yes', slots: [null, { level: 'no' }] }], + } + const fake = fakeSupabase().respond('rpc:quick_poll_preview', { data: [row] }) + const view = await fetchQuickPollPreview(fake.client, 'abc', null) + expect(view.status === 'open' && view.answers).toEqual([ + { seat: 0, name: null, mine: false, slots: [] }, + { + seat: 0, + name: null, + mine: false, + slots: [ + { slot_start: 'undefined', level: 'yes' }, + { slot_start: 'undefined', level: 'yes' }, + ], + }, + ]) + const none = fakeSupabase().respond('rpc:quick_poll_preview', { + data: [{ ...openRow, answers: null }], + }) + const empty = await fetchQuickPollPreview(none.client, 'abc', null) + expect(empty.status === 'open' && empty.answers).toEqual([]) + }) + + it('throws quick_poll_not_found when nothing comes back, and PlanErrors on failure', async () => { + for (const fake of [ + fakeSupabase().respond('rpc:quick_poll_preview', { data: [] }), + fakeSupabase(), + ]) { + await expect(fetchQuickPollPreview(fake.client, 'abc', null)).rejects.toMatchObject({ + name: 'PlanError', + code: 'quick_poll_not_found', + }) + } + const failing = fakeSupabase().respond('rpc:quick_poll_preview', { + error: { message: 'quick_poll_not_found', details: 'This poll is not valid' }, + }) + await expect(fetchQuickPollPreview(failing.client, 'abc', null)).rejects.toMatchObject({ + code: 'quick_poll_not_found', + }) + }) +}) + +describe('quick poll writes', () => { + const input = { + title: 'Board games', + timeZone: 'UTC', + windowStart: '2026-06-01', + windowEnd: '2026-06-03', + dayStartMinute: 600, + dayEndMinute: 720, + durationMinutes: 60, + slotMinutes: 30 as const, + ttl: '7d' as const, + namesRequired: true, + maxPeople: 15, + } + + it('creates a poll from one payload and returns the code and creator token', async () => { + const fake = fakeSupabase().respond('rpc:create_quick_poll', { + data: [{ code: 'c1', creator_token: 'secret', expires_at: '2026-06-08T10:00:00+00:00' }], + }) + + expect(await createQuickPoll(fake.client, input)).toEqual({ + code: 'c1', + creatorToken: 'secret', + expiresAt: '2026-06-08T10:00:00+00:00', + }) + expect(fake.rpcArgs('create_quick_poll')).toEqual([ + { + payload: { + title: 'Board games', + timezone: 'UTC', + window_start: '2026-06-01', + window_end: '2026-06-03', + day_start_minute: 600, + day_end_minute: 720, + duration_minutes: 60, + slot_minutes: 30, + ttl: '7d', + names_required: true, + max_people: 15, + }, + }, + ]) + }) + + it('saves an answer, sending empty strings for no name and no token', async () => { + const fake = fakeSupabase().respond('rpc:set_quick_poll_availability', { + data: [{ answer_token: 'fresh', saved: 1 }], + }) + const slots = [{ slot_start: 's1', level: 'yes' as const }] + + expect( + await setQuickPollAvailability(fake.client, { code: 'c', name: null, token: null, slots }), + ).toEqual({ token: 'fresh', saved: 1 }) + await setQuickPollAvailability(fake.client, { code: 'c', name: 'Ana', token: 'old', slots }) + + expect(fake.rpcArgs('set_quick_poll_availability')).toEqual([ + { code: 'c', name: '', token: '', slots }, + { code: 'c', name: 'Ana', token: 'old', slots }, + ]) + }) + + it('closes and deletes with the creator token', async () => { + const fake = fakeSupabase() + await closeQuickPoll(fake.client, { code: 'c', creatorToken: 'secret' }) + await deleteQuickPoll(fake.client, { code: 'c', creatorToken: 'secret' }) + expect(fake.rpcArgs('close_quick_poll')).toEqual([{ code: 'c', token: 'secret' }]) + expect(fake.rpcArgs('delete_quick_poll')).toEqual([{ code: 'c', token: 'secret' }]) + }) + + it('throws PlanErrors from every write, and unknown on an empty reply', async () => { + const error = { message: 'quick_poll_full' } + const fake = fakeSupabase() + .respond('rpc:create_quick_poll', { error }) + .respond('rpc:set_quick_poll_availability', { error }) + .respond('rpc:close_quick_poll', { error }) + .respond('rpc:delete_quick_poll', { error }) + const answer = { code: 'c', name: 'A', token: null, slots: [] } + const creator = { code: 'c', creatorToken: 'secret' } + for (const write of [ + () => createQuickPoll(fake.client, input), + () => setQuickPollAvailability(fake.client, answer), + () => closeQuickPoll(fake.client, creator), + () => deleteQuickPoll(fake.client, creator), + ]) { + await expect(write()).rejects.toMatchObject({ name: 'PlanError', code: 'quick_poll_full' }) + } + const blank = fakeSupabase() + .respond('rpc:create_quick_poll', { data: [] }) + .respond('rpc:set_quick_poll_availability', { data: [] }) + await expect(createQuickPoll(blank.client, input)).rejects.toMatchObject({ code: 'unknown' }) + await expect(setQuickPollAvailability(blank.client, answer)).rejects.toMatchObject({ + code: 'unknown', + }) + }) +}) + +describe('quickPollQueries', () => { + it('keys the preview by code and token under quickPollKeys.all', async () => { + const fake = fakeSupabase().respond('rpc:quick_poll_preview', { data: [expiredRow] }) + const preview = quickPollQueries.preview(fake.client, 'abc', null) + + expect(preview.queryKey).toEqual(['potluck', 'quick-poll', 'abc', '']) + expect(preview.queryKey.slice(0, 2)).toEqual(quickPollKeys.all) + expect(quickPollQueries.preview(fake.client, 'abc', 't').queryKey.at(-1)).toBe('t') + expect(await (preview.queryFn as () => Promise)()).toEqual({ status: 'expired' }) + }) + + it('does not retry an unknown code, but retries a dropped request twice', () => { + const { client } = fakeSupabase() + const retry = quickPollQueries.preview(client, 'abc', null).retry as ( + count: number, + error: unknown, + ) => boolean + expect(retry(0, new PlanError('quick_poll_not_found'))).toBe(false) + expect(retry(0, new Error('Failed to fetch'))).toBe(true) + expect(retry(2, new Error('Failed to fetch'))).toBe(false) + }) +}) diff --git a/packages/api/src/quick-polls.ts b/packages/api/src/quick-polls.ts new file mode 100644 index 00000000..b97c1669 --- /dev/null +++ b/packages/api/src/quick-polls.ts @@ -0,0 +1,228 @@ +/** + * Quick polls (ADR 22): availability polls anyone can make and answer without an account. Every + * call goes through an anon-callable RPC; the browser keeps the tokens they hand back. + */ +import type { QuickPollSlotMinutes, QuickPollTtl, SlotGrid } from '@potluck/core' +import { queryOptions } from '@tanstack/react-query' +import type { Database } from './database.types' +import type { PotluckClient } from './index' +import { PlanError } from './plans' + +type PreviewRow = Database['public']['Functions']['quick_poll_preview']['Returns'][number] + +// A type, not an interface, so it fits the Json argument of the RPC. +export type QuickPollSlot = { + slot_start: string + level: 'yes' | 'maybe' +} + +export interface QuickPollAnswer { + /** 1, 2, 3... in the order people answered. */ + seat: number + /** Null when the poll does not ask for names. */ + name: string | null + /** True for the answer the visitor's token belongs to. */ + mine: boolean + slots: QuickPollSlot[] +} + +export interface QuickPollInfo { + /** Null when the creator gave none; show a default. */ + title: string | null + grid: SlotGrid + durationMinutes: number + namesRequired: boolean + maxPeople: number + expiresAt: string +} + +/** A poll as its link shows it. An expired poll shows nothing else. */ +export type QuickPollView = + | { status: 'expired' } + | { + status: 'open' | 'full' | 'closed' + poll: QuickPollInfo + answers: QuickPollAnswer[] + isCreator: boolean + } + +export interface CreateQuickPollInput { + title: string | null + timeZone: string + windowStart: string + windowEnd: string + dayStartMinute: number + dayEndMinute: number + durationMinutes: number + slotMinutes: QuickPollSlotMinutes + ttl: QuickPollTtl + namesRequired: boolean + maxPeople: number +} + +export interface CreatedQuickPoll { + code: string + /** Keep it: it closes and deletes the poll, and is the creator's answer token. */ + creatorToken: string + expiresAt: string +} + +export const quickPollKeys = { + all: ['potluck', 'quick-poll'] as const, + preview: (code: string) => ['potluck', 'quick-poll', code] as const, +} + +function fail(error: { message: string; details?: string | null } | null): never { + throw new PlanError(error?.message || 'unknown', error?.details ?? undefined) +} + +function record(value: unknown): Record { + return value && typeof value === 'object' ? (value as Record) : {} +} + +function parseAnswers(value: unknown): QuickPollAnswer[] { + if (!Array.isArray(value)) return [] + return value.map((item) => { + const a = record(item) + return { + seat: Number(a.seat) || 0, + name: typeof a.name === 'string' ? a.name : null, + mine: a.mine === true, + slots: Array.isArray(a.slots) + ? a.slots.map((slot) => { + const s = record(slot) + return { + slot_start: String(s.slot_start), + level: s.level === 'maybe' ? 'maybe' : 'yes', + } + }) + : [], + } + }) +} + +/** The preview row as a view. An unknown status reads as expired, which shows nothing. */ +function parseQuickPollView(row: PreviewRow): QuickPollView { + const status = row.status + if (status !== 'open' && status !== 'full' && status !== 'closed') return { status: 'expired' } + return { + status, + poll: { + // The generated type says string; a poll without a title comes back null. + title: (row.title as string | null) ?? null, + grid: { + windowStart: row.window_start, + windowEnd: row.window_end, + dayStartMinute: row.day_start_minute, + dayEndMinute: row.day_end_minute, + slotMinutes: row.slot_minutes, + timeZone: row.timezone, + }, + durationMinutes: row.duration_minutes, + namesRequired: row.names_required, + maxPeople: row.max_people, + expiresAt: row.expires_at, + }, + answers: parseAnswers(row.answers), + isCreator: row.is_creator === true, + } +} + +/** Works signed out. Throws `quick_poll_not_found` for an unknown code. */ +export async function fetchQuickPollPreview( + client: PotluckClient, + code: string, + token: string | null, +): Promise { + const { data, error } = await client.rpc('quick_poll_preview', { + code, + ...(token ? { token } : {}), + }) + if (error) fail(error) + const row = data?.[0] + if (!row) throw new PlanError('quick_poll_not_found') + return parseQuickPollView(row) +} + +export async function createQuickPoll( + client: PotluckClient, + input: CreateQuickPollInput, +): Promise { + const { data, error } = await client.rpc('create_quick_poll', { + payload: { + title: input.title, + timezone: input.timeZone, + window_start: input.windowStart, + window_end: input.windowEnd, + day_start_minute: input.dayStartMinute, + day_end_minute: input.dayEndMinute, + duration_minutes: input.durationMinutes, + slot_minutes: input.slotMinutes, + ttl: input.ttl, + names_required: input.namesRequired, + max_people: input.maxPeople, + }, + }) + if (error) fail(error) + const row = data?.[0] + if (!row) throw new PlanError('unknown') + return { code: row.code, creatorToken: row.creator_token, expiresAt: row.expires_at } +} + +/** + * Adds or replaces the visitor's answer. With no token (or one the poll does not know) the server + * makes a new answer and returns its token; keep it to edit later. The creator passes their + * creator token and gets it back. + */ +export async function setQuickPollAvailability( + client: PotluckClient, + input: { code: string; name: string | null; token: string | null; slots: QuickPollSlot[] }, +): Promise<{ token: string; saved: number }> { + const { data, error } = await client.rpc('set_quick_poll_availability', { + code: input.code, + // Ignored when the poll does not ask for names. + name: input.name ?? '', + // An empty token is one the poll does not know, so the server makes a new answer. + token: input.token ?? '', + slots: input.slots, + }) + if (error) fail(error) + const row = data?.[0] + if (!row) throw new PlanError('unknown') + return { token: row.answer_token, saved: row.saved } +} + +/** Creator only (`not_allowed` otherwise). Stops answers; results stay readable until expiry. */ +export async function closeQuickPoll( + client: PotluckClient, + input: { code: string; creatorToken: string }, +): Promise { + const { error } = await client.rpc('close_quick_poll', { + code: input.code, + token: input.creatorToken, + }) + if (error) fail(error) +} + +/** Creator only (`not_allowed` otherwise). Deletes the poll and every answer now. */ +export async function deleteQuickPoll( + client: PotluckClient, + input: { code: string; creatorToken: string }, +): Promise { + const { error } = await client.rpc('delete_quick_poll', { + code: input.code, + token: input.creatorToken, + }) + if (error) fail(error) +} + +export const quickPollQueries = { + preview: (client: PotluckClient, code: string, token: string | null) => + queryOptions({ + queryKey: [...quickPollKeys.preview(code), token ?? ''] as const, + queryFn: () => fetchQuickPollPreview(client, code, token), + // An unknown code stays unknown. + retry: (count: number, error: unknown) => + !(error instanceof PlanError && error.code === 'quick_poll_not_found') && count < 2, + }), +} From 5e8cdd41c791feef718c6a62481a9f8d75ca860a Mon Sep 17 00:00:00 2001 From: Musa Kaleem <131704022+Musa-Kal@users.noreply.github.com> Date: Sun, 22 Nov 2026 18:33:38 -0500 Subject: [PATCH 04/21] feat(i18n): word the quick poll error codes Co-authored-by: Ferrin <177692050+Ferrin-Y@users.noreply.github.com> Co-authored-by: noorelmosrati <182049385+noorelmosrati@users.noreply.github.com> --- apps/web/src/lib/errors.ts | 2 +- apps/web/src/lib/server-codes.test.ts | 7 ++++++- packages/i18n/src/de.ts | 2 ++ packages/i18n/src/de/quick-polls.ts | 27 +++++++++++++++++++++++++++ packages/i18n/src/en.ts | 2 ++ packages/i18n/src/en/quick-polls.ts | 26 ++++++++++++++++++++++++++ packages/i18n/src/es.ts | 2 ++ packages/i18n/src/es/quick-polls.ts | 27 +++++++++++++++++++++++++++ packages/i18n/src/fr.ts | 2 ++ packages/i18n/src/fr/quick-polls.ts | 27 +++++++++++++++++++++++++++ packages/i18n/src/pt.ts | 2 ++ packages/i18n/src/pt/quick-polls.ts | 27 +++++++++++++++++++++++++++ 12 files changed, 151 insertions(+), 2 deletions(-) create mode 100644 packages/i18n/src/de/quick-polls.ts create mode 100644 packages/i18n/src/en/quick-polls.ts create mode 100644 packages/i18n/src/es/quick-polls.ts create mode 100644 packages/i18n/src/fr/quick-polls.ts create mode 100644 packages/i18n/src/pt/quick-polls.ts diff --git a/apps/web/src/lib/errors.ts b/apps/web/src/lib/errors.ts index dfedbe2b..d92821ad 100644 --- a/apps/web/src/lib/errors.ts +++ b/apps/web/src/lib/errors.ts @@ -33,7 +33,7 @@ export function isNotFoundError(error: unknown): boolean { } /** Screens with their own wording for server codes, e.g. `expenses.errors.sum_mismatch`. */ -export type ErrorScope = 'expenses.errors' | 'events.errors' +export type ErrorScope = 'expenses.errors' | 'events.errors' | 'quickPolls.errors' /** * `fetch` rejects with a TypeError when the request never got an answer; each browser words it diff --git a/apps/web/src/lib/server-codes.test.ts b/apps/web/src/lib/server-codes.test.ts index 6a596236..c7a09d03 100644 --- a/apps/web/src/lib/server-codes.test.ts +++ b/apps/web/src/lib/server-codes.test.ts @@ -20,7 +20,12 @@ const raised = [ ), ].sort() -const SCOPES: (ErrorScope | undefined)[] = [undefined, 'expenses.errors', 'events.errors'] +const SCOPES: (ErrorScope | undefined)[] = [ + undefined, + 'expenses.errors', + 'events.errors', + 'quickPolls.errors', +] describe('error codes the database raises', () => { it('finds the codes', () => { diff --git a/packages/i18n/src/de.ts b/packages/i18n/src/de.ts index e1604eb3..a98631d5 100644 --- a/packages/i18n/src/de.ts +++ b/packages/i18n/src/de.ts @@ -10,6 +10,7 @@ import { help } from './de/help' import { search, filters, insights, deletedItems, activityFilter } from './de/insights' import { people } from './de/people' import { transfer } from './de/transfer' +import { quickPolls } from './de/quick-polls' /** * German (du). Same files and keys as `./en`; a key missing here shows in English. Loaded on demand @@ -53,6 +54,7 @@ export const de = { activityFilter, people, transfer, + quickPolls, empty, errors, } satisfies Translation diff --git a/packages/i18n/src/de/quick-polls.ts b/packages/i18n/src/de/quick-polls.ts new file mode 100644 index 00000000..3670f839 --- /dev/null +++ b/packages/i18n/src/de/quick-polls.ts @@ -0,0 +1,27 @@ +import type { Translation } from '../locales' +import type * as en from '../en/quick-polls' + +export const quickPolls = { + errors: { + quick_poll_not_found: 'Dieser Umfragelink führt nirgendwohin.', + quick_poll_expired: 'Diese Umfrage ist vorbei.', + quick_poll_closed: 'Diese Umfrage ist geschlossen, die Zeiten stehen fest.', + quick_poll_full: 'Alle Plätze in dieser Umfrage sind vergeben.', + quick_poll_rate_limited: 'Langsam. Versuch es etwas später noch mal.', + quick_poll_slots_required: 'Male zuerst mindestens eine Zeit.', + invalid_quick_poll: 'Etwas an dieser Umfrage stimmt nicht. Prüf sie und versuch es noch mal.', + invalid_quick_poll_title: 'Titel haben bis zu 80 Zeichen.', + invalid_quick_poll_timezone: 'Wähle eine Zeitzone aus der Liste.', + invalid_quick_poll_window: 'Wähle 1 bis 14 Tage, nicht alle in der Vergangenheit.', + invalid_quick_poll_hours: 'Der Tag muss mindestens einen Block nach seinem Beginn enden.', + invalid_quick_poll_slot_minutes: 'Wähle Blöcke von 30 oder 60 Minuten.', + invalid_quick_poll_duration: 'Pläne dauern 15 Minuten bis 24 Stunden.', + invalid_quick_poll_ttl: 'Wähle, wie lange die Umfrage offen bleibt.', + invalid_quick_poll_people: 'Eine Umfrage nimmt 2 bis 15 Personen.', + invalid_quick_poll_name: 'Namen haben 1 bis 40 Zeichen.', + invalid_slot: 'Einige dieser Zeiten liegen außerhalb der Umfrage.', + invalid_slots: 'Diese Zeiten wurden nicht gespeichert. Noch mal versuchen?', + duplicate_slot: 'Eine Zeit kommt doppelt vor. Noch mal versuchen?', + not_allowed: 'Das kann nur, wer die Umfrage erstellt hat.', + }, +} satisfies Translation diff --git a/packages/i18n/src/en.ts b/packages/i18n/src/en.ts index 4e85f291..48653da0 100644 --- a/packages/i18n/src/en.ts +++ b/packages/i18n/src/en.ts @@ -8,6 +8,7 @@ import { help } from './en/help' import { search, filters, insights, deletedItems, activityFilter } from './en/insights' import { people } from './en/people' import { transfer } from './en/transfer' +import { quickPolls } from './en/quick-polls' /** * English strings. Nested by screen or domain; look them up with dotted keys via `t()`. @@ -58,6 +59,7 @@ export const en = { activityFilter, people, transfer, + quickPolls, empty, errors, } as const diff --git a/packages/i18n/src/en/quick-polls.ts b/packages/i18n/src/en/quick-polls.ts new file mode 100644 index 00000000..5f1ffc26 --- /dev/null +++ b/packages/i18n/src/en/quick-polls.ts @@ -0,0 +1,26 @@ +/** Quick polls: availability polls anyone can make and answer without an account (ADR 22). */ +export const quickPolls = { + /** Server codes the quick poll screens show, `errorMessage(error, 'quickPolls.errors')`. */ + errors: { + quick_poll_not_found: 'That poll link does not lead anywhere.', + quick_poll_expired: 'This poll has ended.', + quick_poll_closed: 'This poll is closed, so the times are final.', + quick_poll_full: 'Every spot in this poll is taken.', + quick_poll_rate_limited: 'Easy there. Try again a little later.', + quick_poll_slots_required: 'Paint at least one time first.', + invalid_quick_poll: 'Something in this poll is not right. Check it and try again.', + invalid_quick_poll_title: 'Titles are up to 80 characters.', + invalid_quick_poll_timezone: 'Pick a time zone from the list.', + invalid_quick_poll_window: 'Pick 1 to 14 days, not all in the past.', + invalid_quick_poll_hours: 'The day has to end at least one slot after it starts.', + invalid_quick_poll_slot_minutes: 'Pick 30 or 60 minute slots.', + invalid_quick_poll_duration: 'Plans last 15 minutes to 24 hours.', + invalid_quick_poll_ttl: 'Pick how long the poll stays open.', + invalid_quick_poll_people: 'A poll takes 2 to 15 people.', + invalid_quick_poll_name: 'Names are 1 to 40 characters.', + invalid_slot: 'Some of those times are outside the poll.', + invalid_slots: 'Those times did not save. Try again?', + duplicate_slot: 'A time showed up twice. Try again?', + not_allowed: 'Only whoever made the poll can do that.', + }, +} diff --git a/packages/i18n/src/es.ts b/packages/i18n/src/es.ts index 14ab4dda..906cbbb0 100644 --- a/packages/i18n/src/es.ts +++ b/packages/i18n/src/es.ts @@ -10,6 +10,7 @@ import { help } from './es/help' import { search, filters, insights, deletedItems, activityFilter } from './es/insights' import { people } from './es/people' import { transfer } from './es/transfer' +import { quickPolls } from './es/quick-polls' /** * Spanish (tú, neutral Latin American and Spain friendly). Same files and keys as `./en`; a key @@ -53,6 +54,7 @@ export const es = { activityFilter, people, transfer, + quickPolls, empty, errors, } satisfies Translation diff --git a/packages/i18n/src/es/quick-polls.ts b/packages/i18n/src/es/quick-polls.ts new file mode 100644 index 00000000..2e179d28 --- /dev/null +++ b/packages/i18n/src/es/quick-polls.ts @@ -0,0 +1,27 @@ +import type { Translation } from '../locales' +import type * as en from '../en/quick-polls' + +export const quickPolls = { + errors: { + quick_poll_not_found: 'Ese enlace de encuesta no lleva a ningún sitio.', + quick_poll_expired: 'Esta encuesta terminó.', + quick_poll_closed: 'Esta encuesta está cerrada, así que los horarios son finales.', + quick_poll_full: 'Todos los lugares de esta encuesta están ocupados.', + quick_poll_rate_limited: 'Con calma. Inténtalo de nuevo un poco más tarde.', + quick_poll_slots_required: 'Pinta al menos una hora primero.', + invalid_quick_poll: 'Algo de esta encuesta no está bien. Revísala e inténtalo de nuevo.', + invalid_quick_poll_title: 'Los títulos tienen hasta 80 caracteres.', + invalid_quick_poll_timezone: 'Elige una zona horaria de la lista.', + invalid_quick_poll_window: 'Elige de 1 a 14 días, no todos en el pasado.', + invalid_quick_poll_hours: 'El día tiene que terminar al menos un bloque después de empezar.', + invalid_quick_poll_slot_minutes: 'Elige bloques de 30 o 60 minutos.', + invalid_quick_poll_duration: 'Los planes duran de 15 minutos a 24 horas.', + invalid_quick_poll_ttl: 'Elige cuánto tiempo queda abierta la encuesta.', + invalid_quick_poll_people: 'Una encuesta admite de 2 a 15 personas.', + invalid_quick_poll_name: 'Los nombres tienen de 1 a 40 caracteres.', + invalid_slot: 'Algunas de esas horas están fuera de la encuesta.', + invalid_slots: 'Esas horas no se guardaron. ¿Lo intentamos otra vez?', + duplicate_slot: 'Una hora aparece dos veces. ¿Lo intentamos otra vez?', + not_allowed: 'Solo quien creó la encuesta puede hacer eso.', + }, +} satisfies Translation diff --git a/packages/i18n/src/fr.ts b/packages/i18n/src/fr.ts index d66ee74b..0cc5c441 100644 --- a/packages/i18n/src/fr.ts +++ b/packages/i18n/src/fr.ts @@ -10,6 +10,7 @@ import { help } from './fr/help' import { search, filters, insights, deletedItems, activityFilter } from './fr/insights' import { people } from './fr/people' import { transfer } from './fr/transfer' +import { quickPolls } from './fr/quick-polls' /** * French (tu, written for France and other French-speaking places). Same files and keys as `./en`; a key missing here shows in English. Loaded on demand @@ -53,6 +54,7 @@ export const fr = { activityFilter, people, transfer, + quickPolls, empty, errors, } satisfies Translation diff --git a/packages/i18n/src/fr/quick-polls.ts b/packages/i18n/src/fr/quick-polls.ts new file mode 100644 index 00000000..da4c97c5 --- /dev/null +++ b/packages/i18n/src/fr/quick-polls.ts @@ -0,0 +1,27 @@ +import type { Translation } from '../locales' +import type * as en from '../en/quick-polls' + +export const quickPolls = { + errors: { + quick_poll_not_found: 'Ce lien de sondage ne mène nulle part.', + quick_poll_expired: 'Ce sondage est terminé.', + quick_poll_closed: 'Ce sondage est fermé, les horaires sont donc définitifs.', + quick_poll_full: 'Toutes les places de ce sondage sont prises.', + quick_poll_rate_limited: 'Doucement. Réessaie un peu plus tard.', + quick_poll_slots_required: "Peins au moins un créneau d'abord.", + invalid_quick_poll: 'Quelque chose cloche dans ce sondage. Vérifie et réessaie.', + invalid_quick_poll_title: "Les titres font jusqu'à 80 caractères.", + invalid_quick_poll_timezone: 'Choisis un fuseau horaire dans la liste.', + invalid_quick_poll_window: 'Choisis de 1 à 14 jours, pas tous dans le passé.', + invalid_quick_poll_hours: 'La journée doit finir au moins un créneau après son début.', + invalid_quick_poll_slot_minutes: 'Choisis des créneaux de 30 ou 60 minutes.', + invalid_quick_poll_duration: 'Les plans durent de 15 minutes à 24 heures.', + invalid_quick_poll_ttl: 'Choisis combien de temps le sondage reste ouvert.', + invalid_quick_poll_people: 'Un sondage accepte de 2 à 15 personnes.', + invalid_quick_poll_name: 'Les noms font de 1 à 40 caractères.', + invalid_slot: 'Certains de ces horaires sont hors du sondage.', + invalid_slots: "Ces horaires n'ont pas été enregistrés. On réessaie ?", + duplicate_slot: 'Un horaire apparaît deux fois. On réessaie ?', + not_allowed: 'Seule la personne qui a créé le sondage peut faire ça.', + }, +} satisfies Translation diff --git a/packages/i18n/src/pt.ts b/packages/i18n/src/pt.ts index a2e623ca..917daf31 100644 --- a/packages/i18n/src/pt.ts +++ b/packages/i18n/src/pt.ts @@ -10,6 +10,7 @@ import { help } from './pt/help' import { search, filters, insights, deletedItems, activityFilter } from './pt/insights' import { people } from './pt/people' import { transfer } from './pt/transfer' +import { quickPolls } from './pt/quick-polls' /** * Portuguese (você, written to read naturally in Brazil and Portugal). Same files and keys as `./en`; a key missing here shows in English. Loaded on demand @@ -53,6 +54,7 @@ export const pt = { activityFilter, people, transfer, + quickPolls, empty, errors, } satisfies Translation diff --git a/packages/i18n/src/pt/quick-polls.ts b/packages/i18n/src/pt/quick-polls.ts new file mode 100644 index 00000000..ab6562f4 --- /dev/null +++ b/packages/i18n/src/pt/quick-polls.ts @@ -0,0 +1,27 @@ +import type { Translation } from '../locales' +import type * as en from '../en/quick-polls' + +export const quickPolls = { + errors: { + quick_poll_not_found: 'Esse link de enquete não leva a lugar nenhum.', + quick_poll_expired: 'Esta enquete terminou.', + quick_poll_closed: 'Esta enquete está fechada, então os horários são finais.', + quick_poll_full: 'Todas as vagas desta enquete estão ocupadas.', + quick_poll_rate_limited: 'Calma. Tente de novo um pouco mais tarde.', + quick_poll_slots_required: 'Pinte pelo menos um horário primeiro.', + invalid_quick_poll: 'Algo nesta enquete não está certo. Confira e tente de novo.', + invalid_quick_poll_title: 'Títulos têm até 80 caracteres.', + invalid_quick_poll_timezone: 'Escolha um fuso horário da lista.', + invalid_quick_poll_window: 'Escolha de 1 a 14 dias, não todos no passado.', + invalid_quick_poll_hours: 'O dia precisa terminar pelo menos um bloco depois de começar.', + invalid_quick_poll_slot_minutes: 'Escolha blocos de 30 ou 60 minutos.', + invalid_quick_poll_duration: 'Planos duram de 15 minutos a 24 horas.', + invalid_quick_poll_ttl: 'Escolha por quanto tempo a enquete fica aberta.', + invalid_quick_poll_people: 'Uma enquete aceita de 2 a 15 pessoas.', + invalid_quick_poll_name: 'Nomes têm de 1 a 40 caracteres.', + invalid_slot: 'Alguns desses horários estão fora da enquete.', + invalid_slots: 'Esses horários não foram salvos. Tentamos de novo?', + duplicate_slot: 'Um horário aparece duas vezes. Tentamos de novo?', + not_allowed: 'Só quem criou a enquete pode fazer isso.', + }, +} satisfies Translation From a573d024146be2fb91862ec4cc47e751d3b94247 Mon Sep 17 00:00:00 2001 From: Musa Kaleem <131704022+Musa-Kal@users.noreply.github.com> Date: Sun, 22 Nov 2026 18:33:38 -0500 Subject: [PATCH 05/21] docs: document quick polls Co-authored-by: Ferrin <177692050+Ferrin-Y@users.noreply.github.com> Co-authored-by: noorelmosrati <182049385+noorelmosrati@users.noreply.github.com> --- AGENTS.md | 4 +- ...urity-definer-rpcs-for-multi-row-writes.md | 2 +- docs/adr/0022-quick-polls-without-accounts.md | 25 + docs/adr/README.md | 1 + docs/agent-map.json | 673 ++++++++++++------ docs/architecture.md | 29 +- docs/security.md | 39 +- docs/testing.md | 1 + 8 files changed, 537 insertions(+), 237 deletions(-) create mode 100644 docs/adr/0022-quick-polls-without-accounts.md diff --git a/AGENTS.md b/AGENTS.md index 544de1df..544a5978 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -69,8 +69,8 @@ passes; if a journey changed, its e2e spec passes. Report the commands you ran a - New public function: `security definer`, `set search_path = ''`, schema-qualify every name, then `revoke execute on function public.f(...) from public, anon;` and `grant execute on function public.f(...) to authenticated, service_role;` (Supabase's default - privileges let `anon` execute every new public function). Only invite previews, `email_unsubscribe` - and guest link RPCs are anon-callable; adding one means updating `01_schema.test.sql`, ADR 4 and `docs/security.md`. + privileges let `anon` execute every new public function). Only invite previews, `email_unsubscribe`, + guest link and quick poll RPCs are anon-callable; adding one means updating `01_schema.test.sql`, ADR 4 and `docs/security.md`. - Every new table in `public`: RLS on, policies with `(select auth.uid())` and `group_id = any (array(select private.my_group_ids()))`, revoke-all then column grants, an index per foreign key, pgTAP for who can and who cannot. diff --git a/docs/adr/0004-security-definer-rpcs-for-multi-row-writes.md b/docs/adr/0004-security-definer-rpcs-for-multi-row-writes.md index 80f3cbf1..ba8e1114 100644 --- a/docs/adr/0004-security-definer-rpcs-for-multi-row-writes.md +++ b/docs/adr/0004-security-definer-rpcs-for-multi-row-writes.md @@ -15,7 +15,7 @@ Tables that need multi-row consistency get no insert or update policy at all. Wr - Each one sets `search_path = ''` and schema-qualifies every name, so a caller cannot shadow a table or function. - Errors use one shape: `message` is a stable snake_case code, `detail` is readable English, `errcode` is one of `42501`, `PT404` (HTTP 404), `22023` or `23514`. Clients translate the code, never the English. - Invariants that must hold whatever path wrote the row are deferred constraint triggers checked at commit: one owner per group, splits sum to the amount. -- `execute` is revoked from `public` and `anon` and granted to `authenticated` (and `service_role`). `invite_preview`, `invite_preview_v2` and `friend_invite_preview` (the link code is the credential, [ADR 19](0019-placeholder-members-and-claiming.md)), `email_unsubscribe` ([ADR 11](0011-notification-prefs-and-email.md), the signed token is the credential) and the two guest link RPCs, `guest_link_preview` and `set_guest_availability` ([ADR 16](0016-guest-availability-links.md)), are the only exceptions callable by `anon`. +- `execute` is revoked from `public` and `anon` and granted to `authenticated` (and `service_role`). `invite_preview`, `invite_preview_v2` and `friend_invite_preview` (the link code is the credential, [ADR 19](0019-placeholder-members-and-claiming.md)), `email_unsubscribe` ([ADR 11](0011-notification-prefs-and-email.md), the signed token is the credential) and the two guest link RPCs, `guest_link_preview` and `set_guest_availability` ([ADR 16](0016-guest-availability-links.md)), and the five quick poll RPCs, `create_quick_poll`, `quick_poll_preview`, `set_quick_poll_availability`, `close_quick_poll` and `delete_quick_poll` ([ADR 22](0022-quick-polls-without-accounts.md), the poll code and a token are the credentials), are the only exceptions callable by `anon`. Single-row writes that RLS can judge stay direct: profile fields, group settings, event details, RSVPs, comments, notifications, push tokens, blocks. diff --git a/docs/adr/0022-quick-polls-without-accounts.md b/docs/adr/0022-quick-polls-without-accounts.md new file mode 100644 index 00000000..88fbc7d7 --- /dev/null +++ b/docs/adr/0022-quick-polls-without-accounts.md @@ -0,0 +1,25 @@ +# 22. Quick polls without accounts + +- Status: accepted +- Date: 2026-11-22 + +## Context + +Finding a time with people who are not in a group (a one off dinner, a call with strangers) meant making a group and a plan first. Guest links ([ADR 16](0016-guest-availability-links.md)) let outsiders answer, but someone still needs an account, a group and a plan. Issue 50 asks for a poll anyone can make from the landing page, share as a link, and answer with no account at all, where everyone sees everyone's times. + +## Decision + +- Quick polls are their own tables, with no group, event or auth user: `quick_polls` (code, grid, expiry, settings), `quick_poll_answers` (one per browser, numbered by seat, a name only when the poll asks for one) and `quick_poll_slots` (the same shape as `availability`). Nothing in groups or plans changes, and no existing policy has to learn about them. +- Clients never touch the tables. RLS is on with no policies and `anon` and `authenticated` hold no grants. Five `security definer` RPCs are the whole surface, callable by `anon` and `authenticated`: `create_quick_poll`, `quick_poll_preview`, `set_quick_poll_availability`, `close_quick_poll` and `delete_quick_poll`. +- Tokens, not sessions, as for guests. Creating a poll returns a 24 byte creator token; the database keeps its sha256. The same token is the creator's answer token, so the creator answers like anyone else and takes a seat. Every other browser gets its own token on its first save. Only the creator token closes or deletes a poll. +- One owner per rule. `private.quick_poll_status` decides `expired`, `closed`, `full` or `open` for every RPC. The slot grid check moved out of `private.event_slots` into `private.grid_slots`, which both plans and quick polls call. The limits (2 to 15 people, 10 by default, 1 to 14 days, titles up to 80 characters, `24h` or `7d`) live in `packages/core` and the SQL checks together. +- Polls are small and short lived: at most 15 people, and they last 24 hours or 7 days. The hourly `purge-quick-polls` job deletes expired polls with their answers. +- The app is a static site that talks straight to Supabase, so the create rate limit lives in the database: 5 polls an hour per client and 200 an hour in all, serialized by an advisory lock. The client is the sha256 of the first `x-forwarded-for` entry PostgREST hands over in `request.headers`. Those hashes go in `private.quick_poll_creates`, kept an hour, not on the poll, so deleting a poll does not give quota back and nothing about the client outlives the hour. + +## Consequences + +- Anyone with the code sees every answer's name and times until the poll expires; that is the feature. Creators choose whether to ask for names; without them answers show as seat numbers. +- Five more definer functions open to the internet. pgTAP (`36_quick_polls.test.sql`) covers table access, every create check, names on and off, seats and the cap, the creator token, each status, close, delete, the purge and both rate limits; `01_schema.test.sql` pins the anon allowlist and the cron job. +- The per client limit is only as good as `x-forwarded-for`. A client can send its own header, and its value then comes first, so the per client limit slows honest mistakes and casual scripts, not a determined abuser. The global 200 an hour is the backstop; raising it, or keying on a header the platform sets itself, is a migration. +- A browser that loses its token cannot edit its answer, and a creator who loses theirs cannot close or delete the poll; it still expires within 7 days. +- Answers are never removed one by one, so seats are stable and never reused; the creator has no way to remove a stranger's answer short of deleting the poll. diff --git a/docs/adr/README.md b/docs/adr/README.md index 2f102d15..85171111 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -25,6 +25,7 @@ Short notes on decisions that shape the codebase: what we were facing, what we c | [0019](0019-placeholder-members-and-claiming.md) | Placeholder members and claiming them | | [0020](0020-group-types-restorable-deletes-and-shared-notes.md) | Group types, restorable deletes, covers and shared notes | | [0021](0021-receipt-scanning-and-attachments.md) | Receipt scanning on the device, several attachments | +| [0022](0022-quick-polls-without-accounts.md) | Quick polls without accounts | ## Writing a new one diff --git a/docs/agent-map.json b/docs/agent-map.json index 80da4207..6bbe3989 100644 --- a/docs/agent-map.json +++ b/docs/agent-map.json @@ -266,7 +266,7 @@ "invite_used_up", "invite_wrong_email" ], - "snapshotLine": 5544, + "snapshotLine": 5640, "definedIn": "supabase/migrations/20261113201107_friends_and_blocks.sql" }, { @@ -284,7 +284,7 @@ "invite_used_up", "invite_wrong_email" ], - "snapshotLine": 5599, + "snapshotLine": 5695, "definedIn": "supabase/migrations/20261113201103_placeholder_members.sql" }, { @@ -294,7 +294,7 @@ "securityDefiner": true, "execute": ["authenticated", "service_role"], "raises": ["invalid_friend", "not_a_friend"], - "snapshotLine": 5669, + "snapshotLine": 5765, "definedIn": "supabase/migrations/20261113201107_friends_and_blocks.sql" }, { @@ -304,7 +304,7 @@ "securityDefiner": true, "execute": ["authenticated", "service_role"], "raises": ["already_member", "placeholder_exists"], - "snapshotLine": 5696, + "snapshotLine": 5792, "definedIn": "supabase/migrations/20261113201103_placeholder_members.sql" }, { @@ -314,7 +314,7 @@ "securityDefiner": true, "execute": ["authenticated", "service_role"], "raises": [], - "snapshotLine": 5774, + "snapshotLine": 5870, "definedIn": "supabase/migrations/20261113201103_placeholder_members.sql" }, { @@ -324,7 +324,7 @@ "securityDefiner": true, "execute": ["authenticated", "service_role"], "raises": ["invalid_friend", "person_not_found"], - "snapshotLine": 5843, + "snapshotLine": 5939, "definedIn": "supabase/migrations/20261113201107_friends_and_blocks.sql" }, { @@ -334,7 +334,7 @@ "securityDefiner": true, "execute": ["authenticated", "service_role"], "raises": ["not_authenticated"], - "snapshotLine": 5880, + "snapshotLine": 5976, "definedIn": "supabase/migrations/20261105160000_edge_function_hooks.sql" }, { @@ -344,7 +344,7 @@ "securityDefiner": true, "execute": ["authenticated", "service_role"], "raises": [], - "snapshotLine": 5909, + "snapshotLine": 6005, "definedIn": "supabase/migrations/20261114154849_block_shared_expenses.sql" }, { @@ -354,7 +354,7 @@ "securityDefiner": true, "execute": ["authenticated", "service_role"], "raises": ["event_done"], - "snapshotLine": 5945, + "snapshotLine": 6041, "definedIn": "supabase/migrations/20261105071521_rpc_events_timeline.sql" }, { @@ -364,9 +364,19 @@ "securityDefiner": true, "execute": ["authenticated", "service_role"], "raises": [], - "snapshotLine": 5972, + "snapshotLine": 6068, "definedIn": "supabase/migrations/20261113100301_two_factor_storage_and_limits.sql" }, + { + "name": "public.close_quick_poll", + "args": "code text, token text", + "returns": "void", + "securityDefiner": true, + "execute": ["anon", "authenticated", "service_role"], + "raises": ["not_allowed", "quick_poll_not_found"], + "snapshotLine": 6091, + "definedIn": "supabase/migrations/20261122232215_quick_polls.sql" + }, { "name": "public.create_expense", "args": "payload jsonb", @@ -374,7 +384,7 @@ "securityDefiner": true, "execute": ["authenticated", "service_role"], "raises": [], - "snapshotLine": 5995, + "snapshotLine": 6114, "definedIn": "supabase/migrations/20261113091955_expense_entry.sql" }, { @@ -384,7 +394,7 @@ "securityDefiner": true, "execute": ["authenticated", "service_role"], "raises": [], - "snapshotLine": 6009, + "snapshotLine": 6128, "definedIn": "supabase/migrations/20261114193218_request_keys.sql" }, { @@ -394,7 +404,7 @@ "securityDefiner": true, "execute": ["authenticated", "service_role"], "raises": [], - "snapshotLine": 6035, + "snapshotLine": 6154, "definedIn": "supabase/migrations/20261114193218_request_keys.sql" }, { @@ -404,7 +414,7 @@ "securityDefiner": true, "execute": ["authenticated", "service_role"], "raises": ["invalid_email", "invalid_friend", "too_many_invites"], - "snapshotLine": 6087, + "snapshotLine": 6206, "definedIn": "supabase/migrations/20261113201107_friends_and_blocks.sql" }, { @@ -414,7 +424,7 @@ "securityDefiner": true, "execute": ["authenticated", "service_role"], "raises": ["group_name_required", "invalid_currency"], - "snapshotLine": 6170, + "snapshotLine": 6289, "definedIn": "supabase/migrations/20261105071504_rpc_groups.sql" }, { @@ -424,7 +434,7 @@ "securityDefiner": true, "execute": ["authenticated", "service_role"], "raises": ["group_name_required", "invalid_currency", "trip_dates_invalid"], - "snapshotLine": 6208, + "snapshotLine": 6327, "definedIn": "supabase/migrations/20261113213126_group_types_restore_and_whiteboard.sql" }, { @@ -439,7 +449,7 @@ "invalid_guest_limit", "invalid_guest_link_ttl" ], - "snapshotLine": 6276, + "snapshotLine": 6395, "definedIn": "supabase/migrations/20261113170311_guest_links.sql" }, { @@ -456,7 +466,7 @@ "invalid_role", "not_allowed" ], - "snapshotLine": 6351, + "snapshotLine": 6470, "definedIn": "supabase/migrations/20261105071508_rpc_invites.sql" }, { @@ -466,9 +476,30 @@ "securityDefiner": true, "execute": ["authenticated", "service_role"], "raises": ["mfa_required"], - "snapshotLine": 6405, + "snapshotLine": 6524, "definedIn": "supabase/migrations/20261113100257_two_factor_enforcement.sql" }, + { + "name": "public.create_quick_poll", + "args": "payload jsonb", + "returns": "TABLE(code text, creator_token text, expires_at timestamp with time zone)", + "securityDefiner": true, + "execute": ["anon", "authenticated", "service_role"], + "raises": [ + "invalid_quick_poll", + "invalid_quick_poll_duration", + "invalid_quick_poll_hours", + "invalid_quick_poll_people", + "invalid_quick_poll_slot_minutes", + "invalid_quick_poll_timezone", + "invalid_quick_poll_title", + "invalid_quick_poll_ttl", + "invalid_quick_poll_window", + "quick_poll_rate_limited" + ], + "snapshotLine": 6561, + "definedIn": "supabase/migrations/20261122232215_quick_polls.sql" + }, { "name": "public.delete_expense", "args": "id uuid", @@ -476,7 +507,7 @@ "securityDefiner": true, "execute": ["authenticated", "service_role"], "raises": ["split_member_not_in_group"], - "snapshotLine": 6442, + "snapshotLine": 6675, "definedIn": "supabase/migrations/20261113091955_expense_entry.sql" }, { @@ -486,7 +517,7 @@ "securityDefiner": true, "execute": ["authenticated", "service_role"], "raises": ["direct_group_not_deletable", "group_has_balances", "not_allowed"], - "snapshotLine": 6480, + "snapshotLine": 6713, "definedIn": "supabase/migrations/20261113213127_deleted_groups_everywhere.sql" }, { @@ -496,9 +527,19 @@ "securityDefiner": true, "execute": ["authenticated", "service_role"], "raises": ["not_authenticated"], - "snapshotLine": 6531, + "snapshotLine": 6764, "definedIn": "supabase/migrations/20261113201103_placeholder_members.sql" }, + { + "name": "public.delete_quick_poll", + "args": "code text, token text", + "returns": "void", + "securityDefiner": true, + "execute": ["anon", "authenticated", "service_role"], + "raises": ["not_allowed", "quick_poll_not_found"], + "snapshotLine": 6844, + "definedIn": "supabase/migrations/20261122232215_quick_polls.sql" + }, { "name": "public.delete_settlement", "args": "id uuid", @@ -506,7 +547,7 @@ "securityDefiner": true, "execute": ["authenticated", "service_role"], "raises": ["member_not_in_group", "not_allowed", "settlement_not_found"], - "snapshotLine": 6635, + "snapshotLine": 6891, "definedIn": "supabase/migrations/20261106010000_integrity_fixes.sql" }, { @@ -516,7 +557,7 @@ "securityDefiner": true, "execute": ["authenticated", "service_role"], "raises": ["invalid_cursor"], - "snapshotLine": 6680, + "snapshotLine": 6936, "definedIn": "supabase/migrations/20261113172837_search_insights.sql" }, { @@ -526,7 +567,7 @@ "securityDefiner": true, "execute": ["service_role"], "raises": [], - "snapshotLine": 6771, + "snapshotLine": 7027, "definedIn": "supabase/migrations/20261113062656_notification_prefs_and_email.sql" }, { @@ -536,7 +577,7 @@ "securityDefiner": true, "execute": ["anon", "authenticated", "service_role"], "raises": ["invalid_payload", "invalid_unsubscribe_link"], - "snapshotLine": 6806, + "snapshotLine": 7062, "definedIn": "supabase/migrations/20261113100301_two_factor_storage_and_limits.sql" }, { @@ -546,7 +587,7 @@ "securityDefiner": true, "execute": ["authenticated", "service_role"], "raises": [], - "snapshotLine": 6896, + "snapshotLine": 7152, "definedIn": "supabase/migrations/20261113213127_deleted_groups_everywhere.sql" }, { @@ -556,7 +597,7 @@ "securityDefiner": true, "execute": ["service_role"], "raises": [], - "snapshotLine": 6974, + "snapshotLine": 7230, "definedIn": "supabase/migrations/20261113100257_two_factor_enforcement.sql" }, { @@ -566,7 +607,7 @@ "securityDefiner": true, "execute": ["authenticated", "service_role"], "raises": ["invalid_cursor", "invalid_friend"], - "snapshotLine": 6985, + "snapshotLine": 7241, "definedIn": "supabase/migrations/20261113172837_search_insights.sql" }, { @@ -576,7 +617,7 @@ "securityDefiner": true, "execute": ["authenticated", "service_role"], "raises": [], - "snapshotLine": 7090, + "snapshotLine": 7346, "definedIn": "supabase/migrations/20261113213127_deleted_groups_everywhere.sql" }, { @@ -586,7 +627,7 @@ "securityDefiner": true, "execute": ["anon", "authenticated", "service_role"], "raises": ["invite_not_found"], - "snapshotLine": 7128, + "snapshotLine": 7384, "definedIn": "supabase/migrations/20261113201107_friends_and_blocks.sql" }, { @@ -596,7 +637,7 @@ "securityDefiner": true, "execute": ["authenticated", "service_role"], "raises": ["invalid_friend", "not_a_friend"], - "snapshotLine": 7177, + "snapshotLine": 7433, "definedIn": "supabase/migrations/20261113201103_placeholder_members.sql" }, { @@ -606,7 +647,7 @@ "securityDefiner": true, "execute": ["anon", "authenticated", "service_role"], "raises": ["guest_link_not_found"], - "snapshotLine": 7238, + "snapshotLine": 7494, "definedIn": "supabase/migrations/20261113170311_guest_links.sql" }, { @@ -616,7 +657,7 @@ "securityDefiner": true, "execute": ["authenticated", "service_role"], "raises": ["import_too_large", "invalid_import", "not_a_friend"], - "snapshotLine": 7348, + "snapshotLine": 7604, "definedIn": "supabase/migrations/20261113204239_export_and_import.sql" }, { @@ -626,7 +667,7 @@ "securityDefiner": true, "execute": ["authenticated", "service_role"], "raises": ["import_too_large", "invalid_import"], - "snapshotLine": 7704, + "snapshotLine": 7960, "definedIn": "supabase/migrations/20261113204239_export_and_import.sql" }, { @@ -636,7 +677,7 @@ "securityDefiner": true, "execute": ["anon", "authenticated", "service_role"], "raises": ["invite_not_found"], - "snapshotLine": 7765, + "snapshotLine": 8021, "definedIn": "supabase/migrations/20261113201103_placeholder_members.sql" }, { @@ -646,7 +687,7 @@ "securityDefiner": true, "execute": ["anon", "authenticated", "service_role"], "raises": ["invite_not_found"], - "snapshotLine": 7824, + "snapshotLine": 8080, "definedIn": "supabase/migrations/20261113201103_placeholder_members.sql" }, { @@ -656,7 +697,7 @@ "securityDefiner": true, "execute": ["authenticated", "service_role"], "raises": ["member_has_balance", "owner_must_transfer"], - "snapshotLine": 7916, + "snapshotLine": 8172, "definedIn": "supabase/migrations/20261113201103_placeholder_members.sql" }, { @@ -673,7 +714,7 @@ "not_allowed", "split_member_not_in_group" ], - "snapshotLine": 7971, + "snapshotLine": 8227, "definedIn": "supabase/migrations/20261113153242_recurring_editing.sql" }, { @@ -683,7 +724,7 @@ "securityDefiner": true, "execute": ["service_role"], "raises": [], - "snapshotLine": 8088, + "snapshotLine": 8344, "definedIn": "supabase/migrations/20261113100257_two_factor_enforcement.sql" }, { @@ -693,7 +734,7 @@ "securityDefiner": true, "execute": ["authenticated", "service_role"], "raises": [], - "snapshotLine": 8102, + "snapshotLine": 8358, "definedIn": "supabase/migrations/20261113100257_two_factor_enforcement.sql" }, { @@ -703,7 +744,7 @@ "securityDefiner": true, "execute": ["authenticated", "service_role"], "raises": [], - "snapshotLine": 8113, + "snapshotLine": 8369, "definedIn": "supabase/migrations/20261113201107_friends_and_blocks.sql" }, { @@ -713,7 +754,7 @@ "securityDefiner": true, "execute": ["authenticated", "service_role"], "raises": [], - "snapshotLine": 8134, + "snapshotLine": 8390, "definedIn": "supabase/migrations/20261113213126_group_types_restore_and_whiteboard.sql" }, { @@ -723,7 +764,7 @@ "securityDefiner": true, "execute": ["authenticated", "service_role"], "raises": [], - "snapshotLine": 8152, + "snapshotLine": 8408, "definedIn": "supabase/migrations/20261113201107_friends_and_blocks.sql" }, { @@ -733,7 +774,7 @@ "securityDefiner": true, "execute": ["authenticated", "service_role"], "raises": [], - "snapshotLine": 8185, + "snapshotLine": 8441, "definedIn": "supabase/migrations/20261113100301_two_factor_storage_and_limits.sql" }, { @@ -743,7 +784,7 @@ "securityDefiner": true, "execute": ["authenticated", "service_role"], "raises": [], - "snapshotLine": 8211, + "snapshotLine": 8467, "definedIn": "supabase/migrations/20261113213127_deleted_groups_everywhere.sql" }, { @@ -753,7 +794,7 @@ "securityDefiner": true, "execute": ["service_role"], "raises": [], - "snapshotLine": 8266, + "snapshotLine": 8522, "definedIn": "supabase/migrations/20261113100301_two_factor_storage_and_limits.sql" }, { @@ -763,9 +804,19 @@ "securityDefiner": true, "execute": ["service_role"], "raises": [], - "snapshotLine": 8279, + "snapshotLine": 8535, "definedIn": "supabase/migrations/20261114015104_expense_attachments.sql" }, + { + "name": "public.quick_poll_preview", + "args": "code text, token text DEFAULT NULL::text", + "returns": "TABLE(status text, title text, timezone text, window_start date, window_end date, day_start_minute integer, day_end_minute integer, slot_minutes integer, duration_minutes integer, names_required boolean, max_people integer, expires_at timestamp with time zone, is_creator boolean, answers jsonb)", + "securityDefiner": true, + "execute": ["anon", "authenticated", "service_role"], + "raises": ["quick_poll_not_found"], + "snapshotLine": 8552, + "definedIn": "supabase/migrations/20261122232215_quick_polls.sql" + }, { "name": "public.record_mfa_recover_attempt", "args": "target uuid", @@ -773,7 +824,7 @@ "securityDefiner": true, "execute": ["service_role"], "raises": [], - "snapshotLine": 8296, + "snapshotLine": 8611, "definedIn": "supabase/migrations/20261113100301_two_factor_storage_and_limits.sql" }, { @@ -789,7 +840,7 @@ "note_too_long", "nothing_owed" ], - "snapshotLine": 8343, + "snapshotLine": 8658, "definedIn": "supabase/migrations/20261113115303_debt_reminders.sql" }, { @@ -799,7 +850,7 @@ "securityDefiner": true, "execute": ["authenticated", "service_role"], "raises": ["member_not_found", "placeholder_already_reminded", "placeholder_no_email"], - "snapshotLine": 8407, + "snapshotLine": 8722, "definedIn": "supabase/migrations/20261113201103_placeholder_members.sql" }, { @@ -809,7 +860,7 @@ "securityDefiner": true, "execute": ["authenticated", "service_role"], "raises": ["friend_has_balance"], - "snapshotLine": 8450, + "snapshotLine": 8765, "definedIn": "supabase/migrations/20261113201107_friends_and_blocks.sql" }, { @@ -819,7 +870,7 @@ "securityDefiner": true, "execute": ["authenticated", "service_role"], "raises": ["guest_not_found"], - "snapshotLine": 8477, + "snapshotLine": 8792, "definedIn": "supabase/migrations/20261113170311_guest_links.sql" }, { @@ -835,7 +886,7 @@ "not_allowed", "use_leave_group" ], - "snapshotLine": 8509, + "snapshotLine": 8824, "definedIn": "supabase/migrations/20261106010000_integrity_fixes.sql" }, { @@ -845,7 +896,7 @@ "securityDefiner": true, "execute": ["authenticated", "service_role"], "raises": ["member_has_balance", "member_not_found", "not_allowed"], - "snapshotLine": 8556, + "snapshotLine": 8871, "definedIn": "supabase/migrations/20261113201103_placeholder_members.sql" }, { @@ -855,7 +906,7 @@ "securityDefiner": true, "execute": ["authenticated", "service_role"], "raises": ["event_not_polling", "member_not_found"], - "snapshotLine": 8594, + "snapshotLine": 8909, "definedIn": "supabase/migrations/20261113201103_placeholder_members.sql" }, { @@ -865,7 +916,7 @@ "securityDefiner": true, "execute": ["authenticated", "service_role"], "raises": ["split_member_not_in_group"], - "snapshotLine": 8663, + "snapshotLine": 8978, "definedIn": "supabase/migrations/20261113091955_expense_entry.sql" }, { @@ -875,7 +926,7 @@ "securityDefiner": true, "execute": ["authenticated", "service_role"], "raises": ["group_not_found", "not_a_member"], - "snapshotLine": 8709, + "snapshotLine": 9024, "definedIn": "supabase/migrations/20261113213127_deleted_groups_everywhere.sql" }, { @@ -885,7 +936,7 @@ "securityDefiner": true, "execute": ["authenticated", "service_role"], "raises": ["member_not_in_group", "not_allowed", "settlement_not_found"], - "snapshotLine": 8756, + "snapshotLine": 9071, "definedIn": "supabase/migrations/20261113115254_payments_v2.sql" }, { @@ -895,7 +946,7 @@ "securityDefiner": true, "execute": ["authenticated", "service_role"], "raises": ["guest_link_not_found", "not_allowed"], - "snapshotLine": 8801, + "snapshotLine": 9116, "definedIn": "supabase/migrations/20261113170311_guest_links.sql" }, { @@ -905,7 +956,7 @@ "securityDefiner": true, "execute": ["authenticated", "service_role"], "raises": ["whiteboard_conflict", "whiteboard_too_long"], - "snapshotLine": 8852, + "snapshotLine": 9167, "definedIn": "supabase/migrations/20261113213126_group_types_restore_and_whiteboard.sql" }, { @@ -915,7 +966,7 @@ "securityDefiner": true, "execute": ["authenticated", "service_role"], "raises": ["event_not_schedulable", "starts_at_required"], - "snapshotLine": 8913, + "snapshotLine": 9228, "definedIn": "supabase/migrations/20261106010000_integrity_fixes.sql" }, { @@ -925,7 +976,7 @@ "securityDefiner": true, "execute": ["authenticated", "service_role"], "raises": ["invalid_cursor", "invalid_date_range", "invalid_query"], - "snapshotLine": 8947, + "snapshotLine": 9262, "definedIn": "supabase/migrations/20261113172837_search_insights.sql" }, { @@ -935,7 +986,7 @@ "securityDefiner": true, "execute": ["authenticated", "service_role"], "raises": ["duplicate_slot", "event_not_polling", "invalid_slot", "invalid_slots"], - "snapshotLine": 9209, + "snapshotLine": 9524, "definedIn": "supabase/migrations/20261106020000_availability_lock.sql" }, { @@ -945,7 +996,7 @@ "securityDefiner": true, "execute": ["authenticated", "service_role"], "raises": ["invalid_splits", "split_member_not_in_group"], - "snapshotLine": 9298, + "snapshotLine": 9613, "definedIn": "supabase/migrations/20261113091955_expense_entry.sql" }, { @@ -955,7 +1006,7 @@ "securityDefiner": true, "execute": ["authenticated", "service_role"], "raises": [], - "snapshotLine": 9381, + "snapshotLine": 9696, "definedIn": "supabase/migrations/20261114015104_expense_attachments.sql" }, { @@ -976,7 +1027,7 @@ "guest_slots_required", "invalid_guest_name" ], - "snapshotLine": 9398, + "snapshotLine": 9713, "definedIn": "supabase/migrations/20261113170311_guest_links.sql" }, { @@ -991,7 +1042,7 @@ "not_allowed", "use_transfer_ownership" ], - "snapshotLine": 9488, + "snapshotLine": 9803, "definedIn": "supabase/migrations/20261105071504_rpc_groups.sql" }, { @@ -1001,9 +1052,27 @@ "securityDefiner": true, "execute": ["authenticated", "service_role"], "raises": ["invalid_notification_category", "notification_setting_required"], - "snapshotLine": 9528, + "snapshotLine": 9843, "definedIn": "supabase/migrations/20261113100301_two_factor_storage_and_limits.sql" }, + { + "name": "public.set_quick_poll_availability", + "args": "code text, name text, token text, slots jsonb", + "returns": "TABLE(answer_token text, saved integer)", + "securityDefiner": true, + "execute": ["anon", "authenticated", "service_role"], + "raises": [ + "invalid_quick_poll_name", + "quick_poll_closed", + "quick_poll_expired", + "quick_poll_full", + "quick_poll_not_found", + "quick_poll_rate_limited", + "quick_poll_slots_required" + ], + "snapshotLine": 9880, + "definedIn": "supabase/migrations/20261122232215_quick_polls.sql" + }, { "name": "public.settle_all", "args": "group_id uuid, settled_on date DEFAULT NULL::date, note text DEFAULT NULL::text", @@ -1011,7 +1080,7 @@ "securityDefiner": true, "execute": ["authenticated", "service_role"], "raises": [], - "snapshotLine": 9565, + "snapshotLine": 9967, "definedIn": "supabase/migrations/20261113115301_group_debts_and_bulk_settle.sql" }, { @@ -1027,7 +1096,7 @@ "invalid_recipient", "member_not_found" ], - "snapshotLine": 9604, + "snapshotLine": 10006, "definedIn": "supabase/migrations/20261106010000_integrity_fixes.sql" }, { @@ -1037,7 +1106,7 @@ "securityDefiner": true, "execute": ["authenticated", "service_role"], "raises": [], - "snapshotLine": 9662, + "snapshotLine": 10064, "definedIn": "supabase/migrations/20261113115254_payments_v2.sql" }, { @@ -1047,7 +1116,7 @@ "securityDefiner": true, "execute": ["authenticated", "service_role"], "raises": [], - "snapshotLine": 9699, + "snapshotLine": 10101, "definedIn": "supabase/migrations/20261114193218_request_keys.sql" }, { @@ -1057,7 +1126,7 @@ "securityDefiner": true, "execute": ["authenticated", "service_role"], "raises": ["invalid_amount", "invalid_parties", "invalid_payload", "nothing_owed"], - "snapshotLine": 9727, + "snapshotLine": 10129, "definedIn": "supabase/migrations/20261113213127_deleted_groups_everywhere.sql" }, { @@ -1067,7 +1136,7 @@ "securityDefiner": true, "execute": ["authenticated", "service_role"], "raises": [], - "snapshotLine": 9811, + "snapshotLine": 10213, "definedIn": "supabase/migrations/20261105210000_query_performance.sql" }, { @@ -1077,7 +1146,7 @@ "securityDefiner": true, "execute": ["authenticated", "service_role"], "raises": ["not_allowed", "recurring_not_found"], - "snapshotLine": 9871, + "snapshotLine": 10273, "definedIn": "supabase/migrations/20261113153242_recurring_editing.sql" }, { @@ -1087,7 +1156,7 @@ "securityDefiner": true, "execute": ["authenticated", "service_role"], "raises": ["invalid_currency", "invalid_date_range"], - "snapshotLine": 9920, + "snapshotLine": 10322, "definedIn": "supabase/migrations/20261113172837_search_insights.sql" }, { @@ -1097,7 +1166,7 @@ "securityDefiner": true, "execute": ["authenticated", "service_role"], "raises": ["already_owner", "member_not_found", "not_allowed"], - "snapshotLine": 10065, + "snapshotLine": 10467, "definedIn": "supabase/migrations/20261105071504_rpc_groups.sql" }, { @@ -1107,7 +1176,7 @@ "securityDefiner": true, "execute": ["authenticated", "service_role"], "raises": ["expense_not_found"], - "snapshotLine": 10103, + "snapshotLine": 10505, "definedIn": "supabase/migrations/20261113091955_expense_entry.sql" }, { @@ -1117,7 +1186,7 @@ "securityDefiner": true, "execute": ["authenticated", "service_role"], "raises": ["expense_not_found"], - "snapshotLine": 10122, + "snapshotLine": 10524, "definedIn": "supabase/migrations/20261113091955_expense_entry.sql" }, { @@ -1133,7 +1202,7 @@ "placeholder_exists", "too_many_invites" ], - "snapshotLine": 10138, + "snapshotLine": 10540, "definedIn": "supabase/migrations/20261113201103_placeholder_members.sql" }, { @@ -1158,7 +1227,7 @@ "split_member_not_in_group", "splits_sum_mismatch" ], - "snapshotLine": 10241, + "snapshotLine": 10643, "definedIn": "supabase/migrations/20261113153242_recurring_editing.sql" }, { @@ -1174,7 +1243,7 @@ "settlement_deleted", "settlement_not_found" ], - "snapshotLine": 10511, + "snapshotLine": 10913, "definedIn": "supabase/migrations/20261113115254_payments_v2.sql" } ], @@ -1523,9 +1592,9 @@ "returns": "jsonb", "securityDefiner": false, "execute": [], - "raises": ["duplicate_slot", "invalid_slot", "invalid_slots"], + "raises": [], "snapshotLine": 1333, - "definedIn": "supabase/migrations/20261113170311_guest_links.sql" + "definedIn": "supabase/migrations/20261122232215_quick_polls.sql" }, { "name": "private.events_activity", @@ -1534,7 +1603,7 @@ "securityDefiner": true, "execute": ["PUBLIC"], "raises": [], - "snapshotLine": 1399, + "snapshotLine": 1346, "definedIn": "supabase/migrations/20261105071528_activity_triggers.sql" }, { @@ -1544,7 +1613,7 @@ "securityDefiner": true, "execute": ["PUBLIC"], "raises": [], - "snapshotLine": 1427, + "snapshotLine": 1374, "definedIn": "supabase/migrations/20261105071531_notification_triggers.sql" }, { @@ -1554,7 +1623,7 @@ "securityDefiner": true, "execute": ["PUBLIC"], "raises": [], - "snapshotLine": 1467, + "snapshotLine": 1414, "definedIn": "supabase/migrations/20261105071531_notification_triggers.sql" }, { @@ -1564,7 +1633,7 @@ "securityDefiner": false, "execute": ["PUBLIC"], "raises": [], - "snapshotLine": 1497, + "snapshotLine": 1444, "definedIn": "supabase/migrations/20261113091955_expense_entry.sql" }, { @@ -1574,7 +1643,7 @@ "securityDefiner": true, "execute": ["PUBLIC"], "raises": [], - "snapshotLine": 1526, + "snapshotLine": 1473, "definedIn": "supabase/migrations/20261113201103_placeholder_members.sql" }, { @@ -1584,7 +1653,7 @@ "securityDefiner": true, "execute": ["PUBLIC"], "raises": [], - "snapshotLine": 1577, + "snapshotLine": 1524, "definedIn": "supabase/migrations/20261114072315_expense_notice_paid_share.sql" }, { @@ -1594,7 +1663,7 @@ "securityDefiner": true, "execute": [], "raises": [], - "snapshotLine": 1628, + "snapshotLine": 1575, "definedIn": "supabase/migrations/20261113091955_expense_entry.sql" }, { @@ -1604,7 +1673,7 @@ "securityDefiner": true, "execute": ["PUBLIC"], "raises": [], - "snapshotLine": 1674, + "snapshotLine": 1621, "definedIn": "supabase/migrations/20261113201103_placeholder_members.sql" }, { @@ -1614,7 +1683,7 @@ "securityDefiner": true, "execute": [], "raises": [], - "snapshotLine": 1732, + "snapshotLine": 1679, "definedIn": "supabase/migrations/20261113204239_export_and_import.sql" }, { @@ -1624,7 +1693,7 @@ "securityDefiner": true, "execute": [], "raises": [], - "snapshotLine": 1886, + "snapshotLine": 1833, "definedIn": "supabase/migrations/20261105071542_cron_jobs.sql" }, { @@ -1634,7 +1703,7 @@ "securityDefiner": true, "execute": [], "raises": [], - "snapshotLine": 1905, + "snapshotLine": 1852, "definedIn": "supabase/migrations/20261114193218_request_keys.sql" }, { @@ -1644,7 +1713,7 @@ "securityDefiner": true, "execute": [], "raises": [], - "snapshotLine": 1924, + "snapshotLine": 1871, "definedIn": "supabase/migrations/20261113115259_payment_methods.sql" }, { @@ -1654,7 +1723,7 @@ "securityDefiner": true, "execute": [], "raises": [], - "snapshotLine": 1939, + "snapshotLine": 1886, "definedIn": "supabase/migrations/20261113201103_placeholder_members.sql" }, { @@ -1664,7 +1733,7 @@ "securityDefiner": true, "execute": [], "raises": [], - "snapshotLine": 1953, + "snapshotLine": 1900, "definedIn": "supabase/migrations/20261113062656_notification_prefs_and_email.sql" }, { @@ -1674,7 +1743,7 @@ "securityDefiner": true, "execute": [], "raises": [], - "snapshotLine": 1968, + "snapshotLine": 1915, "definedIn": "supabase/migrations/20261113201103_placeholder_members.sql" }, { @@ -1684,7 +1753,7 @@ "securityDefiner": true, "execute": [], "raises": [], - "snapshotLine": 1985, + "snapshotLine": 1932, "definedIn": "supabase/migrations/20261113201103_placeholder_members.sql" }, { @@ -1694,7 +1763,7 @@ "securityDefiner": true, "execute": [], "raises": ["not_a_friend"], - "snapshotLine": 2011, + "snapshotLine": 1958, "definedIn": "supabase/migrations/20261113201107_friends_and_blocks.sql" }, { @@ -1704,9 +1773,19 @@ "securityDefiner": true, "execute": ["PUBLIC"], "raises": [], - "snapshotLine": 2059, + "snapshotLine": 2006, "definedIn": "supabase/migrations/20261106010000_integrity_fixes.sql" }, + { + "name": "private.grid_slots", + "args": "timezone text, window_start date, window_end date, day_start_minute integer, day_end_minute integer, slot_minutes integer, slots jsonb", + "returns": "jsonb", + "securityDefiner": false, + "execute": [], + "raises": ["duplicate_slot", "invalid_slot", "invalid_slots"], + "snapshotLine": 2039, + "definedIn": "supabase/migrations/20261122232215_quick_polls.sql" + }, { "name": "private.group_debts", "args": "gid uuid", @@ -1714,7 +1793,7 @@ "securityDefiner": true, "execute": [], "raises": [], - "snapshotLine": 2092, + "snapshotLine": 2105, "definedIn": "supabase/migrations/20261113115301_group_debts_and_bulk_settle.sql" }, { @@ -1724,7 +1803,7 @@ "securityDefiner": true, "execute": ["authenticated", "service_role"], "raises": [], - "snapshotLine": 2109, + "snapshotLine": 2122, "definedIn": "supabase/migrations/20261106000000_review_fixes.sql" }, { @@ -1734,7 +1813,7 @@ "securityDefiner": true, "execute": ["PUBLIC"], "raises": [], - "snapshotLine": 2120, + "snapshotLine": 2133, "definedIn": "supabase/migrations/20261113201103_placeholder_members.sql" }, { @@ -1744,7 +1823,7 @@ "securityDefiner": true, "execute": ["PUBLIC"], "raises": [], - "snapshotLine": 2162, + "snapshotLine": 2175, "definedIn": "supabase/migrations/20261113201103_placeholder_members.sql" }, { @@ -1754,7 +1833,7 @@ "securityDefiner": true, "execute": [], "raises": [], - "snapshotLine": 2192, + "snapshotLine": 2205, "definedIn": "supabase/migrations/20261113062656_notification_prefs_and_email.sql" }, { @@ -1764,7 +1843,7 @@ "securityDefiner": true, "execute": [], "raises": [], - "snapshotLine": 2218, + "snapshotLine": 2231, "definedIn": "supabase/migrations/20261113153242_recurring_editing.sql" }, { @@ -1774,7 +1853,7 @@ "securityDefiner": true, "execute": ["PUBLIC", "authenticated", "service_role"], "raises": [], - "snapshotLine": 2232, + "snapshotLine": 2245, "definedIn": "supabase/migrations/20261113213126_group_types_restore_and_whiteboard.sql" }, { @@ -1784,7 +1863,7 @@ "securityDefiner": true, "execute": ["PUBLIC"], "raises": [], - "snapshotLine": 2245, + "snapshotLine": 2258, "definedIn": "supabase/migrations/20261113213126_group_types_restore_and_whiteboard.sql" }, { @@ -1794,7 +1873,7 @@ "securityDefiner": true, "execute": ["PUBLIC"], "raises": ["group_currency_locked"], - "snapshotLine": 2269, + "snapshotLine": 2282, "definedIn": "supabase/migrations/20261105071427_money_tables.sql" }, { @@ -1804,7 +1883,7 @@ "securityDefiner": true, "execute": [], "raises": ["group_has_balances"], - "snapshotLine": 2291, + "snapshotLine": 2304, "definedIn": "supabase/migrations/20261113213127_deleted_groups_everywhere.sql" }, { @@ -1814,7 +1893,7 @@ "securityDefiner": true, "execute": [], "raises": ["rsvp_closed"], - "snapshotLine": 2317, + "snapshotLine": 2330, "definedIn": "supabase/migrations/20261113201103_placeholder_members.sql" }, { @@ -1824,7 +1903,7 @@ "securityDefiner": true, "execute": [], "raises": ["placeholder_member"], - "snapshotLine": 2357, + "snapshotLine": 2370, "definedIn": "supabase/migrations/20261113201103_placeholder_members.sql" }, { @@ -1834,7 +1913,7 @@ "securityDefiner": true, "execute": [], "raises": [], - "snapshotLine": 2415, + "snapshotLine": 2428, "definedIn": "supabase/migrations/20261113170311_guest_links.sql" }, { @@ -1844,7 +1923,7 @@ "securityDefiner": true, "execute": ["PUBLIC"], "raises": [], - "snapshotLine": 2431, + "snapshotLine": 2444, "definedIn": "supabase/migrations/20261105071417_profiles.sql" }, { @@ -1854,7 +1933,7 @@ "securityDefiner": true, "execute": [], "raises": [], - "snapshotLine": 2463, + "snapshotLine": 2476, "definedIn": "supabase/migrations/20261106010000_integrity_fixes.sql" }, { @@ -1864,7 +1943,7 @@ "securityDefiner": false, "execute": [], "raises": [], - "snapshotLine": 2475, + "snapshotLine": 2488, "definedIn": "supabase/migrations/20261113204239_export_and_import.sql" }, { @@ -1874,7 +1953,7 @@ "securityDefiner": false, "execute": [], "raises": [], - "snapshotLine": 2492, + "snapshotLine": 2505, "definedIn": "supabase/migrations/20261113204239_export_and_import.sql" }, { @@ -1884,7 +1963,7 @@ "securityDefiner": false, "execute": [], "raises": [], - "snapshotLine": 2508, + "snapshotLine": 2521, "definedIn": "supabase/migrations/20261113204239_export_and_import.sql" }, { @@ -1894,7 +1973,7 @@ "securityDefiner": false, "execute": [], "raises": [], - "snapshotLine": 2524, + "snapshotLine": 2537, "definedIn": "supabase/migrations/20261113204239_export_and_import.sql" }, { @@ -1904,7 +1983,7 @@ "securityDefiner": false, "execute": [], "raises": [], - "snapshotLine": 2541, + "snapshotLine": 2554, "definedIn": "supabase/migrations/20261113204239_export_and_import.sql" }, { @@ -1914,7 +1993,7 @@ "securityDefiner": false, "execute": [], "raises": [], - "snapshotLine": 2556, + "snapshotLine": 2569, "definedIn": "supabase/migrations/20261113204239_export_and_import.sql" }, { @@ -1924,7 +2003,7 @@ "securityDefiner": true, "execute": [], "raises": [], - "snapshotLine": 2569, + "snapshotLine": 2582, "definedIn": "supabase/migrations/20261113172837_search_insights.sql" }, { @@ -1934,7 +2013,7 @@ "securityDefiner": true, "execute": [], "raises": [], - "snapshotLine": 2598, + "snapshotLine": 2611, "definedIn": "supabase/migrations/20261105160000_edge_function_hooks.sql" }, { @@ -1944,7 +2023,7 @@ "securityDefiner": true, "execute": ["PUBLIC", "authenticated", "service_role"], "raises": [], - "snapshotLine": 2625, + "snapshotLine": 2638, "definedIn": "supabase/migrations/20261113213126_group_types_restore_and_whiteboard.sql" }, { @@ -1954,7 +2033,7 @@ "securityDefiner": true, "execute": ["PUBLIC", "authenticated", "service_role"], "raises": [], - "snapshotLine": 2643, + "snapshotLine": 2656, "definedIn": "supabase/migrations/20261113213126_group_types_restore_and_whiteboard.sql" }, { @@ -1964,7 +2043,7 @@ "securityDefiner": false, "execute": [], "raises": [], - "snapshotLine": 2658, + "snapshotLine": 2671, "definedIn": "supabase/migrations/20261113201103_placeholder_members.sql" }, { @@ -1984,7 +2063,7 @@ "securityDefiner": false, "execute": ["PUBLIC"], "raises": ["duplicate_user", "invalid_items", "items_required", "zero_shares"], - "snapshotLine": 2669, + "snapshotLine": 2682, "definedIn": "supabase/migrations/20261113091955_expense_entry.sql" }, { @@ -1994,7 +2073,7 @@ "securityDefiner": true, "execute": [], "raises": [], - "snapshotLine": 2767, + "snapshotLine": 2780, "definedIn": "supabase/migrations/20261113153242_recurring_editing.sql" }, { @@ -2004,7 +2083,7 @@ "securityDefiner": true, "execute": ["PUBLIC"], "raises": [], - "snapshotLine": 2778, + "snapshotLine": 2791, "definedIn": "supabase/migrations/20261105071528_activity_triggers.sql" }, { @@ -2014,7 +2093,7 @@ "securityDefiner": true, "execute": [], "raises": ["event_not_found", "not_allowed"], - "snapshotLine": 2796, + "snapshotLine": 2809, "definedIn": "supabase/migrations/20261106000000_review_fixes.sql" }, { @@ -2024,7 +2103,7 @@ "securityDefiner": false, "execute": [], "raises": [], - "snapshotLine": 2822, + "snapshotLine": 2835, "definedIn": "supabase/migrations/20261113062656_notification_prefs_and_email.sql" }, { @@ -2034,7 +2113,7 @@ "securityDefiner": true, "execute": [], "raises": [], - "snapshotLine": 2836, + "snapshotLine": 2849, "definedIn": "supabase/migrations/20261113091955_expense_entry.sql" }, { @@ -2044,7 +2123,7 @@ "securityDefiner": true, "execute": [], "raises": [], - "snapshotLine": 2955, + "snapshotLine": 2968, "definedIn": "supabase/migrations/20261105071504_rpc_groups.sql" }, { @@ -2054,7 +2133,7 @@ "securityDefiner": true, "execute": [], "raises": ["event_not_found"], - "snapshotLine": 2969, + "snapshotLine": 2982, "definedIn": "supabase/migrations/20261105071518_rpc_availability.sql" }, { @@ -2064,7 +2143,7 @@ "securityDefiner": true, "execute": ["anon", "authenticated", "service_role"], "raises": [], - "snapshotLine": 2989, + "snapshotLine": 3002, "definedIn": "supabase/migrations/20261113100257_two_factor_enforcement.sql" }, { @@ -2084,7 +2163,7 @@ "securityDefiner": true, "execute": [], "raises": [], - "snapshotLine": 3005, + "snapshotLine": 3018, "definedIn": "supabase/migrations/20261113213127_deleted_groups_everywhere.sql" }, { @@ -2094,7 +2173,7 @@ "securityDefiner": true, "execute": ["PUBLIC", "authenticated", "service_role"], "raises": [], - "snapshotLine": 3071, + "snapshotLine": 3084, "definedIn": "supabase/migrations/20261105071444_policy_helpers.sql" }, { @@ -2104,7 +2183,7 @@ "securityDefiner": true, "execute": ["authenticated", "service_role"], "raises": [], - "snapshotLine": 3087, + "snapshotLine": 3100, "definedIn": "supabase/migrations/20261113213127_deleted_groups_everywhere.sql" }, { @@ -2114,7 +2193,7 @@ "securityDefiner": true, "execute": ["PUBLIC", "authenticated", "service_role"], "raises": [], - "snapshotLine": 3101, + "snapshotLine": 3114, "definedIn": "supabase/migrations/20261113213127_deleted_groups_everywhere.sql" }, { @@ -2124,7 +2203,7 @@ "securityDefiner": true, "execute": ["PUBLIC", "authenticated", "service_role"], "raises": [], - "snapshotLine": 3116, + "snapshotLine": 3129, "definedIn": "supabase/migrations/20261106010000_integrity_fixes.sql" }, { @@ -2134,7 +2213,7 @@ "securityDefiner": true, "execute": ["PUBLIC", "authenticated", "service_role"], "raises": [], - "snapshotLine": 3130, + "snapshotLine": 3143, "definedIn": "supabase/migrations/20261113213126_group_types_restore_and_whiteboard.sql" }, { @@ -2144,7 +2223,7 @@ "securityDefiner": true, "execute": ["PUBLIC"], "raises": [], - "snapshotLine": 3144, + "snapshotLine": 3157, "definedIn": "supabase/migrations/20261113115254_payments_v2.sql" }, { @@ -2154,7 +2233,7 @@ "securityDefiner": false, "execute": [], "raises": [], - "snapshotLine": 3159, + "snapshotLine": 3172, "definedIn": "supabase/migrations/20261113153242_recurring_editing.sql" }, { @@ -2164,7 +2243,7 @@ "securityDefiner": true, "execute": [], "raises": [], - "snapshotLine": 3176, + "snapshotLine": 3189, "definedIn": "supabase/migrations/20261113201103_placeholder_members.sql" }, { @@ -2174,7 +2253,7 @@ "securityDefiner": true, "execute": ["PUBLIC"], "raises": [], - "snapshotLine": 3216, + "snapshotLine": 3229, "definedIn": "supabase/migrations/20261105071531_notification_triggers.sql" }, { @@ -2184,7 +2263,7 @@ "securityDefiner": true, "execute": [], "raises": [], - "snapshotLine": 3234, + "snapshotLine": 3247, "definedIn": "supabase/migrations/20261113115301_group_debts_and_bulk_settle.sql" }, { @@ -2194,7 +2273,7 @@ "securityDefiner": true, "execute": [], "raises": [], - "snapshotLine": 3449, + "snapshotLine": 3462, "definedIn": "supabase/migrations/20261113153242_recurring_editing.sql" }, { @@ -2204,7 +2283,7 @@ "securityDefiner": true, "execute": [], "raises": [], - "snapshotLine": 3487, + "snapshotLine": 3500, "definedIn": "supabase/migrations/20261113153242_recurring_editing.sql" }, { @@ -2214,7 +2293,7 @@ "securityDefiner": false, "execute": ["PUBLIC"], "raises": ["invalid_currency"], - "snapshotLine": 3512, + "snapshotLine": 3525, "definedIn": "supabase/migrations/20261113115254_payments_v2.sql" }, { @@ -2224,7 +2303,7 @@ "securityDefiner": false, "execute": ["PUBLIC"], "raises": [], - "snapshotLine": 3530, + "snapshotLine": 3543, "definedIn": "supabase/migrations/20261113115254_payments_v2.sql" }, { @@ -2234,7 +2313,7 @@ "securityDefiner": true, "execute": [], "raises": ["fx_rate_unavailable"], - "snapshotLine": 3541, + "snapshotLine": 3554, "definedIn": "supabase/migrations/20261113115254_payments_v2.sql" }, { @@ -2244,7 +2323,7 @@ "securityDefiner": false, "execute": ["PUBLIC"], "raises": ["invalid_payment_handle"], - "snapshotLine": 3562, + "snapshotLine": 3575, "definedIn": "supabase/migrations/20261113115259_payment_methods.sql" }, { @@ -2254,7 +2333,7 @@ "securityDefiner": false, "execute": ["PUBLIC"], "raises": ["note_too_long"], - "snapshotLine": 3582, + "snapshotLine": 3595, "definedIn": "supabase/migrations/20261113115254_payments_v2.sql" }, { @@ -2264,7 +2343,7 @@ "securityDefiner": false, "execute": ["PUBLIC"], "raises": [], - "snapshotLine": 3600, + "snapshotLine": 3613, "definedIn": "supabase/migrations/20261113115254_payments_v2.sql" }, { @@ -2274,7 +2353,7 @@ "securityDefiner": false, "execute": [], "raises": ["invalid_email"], - "snapshotLine": 3614, + "snapshotLine": 3627, "definedIn": "supabase/migrations/20261113201103_placeholder_members.sql" }, { @@ -2284,7 +2363,7 @@ "securityDefiner": false, "execute": [], "raises": ["invalid_name"], - "snapshotLine": 3632, + "snapshotLine": 3645, "definedIn": "supabase/migrations/20261113201103_placeholder_members.sql" }, { @@ -2294,7 +2373,7 @@ "securityDefiner": true, "execute": [], "raises": ["profile_without_account"], - "snapshotLine": 3650, + "snapshotLine": 3663, "definedIn": "supabase/migrations/20261113201103_placeholder_members.sql" }, { @@ -2304,9 +2383,19 @@ "securityDefiner": true, "execute": [], "raises": [], - "snapshotLine": 3669, + "snapshotLine": 3682, "definedIn": "supabase/migrations/20261113213126_group_types_restore_and_whiteboard.sql" }, + { + "name": "private.purge_quick_polls", + "args": "", + "returns": "integer", + "securityDefiner": true, + "execute": [], + "raises": [], + "snapshotLine": 3714, + "definedIn": "supabase/migrations/20261122232215_quick_polls.sql" + }, { "name": "private.push_notification", "args": "", @@ -2314,7 +2403,7 @@ "securityDefiner": true, "execute": [], "raises": [], - "snapshotLine": 3701, + "snapshotLine": 3732, "definedIn": "supabase/migrations/20261113062656_notification_prefs_and_email.sql" }, { @@ -2324,9 +2413,29 @@ "securityDefiner": true, "execute": [], "raises": [], - "snapshotLine": 3720, + "snapshotLine": 3751, "definedIn": "supabase/migrations/20261113062656_notification_prefs_and_email.sql" }, + { + "name": "private.quick_poll_status", + "args": "poll public.quick_polls, answered boolean", + "returns": "text", + "securityDefiner": false, + "execute": [], + "raises": [], + "snapshotLine": 3822, + "definedIn": "supabase/migrations/20261122232215_quick_polls.sql" + }, + { + "name": "private.quick_poll_token_hash", + "args": "token text", + "returns": "bytea", + "securityDefiner": false, + "execute": [], + "raises": [], + "snapshotLine": 3840, + "definedIn": "supabase/migrations/20261122232215_quick_polls.sql" + }, { "name": "private.random_code", "args": "bytes integer DEFAULT 9", @@ -2334,7 +2443,7 @@ "securityDefiner": false, "execute": ["PUBLIC"], "raises": [], - "snapshotLine": 3744, + "snapshotLine": 3775, "definedIn": "supabase/migrations/20261105071410_extensions_and_private_schema.sql" }, { @@ -2344,7 +2453,7 @@ "securityDefiner": true, "execute": [], "raises": [], - "snapshotLine": 3755, + "snapshotLine": 3851, "definedIn": "supabase/migrations/20261114015104_expense_attachments.sql" }, { @@ -2354,7 +2463,7 @@ "securityDefiner": false, "execute": [], "raises": [], - "snapshotLine": 3781, + "snapshotLine": 3877, "definedIn": "supabase/migrations/20261113100257_two_factor_enforcement.sql" }, { @@ -2364,7 +2473,7 @@ "securityDefiner": true, "execute": [], "raises": [], - "snapshotLine": 3795, + "snapshotLine": 3891, "definedIn": "supabase/migrations/20261113153242_recurring_editing.sql" }, { @@ -2374,7 +2483,7 @@ "securityDefiner": true, "execute": [], "raises": [], - "snapshotLine": 3808, + "snapshotLine": 3904, "definedIn": "supabase/migrations/20261113153242_recurring_editing.sql" }, { @@ -2384,7 +2493,7 @@ "securityDefiner": true, "execute": [], "raises": [], - "snapshotLine": 3820, + "snapshotLine": 3916, "definedIn": "supabase/migrations/20261113153242_recurring_editing.sql" }, { @@ -2394,7 +2503,7 @@ "securityDefiner": true, "execute": [], "raises": [], - "snapshotLine": 3835, + "snapshotLine": 3931, "definedIn": "supabase/migrations/20261114154849_block_shared_expenses.sql" }, { @@ -2404,7 +2513,7 @@ "securityDefiner": false, "execute": ["authenticated", "service_role"], "raises": [], - "snapshotLine": 3853, + "snapshotLine": 3949, "definedIn": "supabase/migrations/20261113153242_recurring_editing.sql" }, { @@ -2414,7 +2523,7 @@ "securityDefiner": false, "execute": [], "raises": [], - "snapshotLine": 3869, + "snapshotLine": 3965, "definedIn": "supabase/migrations/20261113153242_recurring_editing.sql" }, { @@ -2424,7 +2533,7 @@ "securityDefiner": false, "execute": [], "raises": [], - "snapshotLine": 3891, + "snapshotLine": 3987, "definedIn": "supabase/migrations/20261113153242_recurring_editing.sql" }, { @@ -2434,7 +2543,7 @@ "securityDefiner": true, "execute": [], "raises": ["split_member_not_in_group"], - "snapshotLine": 3906, + "snapshotLine": 4002, "definedIn": "supabase/migrations/20261113153242_recurring_editing.sql" }, { @@ -2444,7 +2553,7 @@ "securityDefiner": true, "execute": [], "raises": [], - "snapshotLine": 3925, + "snapshotLine": 4021, "definedIn": "supabase/migrations/20261113153242_recurring_editing.sql" }, { @@ -2454,7 +2563,7 @@ "securityDefiner": false, "execute": [], "raises": [], - "snapshotLine": 3953, + "snapshotLine": 4049, "definedIn": "supabase/migrations/20261113153242_recurring_editing.sql" }, { @@ -2464,7 +2573,7 @@ "securityDefiner": true, "execute": [], "raises": [], - "snapshotLine": 3975, + "snapshotLine": 4071, "definedIn": "supabase/migrations/20261113091955_expense_entry.sql" }, { @@ -2474,7 +2583,7 @@ "securityDefiner": true, "execute": [], "raises": [], - "snapshotLine": 4008, + "snapshotLine": 4104, "definedIn": "supabase/migrations/20261113201107_friends_and_blocks.sql" }, { @@ -2484,7 +2593,7 @@ "securityDefiner": true, "execute": [], "raises": ["direct_group", "not_allowed"], - "snapshotLine": 4050, + "snapshotLine": 4146, "definedIn": "supabase/migrations/20261113201103_placeholder_members.sql" }, { @@ -2494,7 +2603,7 @@ "securityDefiner": true, "execute": [], "raises": ["group_archived"], - "snapshotLine": 4074, + "snapshotLine": 4170, "definedIn": "supabase/migrations/20261106000000_review_fixes.sql" }, { @@ -2504,7 +2613,7 @@ "securityDefiner": true, "execute": [], "raises": ["group_deleted"], - "snapshotLine": 4089, + "snapshotLine": 4185, "definedIn": "supabase/migrations/20261113213126_group_types_restore_and_whiteboard.sql" }, { @@ -2514,7 +2623,7 @@ "securityDefiner": true, "execute": [], "raises": ["group_deleted", "not_a_member"], - "snapshotLine": 4105, + "snapshotLine": 4201, "definedIn": "supabase/migrations/20261113213126_group_types_restore_and_whiteboard.sql" }, { @@ -2524,7 +2633,7 @@ "securityDefiner": true, "execute": [], "raises": ["blocked_person", "not_a_friend"], - "snapshotLine": 4132, + "snapshotLine": 4228, "definedIn": "supabase/migrations/20261114154849_block_shared_expenses.sql" }, { @@ -2534,7 +2643,7 @@ "securityDefiner": true, "execute": [], "raises": ["group_archived"], - "snapshotLine": 4154, + "snapshotLine": 4250, "definedIn": "supabase/migrations/20261106010000_integrity_fixes.sql" }, { @@ -2544,7 +2653,7 @@ "securityDefiner": true, "execute": [], "raises": ["account_deleted", "not_authenticated"], - "snapshotLine": 4169, + "snapshotLine": 4265, "definedIn": "supabase/migrations/20261105071504_rpc_groups.sql" }, { @@ -2554,7 +2663,7 @@ "securityDefiner": true, "execute": [], "raises": [], - "snapshotLine": 4190, + "snapshotLine": 4286, "definedIn": "supabase/migrations/20261113153242_recurring_editing.sql" }, { @@ -2564,7 +2673,7 @@ "securityDefiner": true, "execute": ["authenticated", "service_role"], "raises": [], - "snapshotLine": 4207, + "snapshotLine": 4303, "definedIn": "supabase/migrations/20261106000000_review_fixes.sql" }, { @@ -2594,7 +2703,7 @@ "splits_required", "splits_sum_mismatch" ], - "snapshotLine": 4223, + "snapshotLine": 4319, "definedIn": "supabase/migrations/20261113091955_expense_entry.sql" }, { @@ -2604,7 +2713,7 @@ "securityDefiner": true, "execute": [], "raises": [], - "snapshotLine": 4744, + "snapshotLine": 4840, "definedIn": "supabase/migrations/20261113201103_placeholder_members.sql" }, { @@ -2614,7 +2723,7 @@ "securityDefiner": true, "execute": [], "raises": [], - "snapshotLine": 4763, + "snapshotLine": 4859, "definedIn": "supabase/migrations/20261113201103_placeholder_members.sql" }, { @@ -2624,7 +2733,7 @@ "securityDefiner": true, "execute": [], "raises": [], - "snapshotLine": 4949, + "snapshotLine": 5045, "definedIn": "supabase/migrations/20261105071542_cron_jobs.sql" }, { @@ -2634,7 +2743,7 @@ "securityDefiner": true, "execute": [], "raises": [], - "snapshotLine": 5000, + "snapshotLine": 5096, "definedIn": "supabase/migrations/20261113062656_notification_prefs_and_email.sql" }, { @@ -2644,7 +2753,7 @@ "securityDefiner": true, "execute": [], "raises": [], - "snapshotLine": 5033, + "snapshotLine": 5129, "definedIn": "supabase/migrations/20261113153242_recurring_editing.sql" }, { @@ -2654,7 +2763,7 @@ "securityDefiner": true, "execute": ["anon", "authenticated", "service_role"], "raises": [], - "snapshotLine": 5114, + "snapshotLine": 5210, "definedIn": "supabase/migrations/20261114072312_signed_out_sessions.sql" }, { @@ -2664,7 +2773,7 @@ "securityDefiner": false, "execute": ["PUBLIC"], "raises": [], - "snapshotLine": 5131, + "snapshotLine": 5227, "definedIn": "supabase/migrations/20261113201103_placeholder_members.sql" }, { @@ -2674,7 +2783,7 @@ "securityDefiner": true, "execute": ["PUBLIC"], "raises": [], - "snapshotLine": 5148, + "snapshotLine": 5244, "definedIn": "supabase/migrations/20261113201103_placeholder_members.sql" }, { @@ -2684,7 +2793,7 @@ "securityDefiner": true, "execute": ["PUBLIC"], "raises": [], - "snapshotLine": 5188, + "snapshotLine": 5284, "definedIn": "supabase/migrations/20261105071531_notification_triggers.sql" }, { @@ -2694,7 +2803,7 @@ "securityDefiner": true, "execute": ["PUBLIC"], "raises": [], - "snapshotLine": 5214, + "snapshotLine": 5310, "definedIn": "supabase/migrations/20261113201103_placeholder_members.sql" }, { @@ -2704,7 +2813,7 @@ "securityDefiner": true, "execute": ["PUBLIC", "authenticated", "service_role"], "raises": [], - "snapshotLine": 5258, + "snapshotLine": 5354, "definedIn": "supabase/migrations/20261105071444_policy_helpers.sql" }, { @@ -2714,7 +2823,7 @@ "securityDefiner": true, "execute": [], "raises": [], - "snapshotLine": 5274, + "snapshotLine": 5370, "definedIn": "supabase/migrations/20261113201103_placeholder_members.sql" }, { @@ -2724,7 +2833,7 @@ "securityDefiner": true, "execute": [], "raises": ["too_many_invites"], - "snapshotLine": 5311, + "snapshotLine": 5407, "definedIn": "supabase/migrations/20261113201103_placeholder_members.sql" }, { @@ -2734,7 +2843,7 @@ "securityDefiner": true, "execute": [], "raises": [], - "snapshotLine": 5331, + "snapshotLine": 5427, "definedIn": "supabase/migrations/20261113201103_placeholder_members.sql" }, { @@ -2744,7 +2853,7 @@ "securityDefiner": true, "execute": ["PUBLIC"], "raises": [], - "snapshotLine": 5351, + "snapshotLine": 5447, "definedIn": "supabase/migrations/20261114015104_expense_attachments.sql" }, { @@ -2754,7 +2863,7 @@ "securityDefiner": true, "execute": ["PUBLIC"], "raises": [], - "snapshotLine": 5396, + "snapshotLine": 5492, "definedIn": "supabase/migrations/20261113091955_expense_entry.sql" }, { @@ -2764,7 +2873,7 @@ "securityDefiner": true, "execute": [], "raises": [], - "snapshotLine": 5414, + "snapshotLine": 5510, "definedIn": "supabase/migrations/20261106010000_integrity_fixes.sql" }, { @@ -2774,7 +2883,7 @@ "securityDefiner": false, "execute": ["PUBLIC", "anon", "authenticated", "service_role"], "raises": [], - "snapshotLine": 5442, + "snapshotLine": 5538, "definedIn": "supabase/migrations/20261105071410_extensions_and_private_schema.sql" }, { @@ -2784,7 +2893,7 @@ "securityDefiner": true, "execute": [], "raises": [], - "snapshotLine": 5458, + "snapshotLine": 5554, "definedIn": "supabase/migrations/20261113062656_notification_prefs_and_email.sql" }, { @@ -2794,7 +2903,7 @@ "securityDefiner": true, "execute": [], "raises": [], - "snapshotLine": 5478, + "snapshotLine": 5574, "definedIn": "supabase/migrations/20261113153242_recurring_editing.sql" }, { @@ -2804,7 +2913,7 @@ "securityDefiner": false, "execute": ["PUBLIC"], "raises": [], - "snapshotLine": 5491, + "snapshotLine": 5587, "definedIn": "supabase/migrations/20261113115254_payments_v2.sql" }, { @@ -2814,7 +2923,7 @@ "securityDefiner": false, "execute": ["PUBLIC", "authenticated", "service_role"], "raises": [], - "snapshotLine": 5502, + "snapshotLine": 5598, "definedIn": "supabase/migrations/20261113115259_payment_methods.sql" }, { @@ -2824,7 +2933,7 @@ "securityDefiner": true, "execute": [], "raises": [], - "snapshotLine": 5526, + "snapshotLine": 5622, "definedIn": "supabase/migrations/20261114015104_expense_attachments.sql" } ], @@ -2917,6 +3026,14 @@ "clientGrants": {}, "policies": [] }, + { + "name": "private.quick_poll_creates", + "kind": "table", + "rls": false, + "realtime": false, + "clientGrants": {}, + "policies": [] + }, { "name": "private.recurring_heads_ups", "kind": "table", @@ -3589,6 +3706,30 @@ { "name": "push_tokens: update own", "command": "UPDATE", "roles": ["authenticated"] } ] }, + { + "name": "public.quick_poll_answers", + "kind": "table", + "rls": true, + "realtime": false, + "clientGrants": {}, + "policies": [] + }, + { + "name": "public.quick_poll_slots", + "kind": "table", + "rls": true, + "realtime": false, + "clientGrants": {}, + "policies": [] + }, + { + "name": "public.quick_polls", + "kind": "table", + "rls": true, + "realtime": false, + "clientGrants": {}, + "policies": [] + }, { "name": "public.recurring_expenses", "kind": "table", @@ -3728,7 +3869,7 @@ { "code": "duplicate_slot", "sqlstates": ["22023"], - "raisedBy": ["private.event_slots", "public.set_availability"], + "raisedBy": ["private.grid_slots", "public.set_availability"], "i18n": ["events.errors.duplicate_slot"] }, { @@ -4104,6 +4245,66 @@ "raisedBy": ["public.search_money"], "i18n": ["errors.codes.invalid_query"] }, + { + "code": "invalid_quick_poll", + "sqlstates": ["22023"], + "raisedBy": ["public.create_quick_poll"], + "i18n": [] + }, + { + "code": "invalid_quick_poll_duration", + "sqlstates": ["22023"], + "raisedBy": ["public.create_quick_poll"], + "i18n": [] + }, + { + "code": "invalid_quick_poll_hours", + "sqlstates": ["22023"], + "raisedBy": ["public.create_quick_poll"], + "i18n": [] + }, + { + "code": "invalid_quick_poll_name", + "sqlstates": ["22023"], + "raisedBy": ["public.set_quick_poll_availability"], + "i18n": [] + }, + { + "code": "invalid_quick_poll_people", + "sqlstates": ["22023"], + "raisedBy": ["public.create_quick_poll"], + "i18n": [] + }, + { + "code": "invalid_quick_poll_slot_minutes", + "sqlstates": ["22023"], + "raisedBy": ["public.create_quick_poll"], + "i18n": [] + }, + { + "code": "invalid_quick_poll_timezone", + "sqlstates": ["22023"], + "raisedBy": ["public.create_quick_poll"], + "i18n": [] + }, + { + "code": "invalid_quick_poll_title", + "sqlstates": ["22023"], + "raisedBy": ["public.create_quick_poll"], + "i18n": [] + }, + { + "code": "invalid_quick_poll_ttl", + "sqlstates": ["22023"], + "raisedBy": ["public.create_quick_poll"], + "i18n": [] + }, + { + "code": "invalid_quick_poll_window", + "sqlstates": ["22023"], + "raisedBy": ["public.create_quick_poll"], + "i18n": [] + }, { "code": "invalid_receipt_path", "sqlstates": ["22023"], @@ -4125,13 +4326,13 @@ { "code": "invalid_slot", "sqlstates": ["22023"], - "raisedBy": ["private.event_slots", "public.set_availability"], + "raisedBy": ["private.grid_slots", "public.set_availability"], "i18n": ["events.errors.invalid_slot"] }, { "code": "invalid_slots", "sqlstates": ["22023"], - "raisedBy": ["private.event_slots", "public.set_availability"], + "raisedBy": ["private.grid_slots", "public.set_availability"], "i18n": ["events.errors.invalid_slots"] }, { @@ -4285,8 +4486,10 @@ "private.manageable_event", "private.require_can_add_people", "private.save_expense", + "public.close_quick_poll", "public.create_invite", "public.delete_group", + "public.delete_quick_poll", "public.delete_settlement", "public.make_expense_recurring", "public.remove_member", @@ -4411,6 +4614,47 @@ "raisedBy": ["private.profile_needs_account"], "i18n": ["errors.codes.profile_without_account"] }, + { + "code": "quick_poll_closed", + "sqlstates": ["23514"], + "raisedBy": ["public.set_quick_poll_availability"], + "i18n": [] + }, + { + "code": "quick_poll_expired", + "sqlstates": ["23514"], + "raisedBy": ["public.set_quick_poll_availability"], + "i18n": [] + }, + { + "code": "quick_poll_full", + "sqlstates": ["23514"], + "raisedBy": ["public.set_quick_poll_availability"], + "i18n": [] + }, + { + "code": "quick_poll_not_found", + "sqlstates": ["PT404"], + "raisedBy": [ + "public.close_quick_poll", + "public.delete_quick_poll", + "public.quick_poll_preview", + "public.set_quick_poll_availability" + ], + "i18n": [] + }, + { + "code": "quick_poll_rate_limited", + "sqlstates": ["23514"], + "raisedBy": ["public.create_quick_poll", "public.set_quick_poll_availability"], + "i18n": [] + }, + { + "code": "quick_poll_slots_required", + "sqlstates": ["22023"], + "raisedBy": ["public.set_quick_poll_availability"], + "i18n": [] + }, { "code": "recurring_not_found", "sqlstates": ["PT404"], @@ -4574,6 +4818,7 @@ { "name": "notifications", "file": "packages/i18n/src/en/me.ts" }, { "name": "onboarding", "file": "packages/i18n/src/en/auth.ts" }, { "name": "people", "file": "packages/i18n/src/en/people.ts" }, + { "name": "quickPolls", "file": null }, { "name": "roles", "file": "packages/i18n/src/en/groups.ts" }, { "name": "rsvp", "file": "packages/i18n/src/en/plans.ts" }, { "name": "search", "file": "packages/i18n/src/en/insights.ts" }, diff --git a/docs/architecture.md b/docs/architecture.md index 279d332c..33440895 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -542,6 +542,15 @@ erDiagram - `event_guests`: `id`, `link_id`, `event_id`, `group_id`, `display_name` (1 to 40 characters after `private.clean_guest_name` drops invisible characters and collapses whitespace), `token_hash bytea` (sha256 of the token the guest's browser keeps; unique per link, never readable by clients), `saves` and `saves_window_start` (rate limit), `removed_at` (the organizer removed the answer; members no longer see the row and the token is refused), timestamps. - `event_guest_availability`: `(guest_id, slot_start)` pk, `event_id`, `level`. Same shape as `availability`. +### Quick polls + +Availability polls that need no account, group or event ([ADR 22](adr/0022-quick-polls-without-accounts.md)). Clients read and write none of these tables; RLS is on with no policies and `anon` and `authenticated` hold no grants. + +- `quick_polls`: `id`, `code text unique` (16 url-safe chars), `title` (null, or 1 to 80 characters cleaned like guest names; the client shows a default for null), `timezone`, `window_start`, `window_end` (1 to 14 days, both included), `day_start_minute`, `day_end_minute`, `slot_minutes` (30 or 60), `duration_minutes` (15 to 1440), `names_required bool default true`, `max_people int default 10` (2 to 15), `creator_token_hash bytea` (sha256 of the creator's token), `expires_at`, `closed_at`, `created_at`. +- `quick_poll_answers`: `id`, `poll_id`, `seat int` (1, 2, 3... in answer order, unique per poll, never reused), `display_name` (1 to 40 characters after `private.clean_guest_name`; null when the poll does not ask for names), `token_hash bytea` (unique per poll; the creator's answer reuses `creator_token_hash`), `saves` and `saves_window_start` (rate limit), timestamps. +- `quick_poll_slots`: `(answer_id, slot_start)` pk, `level`. Same shape as `availability`. +- `private.quick_poll_creates`: `creator_hash` (sha256 of the first `x-forwarded-for` entry, null without one), `created_at`. One row per poll made, kept an hour, for the create rate limit; deleting a poll leaves its row. + ### Feed, notifications, platform - `activity`: `id`, `group_id`, `actor_id`, `verb text` (`expense.created`, `settlement.created`, `member.joined`, `event.scheduled`, ...), `subject_id uuid`, `data jsonb`, `created_at`. Written by triggers. @@ -635,6 +644,10 @@ A placeholder is always a plain member and can never be made admin or owner (`pl | `remove_guest_answer(guest_id)` | plan creator or admins; the guest's slots go, their token is blocked, their seat frees up | | `guest_link_preview(code, token default null)` → status, plan window, aggregated heat, the guest's own answer | callable by `anon`, for `/a/` | | `set_guest_availability(code, name, token, slots)` → `guest_token, saved` | callable by `anon`; adds or edits a guest's answer | +| `create_quick_poll(payload)` → `code, creator_token, expires_at` | callable by `anon`; see Quick polls below | +| `quick_poll_preview(code, token default null)` → status, grid, `is_creator`, every answer | callable by `anon` | +| `set_quick_poll_availability(code, name, token, slots)` → `answer_token, saved` | callable by `anon`; adds or edits the visitor's answer | +| `close_quick_poll(code, token)` / `delete_quick_poll(code, token)` | callable by `anon`; creator token only | | `search_money(query, in_group, person, from_day, to_day, categories, kinds, before_day, before_at, before_id, max_rows)` → expense and payment rows | live items across the viewer's groups (or one), newest first, keyset paged; see below | | `deleted_items(in_group, before_at, before_id, max_rows)` → deleted expenses and payments | most recently deleted first, with `deleted_by` from the feed | | `friend_activity(friend, before_at, before_id, max_rows)` → feed rows | entries that involve both the viewer and the friend | @@ -686,6 +699,7 @@ Codes: - Search and totals: `invalid_date_range` (a `from_day` after `to_day`), `invalid_query` (over 200 characters), `invalid_cursor` (a page cursor missing its day, time or id). - Plans: `event_not_found`, `event_not_polling`, `event_not_schedulable`, `event_done`, `starts_at_required`, `invalid_slot`, `invalid_slots`, `duplicate_slot`, `rsvp_closed` (RSVP after the event's `rsvp_deadline`). - Guest links: `invalid_guest_link_ttl`, `invalid_guest_limit`, `guest_link_limit` (20 open links per plan), `guest_removed` (a token whose answer the organizer removed), `guest_link_not_found`, `guest_link_revoked`, `guest_link_expired`, `guest_link_full`, `invalid_guest_name`, `guest_slots_required` (a new guest with no times), `guest_rate_limited`, `guest_not_found`. +- Quick polls: `invalid_quick_poll` (the payload is not an object, or a value has the wrong type), `invalid_quick_poll_title`, `invalid_quick_poll_timezone`, `invalid_quick_poll_window`, `invalid_quick_poll_hours`, `invalid_quick_poll_slot_minutes`, `invalid_quick_poll_duration`, `invalid_quick_poll_ttl`, `invalid_quick_poll_people`, `invalid_quick_poll_name`, `quick_poll_slots_required` (a new answer with no times), `quick_poll_not_found`, `quick_poll_expired`, `quick_poll_closed`, `quick_poll_full`, `quick_poll_rate_limited` (creates or saves). ### RPC details and deviations @@ -761,6 +775,13 @@ Codes: - `guest_link_preview(code, token?)` returns `status`: `revoked`, `archived`, `removed` (the token's answer was removed), `scheduled` (the plan has a time; only for a guest who answered through this link, with the title, emojis, host, `my_name` and `starts_at`, `ends_at`), `expired`, `closed` (cancelled, or scheduled for anyone who did not answer), `full` or `open`. `open` and `full` carry the title, emoji, group emoji, the link creator's first name, the grid fields, `expires_at`, `max_guests` and `guest_count` (removed guests not counted). Only `open` carries `respondents`, `heat` (`[{slot_start, yes, maybe}]` from members and guests not removed, never names or ids) and, when `token` matches a guest of this link, `my_name` and `my_slots`. A guest who already answered sees `open` on a full link. Unknown codes raise `guest_link_not_found`. - `set_guest_availability(code, name, token, slots)` locks the link row, checks revoked, expired, archived and polling in that order, cleans the name with `private.clean_guest_name` (1 to 40 characters after invisible and zero width characters are dropped and whitespace collapsed; `cleanGuestName` in core is the same rule) and checks the slots like `set_availability`. A token whose answer was removed raises `guest_removed`. A token that matches a guest on this link edits that guest (60 saves per hour). Anything else is a new guest, who needs at least one slot, a free seat (`guest_link_full`) and the link under 20 new guests in 10 minutes, and gets a fresh 24 byte token back. The table keeps `sha256(token)` only. - `remove_guest_answer(guest_id)` locks the link row first (link before event, as in `set_guest_availability`, so no save lands after the removal), then deletes the guest's slots and marks them removed: their seat frees up, members stop seeing them, and their token can no longer answer or see the plan. +- Quick polls ([ADR 22](adr/0022-quick-polls-without-accounts.md)), all `security definer` and callable by `anon` and `authenticated`: + - Status has one owner, `private.quick_poll_status(poll, answered)`: `expired` (`expires_at` passed), then `closed` (`closed_at` set), then `full` (the visitor has not answered and `max_people` answers exist), else `open`. + - The grid rule has one owner, `private.grid_slots(timezone, window_start, window_end, day_start_minute, day_end_minute, slot_minutes, slots)`; `private.event_slots` hands an event's grid to it. + - `create_quick_poll(payload)` checks every key (`22023` codes above), then takes an advisory lock and refuses a sixth poll in an hour from the same client (sha256 of the first `x-forwarded-for` entry of `request.headers`; no limit per client without one) and a 201st in an hour overall (`quick_poll_rate_limited`). It returns the code, a fresh 24 byte creator token (only its sha256 is kept) and `expires_at` (`ttl` `24h` or `7d`). + - `quick_poll_preview(code, token?)` raises `quick_poll_not_found` for an unknown code. `expired` returns the status only. `open`, `full` and `closed` return the title, the grid, `names_required`, `max_people`, `expires_at`, `is_creator` (the token is the creator token) and `answers`: `[{seat, name, mine, slots: [{slot_start, level}]}]` by seat, `name` null when the poll does not ask for names, never ids or hashes. + - `set_quick_poll_availability(code, name, token, slots)` locks the poll row, refuses `expired`, `closed` and, for a new answer, `full`, cleans the name when the poll asks for names (ignores it otherwise) and checks the slots against the grid. A token that matches an answer edits it (60 saves an hour). Otherwise a new answer takes the next seat and needs at least one slot; the creator token makes the creator's answer under that same token, anything else gets a fresh token back. + - `close_quick_poll(code, token)` sets `closed_at` (again changes nothing); `delete_quick_poll(code, token)` deletes the poll, its answers and slots. Both take the creator token only (`not_allowed`). - `schedule_event(event_id, starts_at)` also reschedules an already scheduled event and sets `ends_at = starts_at + duration`. `reminder_sent_at` is cleared only when the start time actually changes, so locking in the same time again does not send a second reminder. `cancel_event` is idempotent. Owner, admins or the event creator. - `my_timeline(from = now(), to = now() + 60 days)` returns `event_id, group_id, group_name, group_emoji, group_color, title, emoji, location, status, timezone, starts_at, ends_at, window_start, window_end, rsvp_deadline, my_rsvp, going_count, availability_requested, availability_submitted` for scheduled events in range and open polls overlapping it. - `search_money(...)`: every argument is optional. Matches `query` (case-insensitive substring, wildcards taken literally) against the description, the notes, live comments on the expense, the payer's or anyone in the split's display name, and an amount (`12`, `12.50`, `$12.50`, `12.50 EUR`, in the expense's own currency; three digits after the separator also read as thousands, and a reading with more decimals than the currency has is ignored, so `1,000` finds 1,000.00 USD and 1000 JPY but not 1.00 USD); payments match on their note, live comments on the payment, either person's name and the amount. Filters: one group (`not_a_member` if the caller is not in it), a person who paid or is in the split (either side of a payment), inclusive `from_day` / `to_day` (`spent_at`, or the payment's day in the caller's time zone), `categories` (matched exactly; an expense without one is `other`; a category filter leaves payments out; `searchMoney` in `@potluck/api` and core `matchesExpenseFilters` add the subcategories of a picked top level id with `withSubcategories()`), `kinds` (`expense`, `payment`). Rows carry `kind`, `id`, `group_id`, `day`, `at` (`created_at` or `settled_at`), `description` (or the payment note), `category`, `amount_cents`, `currency`, `group_currency`, `group_amount_cents`, `paid_by` (or the sender), `to_user`, `created_by`, `my_paid_cents` and `my_share_cents` (from `expense_ledger`, null when the caller is not in it), `deleted_at`, `matched` (`description`, `notes`, `comment`, `person`, `amount`) and `snippet` (the comment or name that matched). The payment's day is in the caller's zone (`private.user_time_zone`, UTC when the profile's zone is unknown), as in `spending_summary` and `deleted_items`. Order `(day, at, id)` descending; pass the last row's three as `before_*` for the next page. `max_rows` is clamped to 1..100. Trigram indexes (`pg_trgm`) on `expenses.description`, `expenses.notes`, `settlements.note` and live comments on expenses and on payments keep the text match off sequential scans; perf01 in `supabase/snippets/perf_volume.sql` (12 groups, about 2,400 expenses) searches in 15 to 35 ms. @@ -845,6 +866,7 @@ These rules exist in `packages/core` and in SQL. Change both sides in the same P | `currency/convert`, `minorUnits`, `invertRate` | `private.convert_minor`, `private.minor_units`, `private.fx_rate` | | `availability/` slots, `rankSlots`, heat | `public.set_availability` grid check, `public.best_slots` | | `people/cleanGuestName` | `private.clean_guest_name` | +| `quick-polls/` limits | `public.create_quick_poll` checks, `public.quick_polls` checks | | `recurrence/nextOccurrence` (biweekly too) | `private.recurring_step` (used by the materialize job) | | `recurrence/firstOccurrenceFrom` | `private.recurring_next_from` (`make_expense_recurring`) | | `roles/can()` | role checks inside each RPC | @@ -874,6 +896,7 @@ Clients write directly (RLS-checked) only to these tables. Everything else goes - `placeholders`: read only (members of its group, every column but `email`); written by the placeholder RPCs. - `recurring_expenses`: an admin or anyone it involves (`private.recurring_involves`: creator, payer, someone in the split) may change `active` (pause, resume) or delete; every other change goes through `update_recurring_expense`. Archived groups raise `group_archived` from a trigger. Turning `active` back on moves a past `next_run_on` to the next occurrence on or after today, so paused periods are never charged, and is refused while the template names someone who left. - `event_guest_links`, `event_guests`, `event_guest_availability`: no direct writes at all; members read them (`event_guests` without `token_hash`, `saves`, `saves_window_start`). +- `quick_polls`, `quick_poll_answers`, `quick_poll_slots`: no grants and no policies; only the quick poll RPCs touch them. Who can read what: @@ -881,6 +904,7 @@ Who can read what: - Former members are tracked in `private.former_members` by a trigger on `group_members`, only while something in the group (an expense, payment, comment, or a feed entry for something they did there, not their joining or leaving) still names them. Rejoining removes the row. - Busy blocks are private. `app_config` is readable by `anon`. - Guests are not users and read nothing directly: `anon` has no grants on the guest tables, only the two guest RPCs, which show one link's plan window and aggregated counts. +- Quick polls are readable by anyone with the code, through `quick_poll_preview` only, and only until they expire. ### Activity and notifications @@ -909,7 +933,7 @@ The browser is untrusted. It holds the publishable key and, once signed in, a sh ### Layers 1. **Grants.** Every table starts with `revoke all ... from anon, authenticated`, then each migration grants back only the columns a client may touch. For example `profiles` grants `update (display_name, avatar_path, timezone, default_currency, locale)`, so a client cannot set `deleted_at` even on its own row. In the database, `anon` gets `select` on `app_config` and `execute` on `invite_preview`, `invite_preview_v2`, `friend_invite_preview` (the link code is the credential) and `email_unsubscribe` (which needs a signed token), and nothing else. The public `avatars` and `group-covers` buckets serve files by URL without signing in; listing `group-covers` takes membership of the group. -1. **Grants.** Every table starts with `revoke all ... from anon, authenticated`, then each migration grants back only the columns a client may touch. For example `profiles` grants `update (display_name, avatar_path, timezone, default_currency, locale)`, so a client cannot set `deleted_at` even on its own row. In the database, `anon` gets `select` on `app_config` and `execute` on `invite_preview`, `email_unsubscribe` (which needs a signed token), `guest_link_preview` and `set_guest_availability` (which need a guest link code), and nothing else. The public `avatars` and `group-covers` buckets serve files by URL without signing in; listing `group-covers` takes membership of the group. +1. **Grants.** Every table starts with `revoke all ... from anon, authenticated`, then each migration grants back only the columns a client may touch. For example `profiles` grants `update (display_name, avatar_path, timezone, default_currency, locale)`, so a client cannot set `deleted_at` even on its own row. In the database, `anon` gets `select` on `app_config` and `execute` on `invite_preview`, `email_unsubscribe` (which needs a signed token), `guest_link_preview` and `set_guest_availability` (which need a guest link code), the five quick poll RPCs (`create_quick_poll`, and four that need a poll code), and nothing else. The public `avatars` and `group-covers` buckets serve files by URL without signing in; listing `group-covers` takes membership of the group. 1. **Row Level Security.** Enabled on every table in `public`. Policies answer "which rows" using helpers from the `private` schema. Policies use `(select auth.uid())` and `group_id = any (array(select private.my_group_ids()))` so Postgres evaluates them once per statement instead of once per row, and can read only the caller's rows through the `group_id` indexes. 1. **Security definer RPCs.** Multi-row writes (expense plus splits, settle up, joining, role changes, scheduling) have no insert or update policy at all. They go through `public.*` functions that run as the owner, start with `private.require_user()` (signed in, account not closed) and `private.require_member(group_id)`, then check the role rules themselves. All of them set `search_path = ''` and schema-qualify every name. 1. **Triggers and constraints** hold invariants no client can skip: exactly one owner per group, splits sum to the amount, group currency locked once money exists, `comments.group_id` copied from the parent, only the author edits a comment body. @@ -918,7 +942,7 @@ The browser is untrusted. It holds the publishable key and, once signed in, a sh `private` is not in `[api].schemas`, so PostgREST never exposes it. `revoke all on schema private from public` plus `alter default privileges ... revoke execute on functions from public` means a new function is callable by nobody until a migration grants it. API roles get `usage` on the schema and `execute` only on the policy helpers (`is_group_member`, `group_role`, `is_group_admin`, `my_group_ids`, `my_event_ids`, `shares_group_with`, `my_contact_ids`, `can_manage_event`) and a few pure functions (`try_uuid`, `minor_units`, `convert_minor`, `is_time_zone`). The helpers are `security definer` so they can read `group_members` without recursing into its own policy, and they only ever answer questions about `auth.uid()`. -Trigger functions, cron jobs, `require_user`, `require_member`, `member_balance`, `compute_splits`, `invoke_edge_function`, `notify`, `notification_channels` and `unsubscribe_token` are not executable by `anon` or `authenticated`. Private tables (`former_members`, `invite_sends`, `notification_categories`, `notification_types`, `email_outbox`, `signing_keys`, `import_batches`, `import_rows`, `request_keys`, and the per call working tables `import_input`, `import_people`, `import_payer`, `import_rates`) are not readable by them either. `mfa_satisfied`, `session_active` and `check_request` are executable by every API role because PostgREST and the realtime policies call them as the caller. `private.mfa_recovery_codes` and `private.mfa_recover_attempts` are readable by nobody but their owner. +Trigger functions, cron jobs, `require_user`, `require_member`, `member_balance`, `compute_splits`, `invoke_edge_function`, `notify`, `notification_channels` and `unsubscribe_token` are not executable by `anon` or `authenticated`. Private tables (`former_members`, `invite_sends`, `notification_categories`, `notification_types`, `email_outbox`, `signing_keys`, `import_batches`, `import_rows`, `request_keys`, `quick_poll_creates`, and the per call working tables `import_input`, `import_people`, `import_payer`, `import_rates`) are not readable by them either. `mfa_satisfied`, `session_active` and `check_request` are executable by every API role because PostgREST and the realtime policies call them as the caller. `private.mfa_recovery_codes` and `private.mfa_recover_attempts` are readable by nobody but their owner. ### Two-step sign in @@ -999,6 +1023,7 @@ All jobs are `pg_cron` entries created by migrations, so every environment gets | `monthly-summary` | `0 15 1 * *` | `private.send_monthly_summaries()` | One `summary.monthly` notification (inbox card, email when on, never push) for everyone with a non-zero balance, about the month that just ended | | `purge-import-batches` | `*/15 * * * *` | `delete from private.import_batches` | Drops staged import parts older than an hour (an import nobody finished), with their rows | | `purge-invite-sends` | `20 3 * * *` | `delete from private.invite_sends` | Drops invite log rows older than a week; the daily invite limit only reads the last day | +| `purge-quick-polls` | `25 * * * *` | `private.purge_quick_polls()` | Deletes quick polls past `expires_at` with their answers and slots, and create log rows older than an hour | Each recurring template (in both recurring jobs) runs inside its own `begin ... exception` block, so one bad template logs a warning and the rest still run. diff --git a/docs/security.md b/docs/security.md index 486ef7f9..dc37aa1c 100644 --- a/docs/security.md +++ b/docs/security.md @@ -16,7 +16,7 @@ How Potluck protects its data, what it stores, and where the known weak spots ar | Actor | Can | Stopped by | | ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| Anyone on the internet | call the API with the publishable key | grants: `anon` can read `app_config`, call `invite_preview`, `invite_preview_v2`, `friend_invite_preview` (each needs a link code), `email_unsubscribe` (needs a signed token) and the two guest link RPCs (need a guest link code), and read the public buckets. Nothing else | +| Anyone on the internet | call the API with the publishable key | grants: `anon` can read `app_config`, call `invite_preview`, `invite_preview_v2`, `friend_invite_preview` (each needs a link code), `email_unsubscribe` (needs a signed token), the two guest link RPCs (need a guest link code) and the five quick poll RPCs (`create_quick_poll`, and four that need a poll code), and read the public buckets. Nothing else | | A signed-in stranger | call every RPC, query every table | RLS on every table, `require_member()` in every group RPC | | A group member overreaching | edit others' expenses, promote themselves, delete the group | role checks inside RPCs and policies, the role matrix in [architecture.md](architecture.md#roles) | | A removed or departed member | keep reading the group | membership is checked on every query. Realtime re-applies RLS per change | @@ -47,6 +47,7 @@ These are real today. Each should become an issue. - **Edge function CORS is `*`.** Harmless for the secret- and token-protected functions, and `delete-account` requires a JWT, but it is wider than the app needs. - **Invite previews show first names** to anyone with the code. That is the point of the join page, but it means an invite link is a small leak of who is in the group. A claim link also shows the saved seat's first name and its masked email. - **A placeholder's name and masked email are visible to its group.** The full address is readable by no client; the person who typed it in knows it. +- **Quick polls are open to anyone with the code until they expire** ([ADR 22](adr/0022-quick-polls-without-accounts.md)). Anyone can make one (5 an hour per client, 200 an hour in all); anyone with the code sees every answer's name and times and can add one answer per browser up to the poll's cap of 15. The per client limit keys on the first `x-forwarded-for` entry, which a client can set itself, so the global limit is the real backstop. Only the creator token closes or deletes a poll; the hourly purge deletes it once expired. - **Guest links are open doors until they close.** Anyone with the code can add names and times up to the link's cap, and the per link limits (20 new guests per 10 minutes, 60 saves per guest per hour) are counted in the database, not per IP. Organizers clean up with remove and turn off. The preview itself is a read and is not rate limited. - **Signing out elsewhere ends at the next request, not before.** "Sign out everywhere" and a password change delete every other session. The database then refuses those devices' tokens (`session_ended`, checked against `auth.sessions` in `private.check_request()`), and the app signs a device out when it sees that or when `getUser()` says the session is gone (on start, whenever the app comes back to the front, and at least every 30 seconds while it is on screen). Three paths do not check: Realtime keeps an open channel until the token expires (up to an hour, `jwt_expiry`), though each change it delivers makes the app refetch and so sign out; Storage downloads and edge functions accept the token until it expires. - **A fresh stolen session can change the password without the old one.** Within a day of signing in, Supabase sets a new password for the session alone; the Me page asks for the current password first, but the API does not unless the project turns on "require current password" (a dashboard setting, not in `config.toml`; the app already sends `current_password`). Older sessions need an emailed code (`secure_password_change`). Either way the account gets a "password changed" email. @@ -66,23 +67,25 @@ These are real today. Each should become an issue. ### What is stored -| Data | Where | Visible to | -| --------------------------------------------------------- | ------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Email, password hash, sessions | `auth.users` (Supabase Auth) | nobody through the API. Supabase operators | -| Display name, avatar, time zone, locale, default currency | `profiles` | you, people you share a group with or who left one of your groups, friends | -| Groups, members, invites | `groups`, `group_members`, `group_invites` | members. Invites only to admins and the invite's creator | -| People not on Potluck yet: name, invite email | `profiles`, `placeholders` | members of that group (the email masked); the address is used only for their invite and reminder, and deleted when they claim the seat or the group goes | -| Friend links | `friend_invites` | only you | -| Blocks, reports | `blocks`, `reports` | only you (the Potluck team reads reports) | -| Expenses, splits, settlements, comments | money tables, `comments` | members of that group | -| Availability, RSVPs, events | plans tables | members of that group | -| Guest names and times | `event_guests`, `event_guest_availability` | members of that group. Guests see only counts per slot, never names. The guest's token is stored as a sha256 hash nobody can read | -| Busy blocks, calendar links | `busy_blocks`, `calendar_connections` | only you. OAuth tokens would live in Vault (feature is off) | -| Notifications, push subscriptions | `notifications`, `push_tokens` | only you | -| Notification settings | `notification_prefs` | only you | -| Receipts and other attachments (up to five per expense) | private `receipts` bucket, `expense_attachments` | members of the group (authenticated download or signed URL) | -| Avatars, group covers | public buckets | anyone with the URL | -| Authenticator secrets, recovery code hashes | `auth.mfa_factors`, `private.mfa_recovery_codes` | nobody through the API. Supabase operators | +| Data | Where | Visible to | +| --------------------------------------------------------- | ------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Email, password hash, sessions | `auth.users` (Supabase Auth) | nobody through the API. Supabase operators | +| Display name, avatar, time zone, locale, default currency | `profiles` | you, people you share a group with or who left one of your groups, friends | +| Groups, members, invites | `groups`, `group_members`, `group_invites` | members. Invites only to admins and the invite's creator | +| People not on Potluck yet: name, invite email | `profiles`, `placeholders` | members of that group (the email masked); the address is used only for their invite and reminder, and deleted when they claim the seat or the group goes | +| Friend links | `friend_invites` | only you | +| Blocks, reports | `blocks`, `reports` | only you (the Potluck team reads reports) | +| Expenses, splits, settlements, comments | money tables, `comments` | members of that group | +| Availability, RSVPs, events | plans tables | members of that group | +| Quick poll names and times | `quick_polls`, `quick_poll_answers`, `quick_poll_slots` | anyone with the poll code, through `quick_poll_preview`, until the poll expires and the hourly purge deletes it. Tokens are stored as sha256 hashes nobody can read | +| Quick poll client addresses | `private.quick_poll_creates` | nobody; a sha256 of the first `x-forwarded-for` entry, kept an hour for the create rate limit | +| Guest names and times | `event_guests`, `event_guest_availability` | members of that group. Guests see only counts per slot, never names. The guest's token is stored as a sha256 hash nobody can read | +| Busy blocks, calendar links | `busy_blocks`, `calendar_connections` | only you. OAuth tokens would live in Vault (feature is off) | +| Notifications, push subscriptions | `notifications`, `push_tokens` | only you | +| Notification settings | `notification_prefs` | only you | +| Receipts and other attachments (up to five per expense) | private `receipts` bucket, `expense_attachments` | members of the group (authenticated download or signed URL) | +| Avatars, group covers | public buckets | anyone with the URL | +| Authenticator secrets, recovery code hashes | `auth.mfa_factors`, `private.mfa_recovery_codes` | nobody through the API. Supabase operators | There is no analytics or tracking code in the app. diff --git a/docs/testing.md b/docs/testing.md index d28d045e..b800cd67 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -118,6 +118,7 @@ Each file runs in its own transaction and rolls back, so tests do not leak into | `32_signed_out_sessions.test.sql` | `private.session_active` and the pre-request check: a token whose session was signed out is refused with `session_ended`, live sessions, other accounts, tokens without the claim and anon go through | | `33_expense_notice.test.sql` | a new expense's notification carries each recipient's `share_cents` and `paid_cents` (several payers, a payer outside the split, refunds) | | `35_request_keys.test.sql` | a save sent again with the same request id returns the first expense (`create_expense_v2`, `create_expense_with_attachments`) or payment (`settle_up_v3`), keys per person and kind, no key or a non uuid key saving each call, a refused try keeping no key, clients unable to read the keys | +| `36_quick_polls.test.sql` | quick polls: nobody reads or writes the tables, every create check, names on and off, seats and the cap, the creator token as answer token, each status in the preview, close, delete, the hourly purge, and the save and create rate limits | Every table in `public` needs tests for both who can and who cannot read and write it. A new RPC needs tests for each error code it can raise. From f66beb43fae1bba4def5a4618f0348831a334540 Mon Sep 17 00:00:00 2001 From: Musa Kaleem <131704022+Musa-Kal@users.noreply.github.com> Date: Sun, 22 Nov 2026 18:50:41 -0500 Subject: [PATCH 06/21] refactor(web): share link memory, public page frame, window fields and share sheet Guest links and quick polls both remember a token per code, sit in the same public frame with the same dead ends, ask for a date window and hours, and share a link. These pieces move out of the guest page and the plan form so both screens use one copy: - lib/link-memory.ts: a per-code record in localStorage that survives blocked storage; guest-token.ts becomes one instance of it. - shell/public-page.tsx: PublicFrame, DeadEnd, NextSteps, Notice and Pitch. - plans/window-fields.tsx and plans/window.ts: the date window and daily hours fields with an optional day cap, and the duration options. - invites/share.ts: shareLink, which shareInvite and shareGuestLink now use. - The heatmap and best times take an optional nameOf for full names. Co-authored-by: Ferrin <177692050+Ferrin-Y@users.noreply.github.com> Co-authored-by: noorelmosrati <182049385+noorelmosrati@users.noreply.github.com> --- .../availability/availability-heatmap.tsx | 5 +- .../src/features/guests/guest-page.test.tsx | 6 +- apps/web/src/features/guests/guest-page.tsx | 154 +++--------------- .../src/features/guests/guest-token.test.ts | 30 ++-- apps/web/src/features/guests/guest-token.ts | 36 +--- apps/web/src/features/guests/share.ts | 25 +-- apps/web/src/features/invites/share.ts | 30 +++- apps/web/src/features/plans/best-times.tsx | 5 +- .../src/features/plans/create-plan-page.tsx | 94 +++-------- apps/web/src/features/plans/window-fields.tsx | 96 +++++++++++ apps/web/src/features/plans/window.ts | 28 ++++ apps/web/src/features/shell/public-page.tsx | 137 ++++++++++++++++ apps/web/src/lib/link-memory.ts | 48 ++++++ 13 files changed, 426 insertions(+), 268 deletions(-) create mode 100644 apps/web/src/features/plans/window-fields.tsx create mode 100644 apps/web/src/features/plans/window.ts create mode 100644 apps/web/src/features/shell/public-page.tsx create mode 100644 apps/web/src/lib/link-memory.ts diff --git a/apps/web/src/features/availability/availability-heatmap.tsx b/apps/web/src/features/availability/availability-heatmap.tsx index f56884fb..50840179 100644 --- a/apps/web/src/features/availability/availability-heatmap.tsx +++ b/apps/web/src/features/availability/availability-heatmap.tsx @@ -27,6 +27,8 @@ export interface AvailabilityHeatmapProps { viewerId?: string label: string avatarUrl?: (path: string | null) => string | null + /** How the inspector names someone; first names with a guest tag by default. */ + nameOf?: (person: PlanMember | undefined) => string } interface SlotInfo { @@ -55,6 +57,7 @@ export function AvailabilityHeatmap({ viewerId, label, avatarUrl, + nameOf = personName, }: AvailabilityHeatmapProps) { const reduced = usePrefersReducedMotion() const gridRef = useRef(null) @@ -121,7 +124,7 @@ export function AvailabilityHeatmap({ } const shown = active ? info.get(active) : undefined - const names = (ids: string[]) => ids.map((id) => personName(byId.get(id))) + const names = (ids: string[]) => ids.map((id) => nameOf(byId.get(id))) return (
diff --git a/apps/web/src/features/guests/guest-page.test.tsx b/apps/web/src/features/guests/guest-page.test.tsx index 3e59161c..0e86424a 100644 --- a/apps/web/src/features/guests/guest-page.test.tsx +++ b/apps/web/src/features/guests/guest-page.test.tsx @@ -4,7 +4,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import { db, resetDb } from '@/test/supabase' import { renderWithProviders } from '@/test/render' import { GuestPage } from './guest-page' -import { readGuestMemory, writeGuestMemory } from './guest-token' +import { guestMemory } from './guest-token' vi.mock('@/lib/supabase', () => import('@/test/supabase')) @@ -84,7 +84,7 @@ describe('GuestPage', () => { slots: [{ slot_start: slot('18:00'), level: 'yes' }], }, ]) - expect(readGuestMemory('abc123')).toEqual({ token: 'tok-new', name: 'Ana' }) + expect(guestMemory.read('abc123')).toEqual({ token: 'tok-new', name: 'Ana' }) // After sending, the page shows how everyone looks, as counts only. expect(screen.getByRole('grid', { name: /How everyone looks/ })).toBeInTheDocument() await waitFor(() => @@ -96,7 +96,7 @@ describe('GuestPage', () => { }) it('brings a returning guest back to their answer and lets them change it', async () => { - writeGuestMemory('abc123', { token: 'tok-ana', name: 'Ana' }) + guestMemory.write('abc123', { token: 'tok-ana', name: 'Ana' }) const mine = { ...open, my_name: 'Ana', diff --git a/apps/web/src/features/guests/guest-page.tsx b/apps/web/src/features/guests/guest-page.tsx index 4c03349f..539dd132 100644 --- a/apps/web/src/features/guests/guest-page.tsx +++ b/apps/web/src/features/guests/guest-page.tsx @@ -14,9 +14,8 @@ import { usePrefersReducedMotion, } from '@potluck/ui' import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' -import { Link } from '@tanstack/react-router' import { CalendarDays, Clock } from 'lucide-react' -import { useEffect, useMemo, useRef, useState, type FormEvent, type ReactNode } from 'react' +import { useEffect, useMemo, useRef, useState, type FormEvent } from 'react' import { AvailabilityPainter } from '@/features/availability/availability-painter' import { buildGridModel, slotKey, type PaintLevel } from '@/features/availability/grid' import { Help } from '@/features/help/help' @@ -26,13 +25,12 @@ import { planErrorCode, planErrorMessage, } from '@/features/plans/format' -import { Wordmark } from '@/features/shell/brand' -import { useSession } from '@/lib/auth' +import { DeadEnd, NextSteps, Notice, Pitch, PublicFrame } from '@/features/shell/public-page' import { isNotFoundError } from '@/lib/errors' import { detectTimezone } from '@/lib/locale' import { supabase } from '@/lib/supabase' import { GuestHeatmap } from './guest-heatmap' -import { readGuestMemory, writeGuestMemory, type GuestMemory } from './guest-token' +import { guestMemory, type GuestMemory } from './guest-token' type OpenPreview = GuestLinkPreview & { plan: NonNullable } type Scheduled = NonNullable @@ -50,90 +48,6 @@ const CLOSING_CODES = new Set([ /** The longest name the server keeps, counted in characters like Postgres does. */ const MAX_NAME = 40 -function Frame({ children, wide = false }: { children: ReactNode; wide?: boolean }) { - return ( -
-
-
- - - - {children} -
-
- ) -} - -/** Where someone with no account goes next: sign up, or a look at what Potluck is. */ -function NextSteps() { - const session = useSession() - if (session) { - return ( - - ) - } - return ( -
- - -
- ) -} - -/** A dead end with a way out: the link closed, is unknown, is full, or the answer was removed. */ -function DeadEnd({ - emoji, - title, - body, - unsaved, -}: { - emoji: string - title: string - body: string - unsaved: boolean -}) { - return ( - -
- - {emoji} - -

{title}

- {unsaved && ( -

- {t('guests.closed.unsaved')} -

- )} -

{body}

- -
- - ) -} - function closedBody(status: GuestLinkPreview['status'] | 'not_found'): string { switch (status) { case 'expired': @@ -155,7 +69,7 @@ function closedBody(status: GuestLinkPreview['status'] | 'not_found'): string { * else about the group. The browser keeps the token the server returns so it can edit later. */ export function GuestPage({ code }: { code: string }) { - const [memory, setMemory] = useState(() => readGuestMemory(code)) + const [memory, setMemory] = useState(() => guestMemory.read(code)) // Painted or typed but not saved: if the link closes meanwhile, the closed page says so. const [unsaved, setUnsaved] = useState(false) // Saving hands back a token, which changes the query key; keep showing the plan meanwhile. @@ -166,20 +80,20 @@ export function GuestPage({ code }: { code: string }) { if (preview.isPending) { return ( - +
- +
) } if (preview.isError && !isNotFoundError(preview.error)) { return ( - +
📡 @@ -190,7 +104,7 @@ export function GuestPage({ code }: { code: string }) { {t('common.retry')}
- +
) } @@ -204,7 +118,7 @@ export function GuestPage({ code }: { code: string }) { emoji="🚪" title={t('guests.closed.removedTitle')} body={t('guests.closed.removed')} - unsaved={unsaved} + notice={unsaved ? t('guests.closed.unsaved') : undefined} /> ) } @@ -215,7 +129,7 @@ export function GuestPage({ code }: { code: string }) { emoji="🪑" title={t('guests.closed.fullTitle')} body={host ? t('guests.closed.full', { name: host }) : t('guests.closed.fullAnon')} - unsaved={unsaved} + notice={unsaved ? t('guests.closed.unsaved') : undefined} /> ) } @@ -225,7 +139,7 @@ export function GuestPage({ code }: { code: string }) { emoji="🔒" title={t('guests.closed.title')} body={closedBody(data?.status ?? 'not_found')} - unsaved={unsaved} + notice={unsaved ? t('guests.closed.unsaved') : undefined} /> ) } @@ -248,7 +162,7 @@ export function GuestPage({ code }: { code: string }) { function ScheduledPlan({ plan, unsaved }: { plan: Scheduled; unsaved: boolean }) { const timeZone = useMemo(() => detectTimezone(), []) return ( - +

@@ -266,20 +180,13 @@ function ScheduledPlan({ plan, unsaved }: { plan: Scheduled; unsaved: boolean })

{t('guests.page.timezoneNote', { zone: timeZone })}

- {unsaved && ( -

- {t('guests.closed.unsaved')} -

- )} + {unsaved && {t('guests.closed.unsaved')}}

{t('guests.scheduled.thanks', { name: plan.myName })}

- + ) } @@ -365,7 +272,7 @@ function GuestPoll({ }), onSuccess: (result) => { const next = { token: result.token, name: cleanName } - writeGuestMemory(code, next) + guestMemory.write(code, next) setName(cleanName) setJustSent(true) setEditing(false) @@ -412,7 +319,7 @@ function GuestPoll({ const respondents = preview.respondents ?? 0 return ( - +
@@ -456,7 +363,7 @@ function GuestPoll({

{closes} {zoneNote}

- +
{closes} {zoneNote}

- +
- +
) } @@ -604,22 +511,13 @@ function Sent({ name, stamp, onEdit }: { name: string; stamp: boolean; onEdit: ( ) } -function Pitch({ className }: { className?: string }) { +function GuestPitch({ className }: { className: string }) { return ( -
-

{t('guests.page.pitchTitle')}

-

{t('guests.page.pitchBody')}

-
- - -
-
+ } + className={className} + /> ) } diff --git a/apps/web/src/features/guests/guest-token.test.ts b/apps/web/src/features/guests/guest-token.test.ts index 0847d6b2..12622cd6 100644 --- a/apps/web/src/features/guests/guest-token.test.ts +++ b/apps/web/src/features/guests/guest-token.test.ts @@ -1,5 +1,5 @@ import { afterEach, describe, expect, it, vi } from 'vitest' -import { readGuestMemory, writeGuestMemory } from './guest-token' +import { guestMemory } from './guest-token' describe('guest memory', () => { afterEach(() => { @@ -8,26 +8,36 @@ describe('guest memory', () => { }) it('keeps a token and name per link', () => { - writeGuestMemory('a', { token: 't-a', name: 'Ana' }) - writeGuestMemory('b', { token: 't-b', name: 'Ben' }) - expect(readGuestMemory('a')).toEqual({ token: 't-a', name: 'Ana' }) - expect(readGuestMemory('b')).toEqual({ token: 't-b', name: 'Ben' }) + guestMemory.write('a', { token: 't-a', name: 'Ana' }) + guestMemory.write('b', { token: 't-b', name: 'Ben' }) + expect(guestMemory.read('a')).toEqual({ token: 't-a', name: 'Ana' }) + expect(guestMemory.read('b')).toEqual({ token: 't-b', name: 'Ben' }) }) it('ignores junk in storage', () => { window.localStorage.setItem('potluck.guest.x', '{not json') - expect(readGuestMemory('x')).toBeNull() + expect(guestMemory.read('x')).toBeNull() window.localStorage.setItem('potluck.guest.x', JSON.stringify({ name: 'No token' })) - expect(readGuestMemory('x')).toBeNull() + expect(guestMemory.read('x')).toBeNull() window.localStorage.setItem('potluck.guest.x', JSON.stringify({ token: 't', name: 3 })) - expect(readGuestMemory('x')).toEqual({ token: 't', name: '' }) + expect(guestMemory.read('x')).toEqual({ token: 't', name: '' }) + }) + + it('forgets a link', () => { + guestMemory.write('a', { token: 't-a', name: 'Ana' }) + guestMemory.forget('a') + expect(guestMemory.read('a')).toBeNull() }) it('carries on when storage is blocked', () => { vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => { throw new Error('blocked') }) - expect(() => writeGuestMemory('a', { token: 't', name: 'A' })).not.toThrow() - expect(readGuestMemory('a')).toBeNull() + vi.spyOn(Storage.prototype, 'removeItem').mockImplementation(() => { + throw new Error('blocked') + }) + expect(() => guestMemory.write('a', { token: 't', name: 'A' })).not.toThrow() + expect(() => guestMemory.forget('a')).not.toThrow() + expect(guestMemory.read('a')).toBeNull() }) }) diff --git a/apps/web/src/features/guests/guest-token.ts b/apps/web/src/features/guests/guest-token.ts index 6e9dd79d..a0c44fbf 100644 --- a/apps/web/src/features/guests/guest-token.ts +++ b/apps/web/src/features/guests/guest-token.ts @@ -1,32 +1,14 @@ -/** - * What a guest's browser remembers per link: the token the server handed back (proof that this - * browser wrote the answer, so it can edit it) and the name they typed. Storage can be missing or - * blocked (private windows, strict settings); the page then works, it just forgets on reload. - */ +import { linkMemory, storedRecord } from '@/lib/link-memory' + +/** What a guest's browser remembers per link: its answer token and the name they typed. */ export interface GuestMemory { token: string name: string } -const key = (code: string) => `potluck.guest.${code}` - -export function readGuestMemory(code: string): GuestMemory | null { - try { - const raw = window.localStorage.getItem(key(code)) - if (!raw) return null - const value = JSON.parse(raw) as Partial - return typeof value.token === 'string' && value.token - ? { token: value.token, name: typeof value.name === 'string' ? value.name : '' } - : null - } catch { - return null - } -} - -export function writeGuestMemory(code: string, memory: GuestMemory): void { - try { - window.localStorage.setItem(key(code), JSON.stringify(memory)) - } catch { - // Nowhere to keep it: the answer is saved, only editing from this browser is lost. - } -} +export const guestMemory = linkMemory('potluck.guest', (stored) => { + const value = storedRecord(stored) + return typeof value.token === 'string' && value.token + ? { token: value.token, name: typeof value.name === 'string' ? value.name : '' } + : null +}) diff --git a/apps/web/src/features/guests/share.ts b/apps/web/src/features/guests/share.ts index b5117477..4a3581f1 100644 --- a/apps/web/src/features/guests/share.ts +++ b/apps/web/src/features/guests/share.ts @@ -1,6 +1,5 @@ import { t } from '@potluck/i18n' -import { toast } from '@potluck/ui' -import { copyText } from '@/features/invites/share' +import { shareLink } from '@/features/invites/share' import { guestUrl } from '@/lib/app-url' /** A whole number from 1 to 100, or null. */ @@ -13,18 +12,12 @@ export function parseGuestCap(text: string): number | null { /** Native share sheet where there is one, clipboard otherwise. */ export async function shareGuestLink(eventTitle: string, code: string) { const url = guestUrl(code) - const data = { - title: t('guests.shareTitle', { event: eventTitle }), - text: t('guests.shareText', { event: eventTitle, url }), - url, - } - if (typeof navigator.share === 'function' && (!navigator.canShare || navigator.canShare(data))) { - try { - await navigator.share(data) - return - } catch (error) { - if (error instanceof DOMException && error.name === 'AbortError') return - } - } - if (await copyText(url)) toast.success(t('guests.panel.copied')) + await shareLink( + { + title: t('guests.shareTitle', { event: eventTitle }), + text: t('guests.shareText', { event: eventTitle, url }), + url, + }, + t('guests.panel.copied'), + ) } diff --git a/apps/web/src/features/invites/share.ts b/apps/web/src/features/invites/share.ts index 12e0d40b..ed322272 100644 --- a/apps/web/src/features/invites/share.ts +++ b/apps/web/src/features/invites/share.ts @@ -11,14 +11,14 @@ export async function copyText(text: string): Promise { } } -/** Native share sheet where there is one, clipboard otherwise. */ -export async function shareInvite(groupName: string, code: string) { - const url = inviteUrl(code) - const data = { - title: t('invites.shareTitle', { group: groupName }), - text: t('invites.shareText', { group: groupName, url }), - url, - } +/** + * Native share sheet where there is one, clipboard otherwise (then a toast saying `copied`). + * Closing the sheet without sharing is not an error. + */ +export async function shareLink( + data: { title: string; text: string; url: string }, + copied: string, +) { if (typeof navigator.share === 'function' && (!navigator.canShare || navigator.canShare(data))) { try { await navigator.share(data) @@ -27,5 +27,17 @@ export async function shareInvite(groupName: string, code: string) { if (error instanceof DOMException && error.name === 'AbortError') return } } - if (await copyText(url)) toast.success(t('invites.linkCopied')) + if (await copyText(data.url)) toast.success(copied) +} + +export async function shareInvite(groupName: string, code: string) { + const url = inviteUrl(code) + await shareLink( + { + title: t('invites.shareTitle', { group: groupName }), + text: t('invites.shareText', { group: groupName, url }), + url, + }, + t('invites.linkCopied'), + ) } diff --git a/apps/web/src/features/plans/best-times.tsx b/apps/web/src/features/plans/best-times.tsx index b9170c38..1465249f 100644 --- a/apps/web/src/features/plans/best-times.tsx +++ b/apps/web/src/features/plans/best-times.tsx @@ -16,6 +16,8 @@ export interface BestTimesProps { /** Called with the slot being looked at, so the heatmap can outline it. */ onPreview?: (slot: PlanBestSlot | null) => void avatarUrl?: (path: string | null) => string | null + /** How "missing" names someone; first names with a guest tag by default. */ + nameOf?: (person: PlanMember | undefined) => string } /** Ranked suggestions from `best_slots`, with "Lock it in" for the organizer and admins. */ @@ -27,6 +29,7 @@ export function BestTimes({ onLock, onPreview, avatarUrl, + nameOf = personName, }: BestTimesProps) { const [confirming, setConfirming] = useState(null) const people = members.filter((m) => !m.deleted) @@ -63,7 +66,7 @@ export function BestTimes({ const whoIsMissing = (slot: PlanBestSlot) => { const missing = slot.missing.filter((id) => byId.has(id)) if (missing.length === 0) return t('bestTime.everyoneCanMake') - const names = missing.map((id) => personName(byId.get(id))).filter(Boolean) + const names = missing.map((id) => nameOf(byId.get(id))).filter(Boolean) return names.length === missing.length ? t('bestTime.missing', { names: joinNames(names, 2) }) : t('bestTime.missingCount', { count: missing.length }) diff --git a/apps/web/src/features/plans/create-plan-page.tsx b/apps/web/src/features/plans/create-plan-page.tsx index f17864e9..4218b487 100644 --- a/apps/web/src/features/plans/create-plan-page.tsx +++ b/apps/web/src/features/plans/create-plan-page.tsx @@ -33,16 +33,12 @@ import { useMemo, useState, type FormEvent, type ReactNode } from 'react' import { supabase } from '@/lib/supabase' import { Help } from '@/features/help/help' import { BackToPlans } from './back-link' -import { formatDuration, formatMinuteOfDay, planErrorMessage } from './format' +import { planErrorMessage } from './format' import { useViewer, useViewerProfile } from './viewer' +import { addDays, durationOptions, type PollWindow } from './window' +import { WindowFields } from './window-fields' const EMOJIS = ['🍽️', '🍕', '🌮', '🍜', '🥾', '🎲', '🎬', '🏖️', '🎉', '☕'] -const DURATIONS = [30, 60, 90, 120, 180, 240, 360, 480, 720] -const DAY = 86_400_000 - -const addDays = (key: string, n: number) => - new Date(Date.parse(`${key}T00:00:00Z`) + n * DAY).toISOString().slice(0, 10) - /** The last user-perceived character typed, so a multi code point emoji stays whole. */ const lastGrapheme = (value: string) => [...new Intl.Segmenter().segment(value)].at(-1)?.segment ?? '' @@ -165,10 +161,12 @@ export function PlanForm({ groups, groupId, onGroupChange, timeZone, viewerId }: const [emoji, setEmoji] = useState(EMOJIS[0]!) const [location, setLocation] = useState('') const [description, setDescription] = useState('') - const [windowStart, setWindowStart] = useState(() => addDays(today, 1)) - const [windowEnd, setWindowEnd] = useState(() => addDays(today, 7)) - const [dayStart, setDayStart] = useState(600) - const [dayEnd, setDayEnd] = useState(1320) + const [pollWindow, setPollWindow] = useState(() => ({ + windowStart: addDays(today, 1), + windowEnd: addDays(today, 7), + dayStartMinute: 600, + dayEndMinute: 1320, + })) const [slot, setSlot] = useState<'15' | '30' | '60'>('30') const [duration, setDuration] = useState(120) const [minAttendees, setMinAttendees] = useState(2) @@ -185,13 +183,6 @@ export function PlanForm({ groups, groupId, onGroupChange, timeZone, viewerId }: const selected = picked[groupId] ?? new Set(others.map((m) => m.userId)) const setSelected = (next: Set) => setPicked((p) => ({ ...p, [groupId]: next })) - const windowDays = Math.round((Date.parse(windowEnd) - Date.parse(windowStart)) / DAY) + 1 || 0 - - const hourOptions = Array.from({ length: 49 }, (_, i) => i * 30).map((m) => ({ - value: String(m), - label: formatMinuteOfDay(m), - })) - const submit = async (e: FormEvent) => { e.preventDefault() if (!members.isSuccess) return @@ -201,10 +192,10 @@ export function PlanForm({ groups, groupId, onGroupChange, timeZone, viewerId }: emoji, location, description, - window_start: windowStart, - window_end: windowEnd, - day_start_minute: dayStart, - day_end_minute: dayEnd, + window_start: pollWindow.windowStart, + window_end: pollWindow.windowEnd, + day_start_minute: pollWindow.dayStartMinute, + day_end_minute: pollWindow.dayEndMinute, slot_minutes: Number(slot), duration_minutes: duration, min_attendees: minAttendees, @@ -327,56 +318,13 @@ export function PlanForm({ groups, groupId, onGroupChange, timeZone, viewerId }: } > -
- - { - setWindowStart(e.target.value) - if (e.target.value > windowEnd) setWindowEnd(e.target.value) - }} - /> - - - setWindowEnd(e.target.value)} - /> - -
- {windowDays > 0 && ( -

- {t('events.create.windowDays', { count: windowDays })} -

- )} -
- - setDayEnd(Number(v))} - options={hourOptions.slice(1)} - /> - -
+
setDuration(Number(v))} - options={DURATIONS.map((d) => ({ value: String(d), label: formatDuration(d) }))} + options={durationOptions()} />
diff --git a/apps/web/src/features/plans/window-fields.tsx b/apps/web/src/features/plans/window-fields.tsx new file mode 100644 index 00000000..a1f25a84 --- /dev/null +++ b/apps/web/src/features/plans/window-fields.tsx @@ -0,0 +1,96 @@ +import { t } from '@potluck/i18n' +import { Field, Input, Select } from '@potluck/ui' +import { formatMinuteOfDay } from './format' +import { addDays, windowDays, type PollWindow, type WindowField } from './window' + +/** + * The date range and daily hours of a poll, shared by plans and quick polls. Each control's id is + * `-` so a form can focus the first one with an error. With `maxDays`, the last + * day cannot be picked more than that many days after the first, and moving the first day pulls + * the last one along. + */ +export function WindowFields({ + value, + onChange, + today, + maxDays, + errors = {}, + idPrefix, +}: { + value: PollWindow + onChange: (next: PollWindow) => void + /** The earliest day to offer, `YYYY-MM-DD` in the viewer's zone. */ + today: string + maxDays?: number + errors?: Partial> + idPrefix: string +}) { + const days = windowDays(value) + const lastDay = (start: string) => (maxDays ? addDays(start, maxDays - 1) : undefined) + const hourOptions = Array.from({ length: 49 }, (_, i) => i * 30).map((m) => ({ + value: String(m), + label: formatMinuteOfDay(m), + })) + + return ( + <> +
+ + { + const start = e.target.value + const last = lastDay(start) + let end = value.windowEnd + if (start > end) end = start + else if (last && end > last) end = last + onChange({ ...value, windowStart: start, windowEnd: end }) + }} + /> + + + onChange({ ...value, windowEnd: e.target.value })} + /> + +
+ {days > 0 && ( +

{t('events.create.windowDays', { count: days })}

+ )} +
+ + onChange({ ...value, dayEndMinute: Number(v) })} + options={hourOptions.slice(1)} + /> + +
+ + ) +} diff --git a/apps/web/src/features/plans/window.ts b/apps/web/src/features/plans/window.ts new file mode 100644 index 00000000..bcc4ec61 --- /dev/null +++ b/apps/web/src/features/plans/window.ts @@ -0,0 +1,28 @@ +import { formatDuration } from './format' + +const DAY = 86_400_000 + +/** Which days and which hours of each day a poll asks about. Days are `YYYY-MM-DD`. */ +export interface PollWindow { + windowStart: string + windowEnd: string + dayStartMinute: number + dayEndMinute: number +} + +export type WindowField = 'window_start' | 'window_end' | 'day_end_minute' + +export const addDays = (key: string, n: number) => + new Date(Date.parse(`${key}T00:00:00Z`) + n * DAY).toISOString().slice(0, 10) + +/** Days from start to end, both included; 0 when the end is before the start. */ +export function windowDays(range: Pick): number { + return Math.round((Date.parse(range.windowEnd) - Date.parse(range.windowStart)) / DAY) + 1 || 0 +} + +const DURATIONS = [30, 60, 90, 120, 180, 240, 360, 480, 720] + +/** The lengths a plan can last, for a duration `Select`. */ +export function durationOptions() { + return DURATIONS.map((d) => ({ value: String(d), label: formatDuration(d) })) +} diff --git a/apps/web/src/features/shell/public-page.tsx b/apps/web/src/features/shell/public-page.tsx new file mode 100644 index 00000000..ddb226b5 --- /dev/null +++ b/apps/web/src/features/shell/public-page.tsx @@ -0,0 +1,137 @@ +import { t } from '@potluck/i18n' +import { Button, cn } from '@potluck/ui' +import { Link } from '@tanstack/react-router' +import type { ReactNode } from 'react' +import { useSession } from '@/lib/auth' +import { Wordmark } from './brand' + +/** + * The page around screens people reach from a shared link, signed in or out (guest links, quick + * polls): the wordmark home and a saffron glow, no app chrome. `wide` is for a grid beside a + * header; the narrow column is for a dead end or a short form. + */ +export function PublicFrame({ children, wide = false }: { children: ReactNode; wide?: boolean }) { + return ( +
+
+
+ + + + {children} +
+
+ ) +} + +/** Where someone with no account goes next: sign up, or a look at what Potluck is. */ +export function NextSteps() { + const session = useSession() + if (session) { + return ( + + ) + } + return ( +
+ + +
+ ) +} + +/** + * A dead end with a way out: the link closed, is unknown or is full. `notice` says what the + * visitor lost (times they painted but did not save); `actions` replaces the default next steps. + */ +export function DeadEnd({ + emoji, + title, + body, + notice, + actions = , +}: { + emoji: string + title: string + body: string + notice?: string + actions?: ReactNode +}) { + return ( + +
+ + {emoji} + +

{title}

+ {notice && {notice}} +

{body}

+ {actions} +
+
+ ) +} + +/** Something the visitor lost or cannot do, said once and plainly. */ +export function Notice({ children }: { children: ReactNode }) { + return ( +

+ {children} +

+ ) +} + +/** The quiet sign up pitch at the foot of a public page. */ +export function Pitch({ + title, + body, + help, + className, +}: { + title: string + body: string + /** A "?" beside the action. */ + help?: ReactNode + className?: string +}) { + return ( +
+

{title}

+

{body}

+
+ + {help} +
+
+ ) +} diff --git a/apps/web/src/lib/link-memory.ts b/apps/web/src/lib/link-memory.ts new file mode 100644 index 00000000..353ec138 --- /dev/null +++ b/apps/web/src/lib/link-memory.ts @@ -0,0 +1,48 @@ +/** + * What a browser remembers per shared link (a guest link, a quick poll): the token the server + * handed back, which proves this browser wrote the answer, plus whatever the page needs next time. + * Storage can be missing or blocked (private windows, strict settings); the page then works, it + * just forgets on reload. + */ +export interface LinkMemory { + read(code: string): T | null + write(code: string, value: T): void + forget(code: string): void +} + +/** + * One record per code under `.`. `parse` gets whatever JSON was stored and returns + * null for anything it does not recognize, so junk in storage reads as nothing remembered. + */ +export function linkMemory(prefix: string, parse: (stored: unknown) => T | null): LinkMemory { + const key = (code: string) => `${prefix}.${code}` + return { + read(code) { + try { + const raw = window.localStorage.getItem(key(code)) + return raw ? parse(JSON.parse(raw)) : null + } catch { + return null + } + }, + write(code, value) { + try { + window.localStorage.setItem(key(code), JSON.stringify(value)) + } catch { + // Nowhere to keep it: the answer is saved, only editing from this browser is lost. + } + }, + forget(code) { + try { + window.localStorage.removeItem(key(code)) + } catch { + // Nothing was kept. + } + }, + } +} + +/** The stored value as a record, or an empty one. */ +export function storedRecord(stored: unknown): Record { + return stored && typeof stored === 'object' ? (stored as Record) : {} +} From 23f3ac1809d821279c0db1a1942f752076cd4a69 Mon Sep 17 00:00:00 2001 From: Musa Kaleem <131704022+Musa-Kal@users.noreply.github.com> Date: Sun, 22 Nov 2026 19:08:04 -0500 Subject: [PATCH 07/21] refactor(web): share the sent card, window facts and token memory with guest links The guest page's "times in" card and its list of days, hours and length move to features/availability, and the token and name record becomes parseTokenMemory in lib/link-memory, so quick polls reuse them. Co-authored-by: Ferrin <177692050+Ferrin-Y@users.noreply.github.com> Co-authored-by: noorelmosrati <182049385+noorelmosrati@users.noreply.github.com> --- .../src/features/availability/sent-card.tsx | 46 +++++++++++ .../features/availability/window-facts.tsx | 66 +++++++++++++++ apps/web/src/features/guests/guest-page.tsx | 80 +++---------------- apps/web/src/features/guests/guest-token.ts | 14 +--- apps/web/src/lib/link-memory.ts | 15 +++- 5 files changed, 138 insertions(+), 83 deletions(-) create mode 100644 apps/web/src/features/availability/sent-card.tsx create mode 100644 apps/web/src/features/availability/window-facts.tsx diff --git a/apps/web/src/features/availability/sent-card.tsx b/apps/web/src/features/availability/sent-card.tsx new file mode 100644 index 00000000..9cdc2555 --- /dev/null +++ b/apps/web/src/features/availability/sent-card.tsx @@ -0,0 +1,46 @@ +import { Button, Card, Stamp, StampAnimation } from '@potluck/ui' + +/** + * Someone without an account just sent their times: an olive stamp, a thank you and a way back + * into editing. `stamp` plays the stamp's landing, only right after sending. + */ +export function SentCard({ + stamp, + stampLabel, + title, + body, + actionLabel, + onAction, +}: { + stamp: boolean + stampLabel: string + title: string + body: string + actionLabel: string + onAction: () => void +}) { + return ( + +
+ {stamp ? ( + + {stampLabel} + + ) : ( + + {stampLabel} + + )} +
+
+

+ {title} +

+

{body}

+
+ +
+ ) +} diff --git a/apps/web/src/features/availability/window-facts.tsx b/apps/web/src/features/availability/window-facts.tsx new file mode 100644 index 00000000..ecd03152 --- /dev/null +++ b/apps/web/src/features/availability/window-facts.tsx @@ -0,0 +1,66 @@ +import { formatDateRange, formatTime, t } from '@potluck/i18n' +import { CalendarDays, Clock } from 'lucide-react' +import type { ReactNode } from 'react' +import { formatDuration, minuteOfDayIn } from '@/features/plans/format' +import type { GridEvent } from './grid' + +/** One line of `WindowFacts`: an icon, a label for screen readers and the value. */ +export function Fact({ + icon, + label, + children, +}: { + icon: ReactNode + label: string + children: ReactNode +}) { + return ( +
+
{label}
+ + {icon} + +
{children}
+
+ ) +} + +/** + * What a poll asks about, in the viewer's zone: the days and hours, then how long the plan + * lasts. `children` adds more `Fact` lines. + */ +export function WindowFacts({ + grid, + durationMinutes, + timeZone, + children, +}: { + grid: Pick< + GridEvent, + 'window_start' | 'window_end' | 'day_start_minute' | 'day_end_minute' | 'timezone' + > + durationMinutes: number + timeZone: string + children?: ReactNode +}) { + const at = (minute: number) => + formatTime(minuteOfDayIn(grid.window_start, minute, grid.timezone), { timeZone }) + return ( +
+ } label={t('events.when')}> + {t('events.windowRange', { + range: formatDateRange(grid.window_start, grid.window_end, { timeZone }), + from: at(grid.day_start_minute), + to: at(grid.day_end_minute), + })} + + } label={t('events.create.durationLabel')}> + {t('events.durationShort', { duration: formatDuration(durationMinutes) })} + + {children} +
+ ) +} diff --git a/apps/web/src/features/guests/guest-page.tsx b/apps/web/src/features/guests/guest-page.tsx index 539dd132..d1bcdf8f 100644 --- a/apps/web/src/features/guests/guest-page.tsx +++ b/apps/web/src/features/guests/guest-page.tsx @@ -1,6 +1,6 @@ import { guestKeys, guestQueries, setGuestAvailability, type GuestLinkPreview } from '@potluck/api' import { cleanGuestName } from '@potluck/core' -import { formatDate, formatDateRange, formatTime, t } from '@potluck/i18n' +import { formatDate, formatTime, t } from '@potluck/i18n' import { Button, Card, @@ -9,22 +9,16 @@ import { Input, SegmentedControl, Skeleton, - Stamp, - StampAnimation, usePrefersReducedMotion, } from '@potluck/ui' import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' -import { CalendarDays, Clock } from 'lucide-react' import { useEffect, useMemo, useRef, useState, type FormEvent } from 'react' import { AvailabilityPainter } from '@/features/availability/availability-painter' import { buildGridModel, slotKey, type PaintLevel } from '@/features/availability/grid' +import { SentCard } from '@/features/availability/sent-card' +import { WindowFacts } from '@/features/availability/window-facts' import { Help } from '@/features/help/help' -import { - formatDuration, - minuteOfDayIn, - planErrorCode, - planErrorMessage, -} from '@/features/plans/format' +import { planErrorCode, planErrorMessage } from '@/features/plans/format' import { DeadEnd, NextSteps, Notice, Pitch, PublicFrame } from '@/features/shell/public-page' import { isNotFoundError } from '@/lib/errors' import { detectTimezone } from '@/lib/locale' @@ -331,35 +325,7 @@ function GuestPoll({

{plan.title}

-
-
-
{t('events.when')}
- -
- {t('events.windowRange', { - range: formatDateRange(plan.window_start, plan.window_end, { timeZone }), - from: formatTime( - minuteOfDayIn(plan.window_start, plan.day_start_minute, plan.timezone), - { timeZone }, - ), - to: formatTime( - minuteOfDayIn(plan.window_start, plan.day_end_minute, plan.timezone), - { timeZone }, - ), - })} -
-
-
-
{t('events.create.durationLabel')}
- -
- {t('events.durationShort', { duration: formatDuration(plan.duration_minutes) })} -
-
-
+

{closes} {zoneNote}

@@ -372,10 +338,13 @@ function GuestPoll({ aria-labelledby="guest-poll-title" > {!editing ? ( - { + stampLabel={t('guests.page.sentStamp')} + title={t('guests.page.sentTitle', { name: cleanName })} + body={t('guests.page.sentBody')} + actionLabel={t('guests.page.edit')} + onAction={() => { setEditing(true) setView('mine') setJustSent(false) @@ -484,33 +453,6 @@ function GuestPoll({ ) } -function Sent({ name, stamp, onEdit }: { name: string; stamp: boolean; onEdit: () => void }) { - return ( - -
- {stamp ? ( - - {t('guests.page.sentStamp')} - - ) : ( - - {t('guests.page.sentStamp')} - - )} -
-
-

- {t('guests.page.sentTitle', { name })} -

-

{t('guests.page.sentBody')}

-
- -
- ) -} - function GuestPitch({ className }: { className: string }) { return ( ('potluck.guest', (stored) => { - const value = storedRecord(stored) - return typeof value.token === 'string' && value.token - ? { token: value.token, name: typeof value.name === 'string' ? value.name : '' } - : null -}) +export const guestMemory = linkMemory('potluck.guest', parseTokenMemory) diff --git a/apps/web/src/lib/link-memory.ts b/apps/web/src/lib/link-memory.ts index 353ec138..11ee2906 100644 --- a/apps/web/src/lib/link-memory.ts +++ b/apps/web/src/lib/link-memory.ts @@ -42,7 +42,16 @@ export function linkMemory(prefix: string, parse: (stored: unknown) => T | nu } } -/** The stored value as a record, or an empty one. */ -export function storedRecord(stored: unknown): Record { - return stored && typeof stored === 'object' ? (stored as Record) : {} +/** The usual record: the token that proves this browser wrote its answer, and the name typed. */ +export interface TokenMemory { + token: string + name: string +} + +/** Reads a `TokenMemory`; a record without a token is nothing remembered. */ +export function parseTokenMemory(stored: unknown): TokenMemory | null { + const value = stored && typeof stored === 'object' ? (stored as Record) : {} + return typeof value.token === 'string' && value.token + ? { token: value.token, name: typeof value.name === 'string' ? value.name : '' } + : null } From 32cb20d6157cacb1ecc4cbaa2a717d6a000648c8 Mon Sep 17 00:00:00 2001 From: Musa Kaleem <131704022+Musa-Kal@users.noreply.github.com> Date: Sun, 22 Nov 2026 19:08:04 -0500 Subject: [PATCH 08/21] feat(i18n): word the quick poll screens and the landing entry Create page, poll page, dead ends and the landing page entry, in English, German, Spanish, French and Portuguese. Co-authored-by: Ferrin <177692050+Ferrin-Y@users.noreply.github.com> Co-authored-by: noorelmosrati <182049385+noorelmosrati@users.noreply.github.com> --- packages/i18n/src/de/quick-polls.ts | 94 +++++++++++++++++++++++++++++ packages/i18n/src/de/shell.ts | 5 ++ packages/i18n/src/en/quick-polls.ts | 93 +++++++++++++++++++++++++++- packages/i18n/src/en/shell.ts | 5 ++ packages/i18n/src/es/quick-polls.ts | 93 ++++++++++++++++++++++++++++ packages/i18n/src/es/shell.ts | 5 ++ packages/i18n/src/fr/quick-polls.ts | 93 ++++++++++++++++++++++++++++ packages/i18n/src/fr/shell.ts | 5 ++ packages/i18n/src/pt/quick-polls.ts | 93 ++++++++++++++++++++++++++++ packages/i18n/src/pt/shell.ts | 5 ++ 10 files changed, 490 insertions(+), 1 deletion(-) diff --git a/packages/i18n/src/de/quick-polls.ts b/packages/i18n/src/de/quick-polls.ts index 3670f839..52a68388 100644 --- a/packages/i18n/src/de/quick-polls.ts +++ b/packages/i18n/src/de/quick-polls.ts @@ -2,6 +2,100 @@ import type { Translation } from '../locales' import type * as en from '../en/quick-polls' export const quickPolls = { + defaultTitle: 'Termin finden', + anonymous: 'Anonym {seat}', + create: { + title: 'Termin finden', + intro: + 'Erstell eine Umfrage, schick den Link und sieh, wann alle Zeit haben. Niemand braucht ein Konto.', + titleLabel: 'Worum geht es?', + when: 'Wann könnte es sein?', + more: 'Mehr Optionen', + summary: '{names}, bis zu {max} Personen, offen für {expiry}', + namesOn: 'Mit Namen', + namesOff: 'Anonym', + namesLabel: 'Nach Namen fragen', + namesHint: 'Alle sehen, wer wann Zeit hat. Schalte es aus für anonyme Antworten.', + maxLabel: 'Personen, die antworten können', + maxHint: '{min} bis {max}, dich eingeschlossen.', + fewer: 'Weniger Personen', + morePeople: 'Mehr Personen', + expiryLabel: 'Die Umfrage bleibt offen für', + expiry: { + day: '24 Stunden', + week: '7 Tage', + }, + submit: 'Umfrage erstellen', + footnote: 'Wenn die Umfrage endet, wird sie mit allen Antworten gelöscht.', + }, + page: { + closes: 'Offen bis {date}.', + resultsUntil: 'Die Ergebnisse bleiben bis {date} sichtbar.', + timezoneNote: 'Die Zeiten sind in deiner Zeitzone, {zone}.', + answered_one: '{count} von {max} hat geantwortet', + answered_other: '{count} von {max} haben geantwortet', + anonymousNote: 'Die Antworten sind anonym.', + readyTitle: 'Deine Umfrage ist bereit', + readyBody: + 'Schick den Link an alle, die du fragen willst. Dann trag unten deine eigenen Zeiten ein.', + linkLabel: 'Umfragelink', + copy: 'Link kopieren', + copied: 'Umfragelink kopiert', + share: 'Teilen', + shareTitle: 'Wann hast du Zeit für {title}?', + shareText: 'Trag deine Zeiten für {title} ein. Kein Konto nötig: {url}', + paintTitle: 'Wann hast du Zeit?', + nameLabel: 'Dein Name', + nameHint: 'Alle in dieser Umfrage sehen ihn.', + needName: 'Trag zuerst deinen Namen ein.', + needTimes: 'Male zuerst mindestens eine Zeit.', + submit: 'Meine Zeiten senden', + update: 'Meine Zeiten aktualisieren', + cancel: 'Meine Zeiten behalten', + sentStamp: 'Eingetragen', + sentTitle: 'Danke, {name}. Du stehst auf der Liste.', + sentTitleAnon: 'Danke. Du stehst als {name} auf der Liste.', + sentBody: + 'Öffne diesen Link auf diesem Gerät wieder, um sie zu ändern, jederzeit bis die Umfrage endet.', + edit: 'Meine Zeiten ändern', + gridLabel: 'Deine Zeiten für {title}', + everyoneTitle: 'Alle', + heatGridLabel: 'Die Zeiten aller für {title}', + noAnswersTitle: 'Noch hat niemand geantwortet', + noAnswersBody: + 'Schick den Link herum. Die Zeiten leuchten hier auf, sobald Leute sie eintragen.', + fullTitle: 'Diese Umfrage ist voll', + fullBody: + 'Alle {max} Plätze sind vergeben, neue Antworten gehen also nicht mehr. So sieht es bei allen aus.', + closedTitle: 'Diese Umfrage ist geschlossen', + closedBody: 'Wer sie erstellt hat, hat sie geschlossen, die Zeiten stehen also fest.', + closedByYou: 'Du hast diese Umfrage geschlossen, die Zeiten stehen also fest.', + unsaved: 'Deine Zeiten wurden nicht gespeichert.', + yourPoll: 'Deine Umfrage', + close: 'Umfrage schließen', + closeTitle: 'Diese Umfrage schließen?', + closeConfirm: + 'Danach kann niemand mehr Zeiten eintragen oder ändern. Alle mit dem Link sehen die Ergebnisse weiter, bis die Umfrage endet.', + closed: 'Umfrage geschlossen', + delete: 'Umfrage löschen', + deleteTitle: 'Diese Umfrage löschen?', + deleteConfirm: + 'Die Umfrage und alle Antworten sind sofort für alle weg. Das lässt sich nicht rückgängig machen.', + deleted: 'Umfrage gelöscht', + pitchTitle: 'Wird daraus ein Plan?', + pitchBody: + 'Mit einem kostenlosen Konto behält Potluck deine Pläne, schickt Erinnerungen, legt die Zeit fest und teilt danach die Rechnung.', + loadFailedTitle: 'Kein Empfang', + loadFailed: + 'Wir konnten diese Umfrage nicht öffnen. Prüf deine Verbindung und versuch es noch mal.', + }, + ended: { + title: 'Diese Umfrage ist vorbei', + body: 'Umfragen sind nur eine Weile offen, und diese ist abgelaufen. Ihre Antworten sind auch weg.', + notFoundTitle: 'Hier ist keine Umfrage', + notFound: 'Dieser Link führt zu keiner Umfrage. Prüf, ob er ganz kopiert wurde.', + newPoll: 'Neue Umfrage erstellen', + }, errors: { quick_poll_not_found: 'Dieser Umfragelink führt nirgendwohin.', quick_poll_expired: 'Diese Umfrage ist vorbei.', diff --git a/packages/i18n/src/de/shell.ts b/packages/i18n/src/de/shell.ts index 225ef450..a0ed6684 100644 --- a/packages/i18n/src/de/shell.ts +++ b/packages/i18n/src/de/shell.ts @@ -12,6 +12,10 @@ export const app = { body: 'Potluck führt eine laufende Rechnung für deine Leute und findet den Abend, an dem wirklich alle können. Kostenlos, Open Source und keine Werbung am Tisch.', cta: 'Tisch eröffnen', secondary: 'Ich habe schon ein Konto', + quickPoll: { + title: 'Termin finden, ohne Anmeldung', + body: 'Schick eine schnelle Umfrage und sieh, wann alle Zeit haben.', + }, demo: { label: 'Eine kurze Demo: Eine Restaurantrechnung wird durch vier geteilt, dann markieren Freunde, wann sie Zeit haben, und ein Abend wird festgezurrt.', @@ -44,6 +48,7 @@ export const app = { night: { title: 'Der Abend', body: 'Alle ziehen über die Stunden, in denen sie Zeit haben. Das Raster leuchtet dort auf, wo es passt, und der beste Termin schwimmt nach oben.', + poll: 'Oder starte mit einer schnellen Umfrage, ganz ohne Konto', }, square: { title: 'Die Abrechnung', diff --git a/packages/i18n/src/en/quick-polls.ts b/packages/i18n/src/en/quick-polls.ts index 5f1ffc26..3136dc04 100644 --- a/packages/i18n/src/en/quick-polls.ts +++ b/packages/i18n/src/en/quick-polls.ts @@ -1,5 +1,96 @@ /** Quick polls: availability polls anyone can make and answer without an account (ADR 22). */ export const quickPolls = { + /** Shown when the person who made the poll gave it no title. */ + defaultTitle: 'Find a time', + /** Answers when the poll does not ask for names, numbered by the order people answered. */ + anonymous: 'Anonymous {seat}', + create: { + title: 'Find a time', + intro: 'Make a poll, send the link, see when everyone is free. Nobody needs an account.', + titleLabel: 'What is it for?', + when: 'When could it be?', + more: 'More options', + summary: '{names}, up to {max} people, open for {expiry}', + namesOn: 'Names on', + namesOff: 'Anonymous', + namesLabel: 'Ask for names', + namesHint: 'Everyone sees who is free when. Turn it off for anonymous answers.', + maxLabel: 'People who can answer', + maxHint: '{min} to {max}, you included.', + fewer: 'Fewer people', + morePeople: 'More people', + expiryLabel: 'Poll stays open for', + expiry: { + day: '24 hours', + week: '7 days', + }, + submit: 'Create poll', + footnote: 'When the poll ends, it is deleted with every answer.', + }, + page: { + closes: 'Open until {date}.', + resultsUntil: 'Results stay up until {date}.', + timezoneNote: 'Times are in your time zone, {zone}.', + answered_one: '{count} of {max} answered', + answered_other: '{count} of {max} answered', + anonymousNote: 'Answers are anonymous.', + readyTitle: 'Your poll is ready', + readyBody: 'Send the link to everyone you want to ask. Then add your own times below.', + linkLabel: 'Poll link', + copy: 'Copy link', + copied: 'Poll link copied', + share: 'Share', + shareTitle: 'When are you free for {title}?', + shareText: 'Add your times for {title}. No account needed: {url}', + paintTitle: 'When are you free?', + nameLabel: 'Your name', + nameHint: 'Everyone in this poll sees it.', + needName: 'Add your name first.', + needTimes: 'Paint at least one time first.', + submit: 'Send my times', + update: 'Update my times', + cancel: 'Keep my times', + sentStamp: 'Times in', + sentTitle: 'Thanks, {name}. You are on the list.', + sentTitleAnon: 'Thanks. You are on the list as {name}.', + sentBody: 'Open this link again on this device to change them, any time until the poll ends.', + edit: 'Change my times', + gridLabel: 'Your times for {title}', + everyoneTitle: 'Everyone', + heatGridLabel: "Everyone's times for {title}", + noAnswersTitle: 'Nobody has answered yet', + noAnswersBody: 'Send the link around. Times warm up here as people add them.', + fullTitle: 'This poll is full', + fullBody: + 'All {max} spots are taken, so it cannot take new answers. Here is how everyone looks.', + closedTitle: 'This poll is closed', + closedBody: 'Whoever made it closed it, so these times are final.', + closedByYou: 'You closed this poll, so these times are final.', + unsaved: 'Your times were not saved.', + yourPoll: 'Your poll', + close: 'Close poll', + closeTitle: 'Close this poll?', + closeConfirm: + 'Nobody can add or change times after this. Everyone with the link still sees the results until the poll ends.', + closed: 'Poll closed', + delete: 'Delete poll', + deleteTitle: 'Delete this poll?', + deleteConfirm: + 'The poll and every answer are gone for everyone, right now. This cannot be undone.', + deleted: 'Poll deleted', + pitchTitle: 'Turning this into a plan?', + pitchBody: + 'With a free account Potluck keeps your plans, sends reminders, locks in the time and splits the bill after.', + loadFailedTitle: 'Lost the signal', + loadFailed: 'We could not open this poll. Check your connection and try again.', + }, + ended: { + title: 'This poll has ended', + body: 'Polls only stay open for a while, and this one is over. Its answers are gone too.', + notFoundTitle: 'No poll here', + notFound: 'This link does not lead to a poll. Check that it was copied in full.', + newPoll: 'Make a new poll', + }, /** Server codes the quick poll screens show, `errorMessage(error, 'quickPolls.errors')`. */ errors: { quick_poll_not_found: 'That poll link does not lead anywhere.', @@ -23,4 +114,4 @@ export const quickPolls = { duplicate_slot: 'A time showed up twice. Try again?', not_allowed: 'Only whoever made the poll can do that.', }, -} +} as const diff --git a/packages/i18n/src/en/shell.ts b/packages/i18n/src/en/shell.ts index fa3eaa7d..049270ef 100644 --- a/packages/i18n/src/en/shell.ts +++ b/packages/i18n/src/en/shell.ts @@ -9,6 +9,10 @@ export const app = { body: 'Potluck keeps a running tab for your people and finds the evening everyone can actually make. Free, open source, and no ads at the table.', cta: 'Start a table', secondary: 'I already have an account', + quickPoll: { + title: 'Find a time, no sign-up', + body: 'Send a quick poll and see when everyone is free.', + }, demo: { label: 'A short demo: a dinner bill splits four ways, then friends paint when they are free and a night gets locked in.', @@ -41,6 +45,7 @@ export const app = { night: { title: 'The night', body: 'Everyone drags across the hours they are free. The grid warms up where it works and the best slot floats to the top.', + poll: 'Or start with a quick poll, no account needed', }, square: { title: 'The square up', diff --git a/packages/i18n/src/es/quick-polls.ts b/packages/i18n/src/es/quick-polls.ts index 2e179d28..10705515 100644 --- a/packages/i18n/src/es/quick-polls.ts +++ b/packages/i18n/src/es/quick-polls.ts @@ -2,6 +2,99 @@ import type { Translation } from '../locales' import type * as en from '../en/quick-polls' export const quickPolls = { + defaultTitle: 'Encontrar un horario', + anonymous: 'Anónimo {seat}', + create: { + title: 'Encontrar un horario', + intro: + 'Crea una encuesta, manda el enlace y mira cuándo puede todo el mundo. Nadie necesita cuenta.', + titleLabel: '¿Para qué es?', + when: '¿Cuándo podría ser?', + more: 'Más opciones', + summary: '{names}, hasta {max} personas, abierta {expiry}', + namesOn: 'Con nombres', + namesOff: 'Anónima', + namesLabel: 'Pedir nombres', + namesHint: 'Todos ven quién puede y cuándo. Desactívalo para respuestas anónimas.', + maxLabel: 'Personas que pueden responder', + maxHint: 'De {min} a {max}, contándote a ti.', + fewer: 'Menos personas', + morePeople: 'Más personas', + expiryLabel: 'La encuesta queda abierta', + expiry: { + day: '24 horas', + week: '7 días', + }, + submit: 'Crear encuesta', + footnote: 'Cuando la encuesta termina, se borra con todas las respuestas.', + }, + page: { + closes: 'Abierta hasta el {date}.', + resultsUntil: 'Los resultados siguen visibles hasta el {date}.', + timezoneNote: 'Las horas están en tu zona horaria, {zone}.', + answered_one: '{count} de {max} respondió', + answered_other: '{count} de {max} respondieron', + anonymousNote: 'Las respuestas son anónimas.', + readyTitle: 'Tu encuesta está lista', + readyBody: + 'Manda el enlace a todas las personas a las que quieras preguntar. Luego añade tus propias horas abajo.', + linkLabel: 'Enlace de la encuesta', + copy: 'Copiar enlace', + copied: 'Enlace de la encuesta copiado', + share: 'Compartir', + shareTitle: '¿Cuándo puedes para {title}?', + shareText: 'Añade tus horas para {title}. No hace falta cuenta: {url}', + paintTitle: '¿Cuándo puedes?', + nameLabel: 'Tu nombre', + nameHint: 'Todos en esta encuesta lo ven.', + needName: 'Primero añade tu nombre.', + needTimes: 'Pinta al menos una hora primero.', + submit: 'Enviar mis horas', + update: 'Actualizar mis horas', + cancel: 'Mantener mis horas', + sentStamp: 'Recibido', + sentTitle: 'Gracias, {name}. Ya estás en la lista.', + sentTitleAnon: 'Gracias. Ya estás en la lista como {name}.', + sentBody: + 'Abre este enlace otra vez en este dispositivo para cambiarlas, cuando quieras hasta que termine la encuesta.', + edit: 'Cambiar mis horas', + gridLabel: 'Tus horas para {title}', + everyoneTitle: 'Todos', + heatGridLabel: 'Las horas de todos para {title}', + noAnswersTitle: 'Nadie ha respondido todavía', + noAnswersBody: + 'Haz circular el enlace. Las horas se calientan aquí a medida que la gente las añade.', + fullTitle: 'Esta encuesta está llena', + fullBody: + 'Los {max} lugares están ocupados, así que no admite respuestas nuevas. Así quedan las horas de todos.', + closedTitle: 'Esta encuesta está cerrada', + closedBody: 'Quien la creó la cerró, así que estas horas son finales.', + closedByYou: 'Cerraste esta encuesta, así que estas horas son finales.', + unsaved: 'Tus horas no se guardaron.', + yourPoll: 'Tu encuesta', + close: 'Cerrar encuesta', + closeTitle: '¿Cerrar esta encuesta?', + closeConfirm: + 'Después de esto nadie podrá añadir ni cambiar horas. Quien tenga el enlace seguirá viendo los resultados hasta que termine la encuesta.', + closed: 'Encuesta cerrada', + delete: 'Eliminar encuesta', + deleteTitle: '¿Eliminar esta encuesta?', + deleteConfirm: + 'La encuesta y todas las respuestas desaparecen para todos, ahora mismo. No se puede deshacer.', + deleted: 'Encuesta eliminada', + pitchTitle: '¿Lo convertimos en un plan?', + pitchBody: + 'Con una cuenta gratis, Potluck guarda tus planes, manda recordatorios, fija la hora y después divide la cuenta.', + loadFailedTitle: 'Se perdió la señal', + loadFailed: 'No pudimos abrir esta encuesta. Revisa tu conexión e inténtalo de nuevo.', + }, + ended: { + title: 'Esta encuesta terminó', + body: 'Las encuestas solo quedan abiertas un tiempo, y esta ya terminó. Sus respuestas también se borraron.', + notFoundTitle: 'Aquí no hay ninguna encuesta', + notFound: 'Este enlace no lleva a ninguna encuesta. Revisa que se copió completo.', + newPoll: 'Crear una encuesta nueva', + }, errors: { quick_poll_not_found: 'Ese enlace de encuesta no lleva a ningún sitio.', quick_poll_expired: 'Esta encuesta terminó.', diff --git a/packages/i18n/src/es/shell.ts b/packages/i18n/src/es/shell.ts index df70b34a..f8137a07 100644 --- a/packages/i18n/src/es/shell.ts +++ b/packages/i18n/src/es/shell.ts @@ -12,6 +12,10 @@ export const app = { body: 'Potluck lleva la cuenta de tu gente y encuentra la noche en la que todos pueden de verdad. Gratis, de código abierto y sin anuncios en la mesa.', cta: 'Abre una mesa', secondary: 'Ya tengo una cuenta', + quickPoll: { + title: 'Encuentra un horario, sin registro', + body: 'Manda una encuesta rápida y mira cuándo puede todo el mundo.', + }, demo: { label: 'Una demo corta: la cuenta de una cena se divide entre cuatro, luego los amigos marcan cuándo están libres y se fija una noche.', @@ -44,6 +48,7 @@ export const app = { night: { title: 'La noche', body: 'Cada uno arrastra por las horas en que está libre. La cuadrícula se calienta donde encaja y el mejor hueco sube arriba.', + poll: 'O empieza con una encuesta rápida, sin cuenta', }, square: { title: 'Las cuentas claras', diff --git a/packages/i18n/src/fr/quick-polls.ts b/packages/i18n/src/fr/quick-polls.ts index da4c97c5..228ee515 100644 --- a/packages/i18n/src/fr/quick-polls.ts +++ b/packages/i18n/src/fr/quick-polls.ts @@ -2,6 +2,99 @@ import type { Translation } from '../locales' import type * as en from '../en/quick-polls' export const quickPolls = { + defaultTitle: 'Trouver un créneau', + anonymous: 'Anonyme {seat}', + create: { + title: 'Trouver un créneau', + intro: + "Crée un sondage, envoie le lien, vois quand tout le monde est dispo. Personne n'a besoin de compte.", + titleLabel: "C'est pour quoi ?", + when: 'Ça pourrait être quand ?', + more: "Plus d'options", + summary: "{names}, jusqu'à {max} personnes, ouvert {expiry}", + namesOn: 'Avec les noms', + namesOff: 'Anonyme', + namesLabel: 'Demander les noms', + namesHint: 'Tout le monde voit qui est dispo et quand. Désactive pour des réponses anonymes.', + maxLabel: 'Personnes qui peuvent répondre', + maxHint: 'De {min} à {max}, toi compris.', + fewer: 'Moins de personnes', + morePeople: 'Plus de personnes', + expiryLabel: 'Le sondage reste ouvert', + expiry: { + day: '24 heures', + week: '7 jours', + }, + submit: 'Créer le sondage', + footnote: 'Quand le sondage se termine, il est supprimé avec toutes les réponses.', + }, + page: { + closes: "Ouvert jusqu'au {date}.", + resultsUntil: "Les résultats restent visibles jusqu'au {date}.", + timezoneNote: 'Les horaires sont dans ton fuseau, {zone}.', + answered_one: '{count} sur {max} a répondu', + answered_other: '{count} sur {max} ont répondu', + anonymousNote: 'Les réponses sont anonymes.', + readyTitle: 'Ton sondage est prêt', + readyBody: + 'Envoie le lien à tous ceux à qui tu veux demander. Ensuite, ajoute tes propres horaires en dessous.', + linkLabel: 'Lien du sondage', + copy: 'Copier le lien', + copied: 'Lien du sondage copié', + share: 'Partager', + shareTitle: 'Tu es dispo quand pour {title} ?', + shareText: 'Ajoute tes horaires pour {title}. Pas besoin de compte : {url}', + paintTitle: 'Tu es dispo quand ?', + nameLabel: 'Ton nom', + nameHint: 'Tout le monde dans ce sondage le voit.', + needName: "Ajoute d'abord ton nom.", + needTimes: "Peins au moins un créneau d'abord.", + submit: 'Envoyer mes horaires', + update: 'Mettre à jour mes horaires', + cancel: 'Garder mes horaires', + sentStamp: 'Reçu', + sentTitle: 'Merci, {name}. Tu es sur la liste.', + sentTitleAnon: 'Merci. Tu es sur la liste en tant que {name}.', + sentBody: + "Rouvre ce lien sur cet appareil pour les changer, quand tu veux jusqu'à la fin du sondage.", + edit: 'Changer mes horaires', + gridLabel: 'Tes horaires pour {title}', + everyoneTitle: 'Tout le monde', + heatGridLabel: 'Les dispos de tout le monde pour {title}', + noAnswersTitle: "Personne n'a encore répondu", + noAnswersBody: + 'Fais tourner le lien. Les horaires se réchauffent ici à mesure que les gens les ajoutent.', + fullTitle: 'Ce sondage est complet', + fullBody: + "Les {max} places sont prises, il n'accepte donc plus de nouvelles réponses. Voici les dispos de tout le monde.", + closedTitle: 'Ce sondage est fermé', + closedBody: "La personne qui l'a créé l'a fermé, ces horaires sont donc définitifs.", + closedByYou: 'Tu as fermé ce sondage, ces horaires sont donc définitifs.', + unsaved: "Tes horaires n'ont pas été enregistrés.", + yourPoll: 'Ton sondage', + close: 'Fermer le sondage', + closeTitle: 'Fermer ce sondage ?', + closeConfirm: + "Plus personne ne pourra ajouter ou changer des horaires. Tous ceux qui ont le lien voient encore les résultats jusqu'à la fin du sondage.", + closed: 'Sondage fermé', + delete: 'Supprimer le sondage', + deleteTitle: 'Supprimer ce sondage ?', + deleteConfirm: + 'Le sondage et toutes les réponses disparaissent pour tout le monde, tout de suite. Impossible de revenir en arrière.', + deleted: 'Sondage supprimé', + pitchTitle: 'On en fait une sortie ?', + pitchBody: + "Avec un compte gratuit, Potluck garde tes sorties, envoie des rappels, cale l'horaire et partage l'addition ensuite.", + loadFailedTitle: 'Plus de réseau', + loadFailed: "Impossible d'ouvrir ce sondage. Vérifie ta connexion et réessaie.", + }, + ended: { + title: 'Ce sondage est terminé', + body: "Les sondages ne restent ouverts qu'un temps, et celui-ci est fini. Ses réponses ont disparu aussi.", + notFoundTitle: 'Pas de sondage ici', + notFound: "Ce lien ne mène à aucun sondage. Vérifie qu'il a été copié en entier.", + newPoll: 'Créer un nouveau sondage', + }, errors: { quick_poll_not_found: 'Ce lien de sondage ne mène nulle part.', quick_poll_expired: 'Ce sondage est terminé.', diff --git a/packages/i18n/src/fr/shell.ts b/packages/i18n/src/fr/shell.ts index 0a6ee691..17ac0cef 100644 --- a/packages/i18n/src/fr/shell.ts +++ b/packages/i18n/src/fr/shell.ts @@ -12,6 +12,10 @@ export const app = { body: 'Potluck tient les comptes de ta bande et trouve la soirée où tout le monde est vraiment dispo. Gratuit, open source, et pas de pub à table.', cta: 'Dresser la table', secondary: "J'ai déjà un compte", + quickPoll: { + title: 'Trouve un créneau, sans inscription', + body: 'Lance un sondage rapide et vois quand tout le monde est dispo.', + }, demo: { label: "Une courte démo : l'addition d'un dîner se partage en quatre, puis les amis indiquent quand ils sont libres et une soirée est fixée.", @@ -44,6 +48,7 @@ export const app = { night: { title: 'La soirée', body: 'Chacun fait glisser son doigt sur les heures où il est libre. La grille se réchauffe là où ça colle et le meilleur créneau remonte en haut.', + poll: 'Ou commence par un sondage rapide, sans compte', }, square: { title: 'Les comptes soldés', diff --git a/packages/i18n/src/pt/quick-polls.ts b/packages/i18n/src/pt/quick-polls.ts index ab6562f4..e517b539 100644 --- a/packages/i18n/src/pt/quick-polls.ts +++ b/packages/i18n/src/pt/quick-polls.ts @@ -2,6 +2,99 @@ import type { Translation } from '../locales' import type * as en from '../en/quick-polls' export const quickPolls = { + defaultTitle: 'Encontrar um horário', + anonymous: 'Anônimo {seat}', + create: { + title: 'Encontrar um horário', + intro: + 'Crie uma enquete, mande o link e veja quando todo mundo pode. Ninguém precisa de conta.', + titleLabel: 'É para quê?', + when: 'Quando poderia ser?', + more: 'Mais opções', + summary: '{names}, até {max} pessoas, aberta por {expiry}', + namesOn: 'Com nomes', + namesOff: 'Anônima', + namesLabel: 'Pedir nomes', + namesHint: 'Todos veem quem pode e quando. Desative para respostas anônimas.', + maxLabel: 'Pessoas que podem responder', + maxHint: 'De {min} a {max}, contando com você.', + fewer: 'Menos pessoas', + morePeople: 'Mais pessoas', + expiryLabel: 'A enquete fica aberta por', + expiry: { + day: '24 horas', + week: '7 dias', + }, + submit: 'Criar enquete', + footnote: 'Quando a enquete termina, ela é apagada com todas as respostas.', + }, + page: { + closes: 'Aberta até {date}.', + resultsUntil: 'Os resultados ficam visíveis até {date}.', + timezoneNote: 'Os horários estão no seu fuso, {zone}.', + answered_one: '{count} de {max} respondeu', + answered_other: '{count} de {max} responderam', + anonymousNote: 'As respostas são anônimas.', + readyTitle: 'Sua enquete está pronta', + readyBody: + 'Mande o link para todo mundo que você quer consultar. Depois adicione seus próprios horários abaixo.', + linkLabel: 'Link da enquete', + copy: 'Copiar link', + copied: 'Link da enquete copiado', + share: 'Compartilhar', + shareTitle: 'Quando você pode para {title}?', + shareText: 'Adicione seus horários para {title}. Não precisa de conta: {url}', + paintTitle: 'Quando você pode?', + nameLabel: 'Seu nome', + nameHint: 'Todos nesta enquete veem.', + needName: 'Primeiro adicione seu nome.', + needTimes: 'Pinte pelo menos um horário primeiro.', + submit: 'Enviar meus horários', + update: 'Atualizar meus horários', + cancel: 'Manter meus horários', + sentStamp: 'Recebido', + sentTitle: 'Valeu, {name}. Você está na lista.', + sentTitleAnon: 'Valeu. Você está na lista como {name}.', + sentBody: + 'Abra este link de novo neste aparelho para mudar, quando quiser até a enquete terminar.', + edit: 'Mudar meus horários', + gridLabel: 'Seus horários para {title}', + everyoneTitle: 'Todos', + heatGridLabel: 'Os horários de todos para {title}', + noAnswersTitle: 'Ninguém respondeu ainda', + noAnswersBody: + 'Espalhe o link. Os horários esquentam aqui conforme as pessoas adicionam os seus.', + fullTitle: 'Esta enquete está lotada', + fullBody: + 'Todas as {max} vagas estão ocupadas, então ela não aceita novas respostas. Veja como está para todos.', + closedTitle: 'Esta enquete está fechada', + closedBody: 'Quem criou fechou a enquete, então estes horários são finais.', + closedByYou: 'Você fechou esta enquete, então estes horários são finais.', + unsaved: 'Seus horários não foram salvos.', + yourPoll: 'Sua enquete', + close: 'Fechar enquete', + closeTitle: 'Fechar esta enquete?', + closeConfirm: + 'Depois disso, ninguém consegue adicionar ou mudar horários. Quem tem o link continua vendo os resultados até a enquete terminar.', + closed: 'Enquete fechada', + delete: 'Excluir enquete', + deleteTitle: 'Excluir esta enquete?', + deleteConfirm: + 'A enquete e todas as respostas somem para todo mundo, agora mesmo. Não dá para desfazer.', + deleted: 'Enquete excluída', + pitchTitle: 'Vai virar um plano?', + pitchBody: + 'Com uma conta grátis, o Potluck guarda seus planos, manda lembretes, confirma o horário e depois divide a conta.', + loadFailedTitle: 'Sem sinal', + loadFailed: 'Não conseguimos abrir esta enquete. Confira sua conexão e tente de novo.', + }, + ended: { + title: 'Esta enquete terminou', + body: 'Enquetes só ficam abertas por um tempo, e esta acabou. As respostas também foram apagadas.', + notFoundTitle: 'Nenhuma enquete aqui', + notFound: 'Este link não leva a nenhuma enquete. Confira se foi copiado inteiro.', + newPoll: 'Criar uma nova enquete', + }, errors: { quick_poll_not_found: 'Esse link de enquete não leva a lugar nenhum.', quick_poll_expired: 'Esta enquete terminou.', diff --git a/packages/i18n/src/pt/shell.ts b/packages/i18n/src/pt/shell.ts index 6c57e958..c513f052 100644 --- a/packages/i18n/src/pt/shell.ts +++ b/packages/i18n/src/pt/shell.ts @@ -12,6 +12,10 @@ export const app = { body: 'O Potluck mantém a conta da sua turma em dia e encontra a noite em que todo mundo pode de verdade. Gratuito, de código aberto e sem anúncios à mesa.', cta: 'Abrir uma mesa', secondary: 'Já tenho uma conta', + quickPoll: { + title: 'Ache um horário, sem cadastro', + body: 'Mande uma enquete rápida e veja quando todo mundo está livre.', + }, demo: { label: 'Uma demonstração rápida: a conta de um jantar é dividida por quatro, depois os amigos marcam quando estão livres e uma noite fica confirmada.', @@ -44,6 +48,7 @@ export const app = { night: { title: 'A noite', body: 'Cada um arrasta pelas horas em que está livre. A grade esquenta onde dá certo e o melhor horário sobe para o topo.', + poll: 'Ou comece com uma enquete rápida, sem precisar de conta', }, square: { title: 'As contas acertadas', From 4caf079c820369263ba032c3ef402f1bd201d996 Mon Sep 17 00:00:00 2001 From: Musa Kaleem <131704022+Musa-Kal@users.noreply.github.com> Date: Sun, 22 Nov 2026 19:08:05 -0500 Subject: [PATCH 09/21] feat(web): quick poll create page and poll page /poll makes a poll from sensible defaults with names, the seat cap and expiry folded under More options. /p/$code renders from the poll status plus a viewing or editing mode: paint and send, everyone's heatmap and ranked best times (core rankSlots), share and copy, a sent card to edit from, full and closed notices, close and delete for the creator, dead ends for expired and unknown codes, and a sign up pitch for visitors without an account. Results refresh every 15 seconds while the tab is visible and on focus. Both routes work signed out; /p/* is kept out of search engines with a robots meta tag and an X-Robots-Tag header. Co-authored-by: Ferrin <177692050+Ferrin-Y@users.noreply.github.com> Co-authored-by: noorelmosrati <182049385+noorelmosrati@users.noreply.github.com> --- apps/web/public/_headers | 3 + .../quick-polls/create-poll-page.test.tsx | 145 +++++ .../features/quick-polls/create-poll-page.tsx | 267 +++++++++ .../src/features/quick-polls/poll-memory.ts | 10 + .../features/quick-polls/poll-page.test.tsx | 388 ++++++++++++ .../src/features/quick-polls/poll-page.tsx | 567 ++++++++++++++++++ apps/web/src/features/quick-polls/results.ts | 72 +++ .../src/features/quick-polls/share-poll.tsx | 74 +++ .../shell/use-auth-redirects.test.tsx | 23 +- .../src/features/shell/use-auth-redirects.ts | 2 + apps/web/src/lib/app-url.ts | 5 + apps/web/src/routeTree.gen.ts | 42 ++ apps/web/src/routes/p.$code.tsx | 12 + apps/web/src/routes/poll.tsx | 7 + 14 files changed, 1608 insertions(+), 9 deletions(-) create mode 100644 apps/web/public/_headers create mode 100644 apps/web/src/features/quick-polls/create-poll-page.test.tsx create mode 100644 apps/web/src/features/quick-polls/create-poll-page.tsx create mode 100644 apps/web/src/features/quick-polls/poll-memory.ts create mode 100644 apps/web/src/features/quick-polls/poll-page.test.tsx create mode 100644 apps/web/src/features/quick-polls/poll-page.tsx create mode 100644 apps/web/src/features/quick-polls/results.ts create mode 100644 apps/web/src/features/quick-polls/share-poll.tsx create mode 100644 apps/web/src/routes/p.$code.tsx create mode 100644 apps/web/src/routes/poll.tsx diff --git a/apps/web/public/_headers b/apps/web/public/_headers new file mode 100644 index 00000000..3af429a0 --- /dev/null +++ b/apps/web/public/_headers @@ -0,0 +1,3 @@ +# Quick polls are reached by a private link: keep them out of search results. +/p/* + X-Robots-Tag: noindex diff --git a/apps/web/src/features/quick-polls/create-poll-page.test.tsx b/apps/web/src/features/quick-polls/create-poll-page.test.tsx new file mode 100644 index 00000000..e4105915 --- /dev/null +++ b/apps/web/src/features/quick-polls/create-poll-page.test.tsx @@ -0,0 +1,145 @@ +import { QUICK_POLL_MAX_PEOPLE, QUICK_POLL_MIN_PEOPLE } from '@potluck/core' +import { t } from '@potluck/i18n' +import { fireEvent, screen, waitFor } from '@testing-library/react' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { db, resetDb } from '@/test/supabase' +import { renderWithProviders } from '@/test/render' +import { CreatePollPage } from './create-poll-page' +import { pollMemory } from './poll-memory' + +vi.mock('@/lib/supabase', () => import('@/test/supabase')) + +const created = { + data: [{ code: 'newpoll', creator_token: 'tok-creator', expires_at: '2026-06-08T09:00:00Z' }], +} + +async function renderPage() { + const view = renderWithProviders(, { path: '/poll' }) + await screen.findByRole('heading', { level: 1, name: t('quickPolls.create.title') }) + return view +} + +const submit = () => + fireEvent.click(screen.getByRole('button', { name: t('quickPolls.create.submit') })) + +describe('CreatePollPage', () => { + beforeEach(() => { + resetDb() + window.localStorage.clear() + vi.useFakeTimers({ toFake: ['Date'] }) + vi.setSystemTime(new Date('2026-06-01T09:00:00Z')) + }) + afterEach(() => { + vi.useRealTimers() + }) + + it('makes a poll from the defaults, keeps the creator token and opens it', async () => { + db().respond('rpc:create_quick_poll', created) + const { router } = await renderPage() + + // The rarer settings wait folded away, summed up in one line. + expect( + screen.getByText( + t('quickPolls.create.summary', { + names: t('quickPolls.create.namesOn'), + max: 10, + expiry: t('quickPolls.create.expiry.week'), + }), + ), + ).toBeInTheDocument() + submit() + + await waitFor(() => expect(router.state.location.pathname).toBe('/p/newpoll')) + const [args] = db().rpcArgs('create_quick_poll') as [{ payload: Record }] + expect(args.payload).toEqual({ + title: null, + timezone: expect.any(String), + window_start: '2026-06-02', + window_end: '2026-06-08', + day_start_minute: 600, + day_end_minute: 1320, + duration_minutes: 60, + slot_minutes: 30, + ttl: '7d', + names_required: true, + max_people: 10, + }) + expect(pollMemory.read('newpoll')).toEqual({ token: 'tok-creator', name: '' }) + }) + + it('sends a title, anonymous answers, a smaller cap and a 24 hour expiry', async () => { + db().respond('rpc:create_quick_poll', created) + await renderPage() + + fireEvent.change(screen.getByLabelText(t('quickPolls.create.titleLabel')), { + target: { value: ' Team lunch ' }, + }) + fireEvent.click(screen.getByText(t('quickPolls.create.more'))) + fireEvent.click(screen.getByRole('switch', { name: t('quickPolls.create.namesLabel') })) + const fewer = screen.getByRole('button', { name: t('quickPolls.create.fewer') }) + for (let i = 0; i < 20; i++) fireEvent.click(fewer) + // The cap stops at the smallest poll. + expect(fewer).toBeDisabled() + fireEvent.click(screen.getByRole('radio', { name: t('quickPolls.create.expiry.day') })) + expect( + screen.getByText( + t('quickPolls.create.summary', { + names: t('quickPolls.create.namesOff'), + max: QUICK_POLL_MIN_PEOPLE, + expiry: t('quickPolls.create.expiry.day'), + }), + ), + ).toBeInTheDocument() + submit() + + await waitFor(() => + expect(db().rpcArgs('create_quick_poll')[0]).toMatchObject({ + payload: { + title: 'Team lunch', + names_required: false, + max_people: QUICK_POLL_MIN_PEOPLE, + ttl: '24h', + }, + }), + ) + }) + + it('caps the people at the largest poll', async () => { + await renderPage() + fireEvent.click(screen.getByText(t('quickPolls.create.more'))) + const more = screen.getByRole('button', { name: t('quickPolls.create.morePeople') }) + for (let i = 0; i < 20; i++) fireEvent.click(more) + expect(more).toBeDisabled() + expect(screen.getByText(String(QUICK_POLL_MAX_PEOPLE))).toBeInTheDocument() + }) + + it('keeps the window to two weeks and moves the last day along with the first', async () => { + await renderPage() + const first = screen.getByLabelText(t('events.create.windowFrom')) + const last = screen.getByLabelText(t('events.create.windowTo')) + expect(last).toHaveAttribute('max', '2026-06-15') + fireEvent.change(first, { target: { value: '2026-06-20' } }) + expect(last).toHaveValue('2026-06-20') + expect(last).toHaveAttribute('max', '2026-07-03') + }) + + it('stops a window longer than two weeks before sending it', async () => { + await renderPage() + fireEvent.change(screen.getByLabelText(t('events.create.windowTo')), { + target: { value: '2026-06-30' }, + }) + submit() + expect(await screen.findByText(t('quickPolls.errors.invalid_quick_poll_window'))).toBeVisible() + expect(db().rpcArgs('create_quick_poll')).toEqual([]) + }) + + it('says when someone has made too many polls', async () => { + db().respond('rpc:create_quick_poll', { error: { message: 'quick_poll_rate_limited' } }) + const { router } = await renderPage() + submit() + expect(await screen.findByRole('alert')).toHaveTextContent( + t('quickPolls.errors.quick_poll_rate_limited'), + ) + expect(router.state.location.pathname).toBe('/poll') + }) +}) diff --git a/apps/web/src/features/quick-polls/create-poll-page.tsx b/apps/web/src/features/quick-polls/create-poll-page.tsx new file mode 100644 index 00000000..b8bf5ad2 --- /dev/null +++ b/apps/web/src/features/quick-polls/create-poll-page.tsx @@ -0,0 +1,267 @@ +import { createQuickPoll } from '@potluck/api' +import { + dayKey, + QUICK_POLL_DEFAULT_PEOPLE, + QUICK_POLL_MAX_DAYS, + QUICK_POLL_MAX_PEOPLE, + QUICK_POLL_MIN_PEOPLE, + QUICK_POLL_TITLE_MAX, + quickPollWindowFits, + type QuickPollTtl, +} from '@potluck/core' +import { t } from '@potluck/i18n' +import { Button, Card, Field, Input, SegmentedControl, Select, Switch } from '@potluck/ui' +import { useMutation } from '@tanstack/react-query' +import { useNavigate } from '@tanstack/react-router' +import { ChevronDown, Minus, Plus } from 'lucide-react' +import { useMemo, useState, type FormEvent } from 'react' +import { + addDays, + durationOptions, + type PollWindow, + type WindowField, +} from '@/features/plans/window' +import { WindowFields } from '@/features/plans/window-fields' +import { Notice, PublicFrame } from '@/features/shell/public-page' +import { errorMessage } from '@/lib/errors' +import { detectTimezone } from '@/lib/locale' +import { supabase } from '@/lib/supabase' +import { pollMemory } from './poll-memory' + +/** Everything past the title, the days and the length: sensible defaults behind "More options". */ +interface PollSettings { + ttl: QuickPollTtl + namesRequired: boolean + maxPeople: number +} + +const DEFAULT_SETTINGS: PollSettings = { + ttl: '7d', + namesRequired: true, + maxPeople: QUICK_POLL_DEFAULT_PEOPLE, +} + +const TTL_LABEL = { + '24h': () => t('quickPolls.create.expiry.day'), + '7d': () => t('quickPolls.create.expiry.week'), +} satisfies Record string> + +/** One slot size for every quick poll: fine enough for a call, small enough to paint fast. */ +const SLOT_MINUTES = 30 + +/** + * `/poll`: anyone, signed in or not, makes an availability poll. Every field starts on a sensible + * value, so the first poll is one tap away; the rarer settings wait behind "More options". On + * success the browser keeps the creator token and the poll page takes over. + */ +export function CreatePollPage() { + const navigate = useNavigate() + const timeZone = useMemo(() => detectTimezone(), []) + const [today] = useState(() => dayKey(Date.now(), timeZone)) + const [title, setTitle] = useState('') + const [pollWindow, setPollWindow] = useState(() => ({ + windowStart: addDays(today, 1), + windowEnd: addDays(today, 7), + dayStartMinute: 10 * 60, + dayEndMinute: 22 * 60, + })) + const [duration, setDuration] = useState(60) + const [settings, setSettings] = useState(DEFAULT_SETTINGS) + const [errors, setErrors] = useState>>({}) + + const create = useMutation({ + mutationFn: () => + createQuickPoll(supabase, { + title: title.trim() || null, + timeZone, + windowStart: pollWindow.windowStart, + windowEnd: pollWindow.windowEnd, + dayStartMinute: pollWindow.dayStartMinute, + dayEndMinute: pollWindow.dayEndMinute, + durationMinutes: duration, + slotMinutes: SLOT_MINUTES, + ttl: settings.ttl, + namesRequired: settings.namesRequired, + maxPeople: settings.maxPeople, + }), + onSuccess: async (created) => { + pollMemory.write(created.code, { token: created.creatorToken, name: '' }) + await navigate({ to: '/p/$code', params: { code: created.code } }) + }, + }) + + const submit = (e: FormEvent) => { + e.preventDefault() + const next: Partial> = {} + if (!quickPollWindowFits(pollWindow.windowStart, pollWindow.windowEnd)) { + next.window_end = t('quickPolls.errors.invalid_quick_poll_window') + } + if (pollWindow.dayEndMinute - pollWindow.dayStartMinute < SLOT_MINUTES) { + next.day_end_minute = t('quickPolls.errors.invalid_quick_poll_hours') + } + setErrors(next) + const first = Object.keys(next)[0] + if (first) { + document.getElementById(`poll-${first}`)?.focus() + return + } + create.mutate() + } + + const summary = t('quickPolls.create.summary', { + names: settings.namesRequired + ? t('quickPolls.create.namesOn') + : t('quickPolls.create.namesOff'), + max: settings.maxPeople, + expiry: TTL_LABEL[settings.ttl](), + }) + + return ( + +
+
+

+ {t('quickPolls.create.title')} +

+

+ {t('quickPolls.create.intro')} +

+
+ +
+ + + setTitle(e.target.value)} + placeholder={t('quickPolls.defaultTitle')} + maxLength={QUICK_POLL_TITLE_MAX} + enterKeyHint="next" + /> + +

+ {t('quickPolls.create.when')} +

+ + + { + setName(e.target.value) + setNameError(null) + onDirty() + }} + /> + + )} +
+
+ {formError && ( +

+ {formError} +

+ )} +
+ {onCancel && ( + + )} + +
+
+
+ ) +} + +/** Close and delete, for whoever made the poll. Both ask first. */ +function CreatorControls({ + code, + token, + status, +}: { + code: string + token: string + status: LivePoll['status'] +}) { + const queryClient = useQueryClient() + const navigate = useNavigate() + const [asking, setAsking] = useState<'close' | 'delete' | null>(null) + + const close = async () => { + try { + await closeQuickPoll(supabase, { code, creatorToken: token }) + } catch (error) { + toast.error(errorMessage(error, 'quickPolls.errors')) + throw error + } + toast.success(t('quickPolls.page.closed')) + await queryClient.invalidateQueries({ queryKey: quickPollKeys.preview(code) }) + } + + const remove = async () => { + try { + await deleteQuickPoll(supabase, { code, creatorToken: token }) + } catch (error) { + toast.error(errorMessage(error, 'quickPolls.errors')) + throw error + } + pollMemory.forget(code) + toast.success(t('quickPolls.page.deleted')) + await navigate({ to: '/poll' }) + queryClient.removeQueries({ queryKey: quickPollKeys.preview(code) }) + } + + return ( +
+

{t('quickPolls.page.yourPoll')}

+
+ {status !== 'closed' && ( + + )} + +
+ !open && setAsking(null)} + title={t('quickPolls.page.closeTitle')} + description={t('quickPolls.page.closeConfirm')} + confirmLabel={t('quickPolls.page.close')} + cancelLabel={t('common.cancel')} + closeLabel={t('common.close')} + onConfirm={close} + /> + !open && setAsking(null)} + title={t('quickPolls.page.deleteTitle')} + description={t('quickPolls.page.deleteConfirm')} + confirmLabel={t('quickPolls.page.delete')} + cancelLabel={t('common.cancel')} + closeLabel={t('common.close')} + tone="danger" + onConfirm={remove} + /> +
+ ) +} diff --git a/apps/web/src/features/quick-polls/results.ts b/apps/web/src/features/quick-polls/results.ts new file mode 100644 index 00000000..9005ee28 --- /dev/null +++ b/apps/web/src/features/quick-polls/results.ts @@ -0,0 +1,72 @@ +import type { PlanBestSlot, PlanMember, QuickPollAnswer, QuickPollInfo } from '@potluck/api' +import { rankSlots, type SlotGrid } from '@potluck/core' +import { t } from '@potluck/i18n' +import { slotKey, type GridEvent } from '@/features/availability/grid' +import type { HeatRow } from '@/features/availability/availability-heatmap' + +/** + * The heatmap and best times work on people with ids; a poll answer's id is its seat, padded so + * ids sort in seat order (best times lists who is missing in id order). + */ +const seatId = (seat: number) => `seat-${String(seat).padStart(2, '0')}` + +/** A poll's grid in the shape the painter and heatmap read. */ +export function gridEvent(grid: SlotGrid): GridEvent { + return { + window_start: grid.windowStart, + window_end: grid.windowEnd, + day_start_minute: grid.dayStartMinute, + day_end_minute: grid.dayEndMinute, + slot_minutes: grid.slotMinutes, + timezone: grid.timeZone, + } +} + +/** What everyone answered, in the shapes the heatmap and best times take. */ +export interface PollResults { + people: PlanMember[] + rows: HeatRow[] + best: PlanBestSlot[] + /** The visitor's own answer's id, for the dots on their cells. */ + mineId: string | undefined +} + +/** An answer's name: what they typed, or "Anonymous 3" when the poll does not ask. */ +export function answerName(answer: Pick): string { + return answer.name ?? t('quickPolls.anonymous', { seat: answer.seat }) +} + +/** Ranks the answers with core `rankSlots`: anyone free for the whole length counts. */ +export function pollResults( + poll: Pick, + answers: readonly QuickPollAnswer[], +): PollResults { + const people = answers.map((a): PlanMember => ({ + userId: seatId(a.seat), + role: 'member', + displayName: answerName(a), + avatarPath: null, + deleted: false, + })) + const rows = answers.flatMap((a) => + a.slots.map((s) => ({ userId: seatId(a.seat), slot: slotKey(s.slot_start), level: s.level })), + ) + const best = rankSlots( + rows.map((r) => ({ userId: r.userId, slotStart: r.slot, level: r.level })), + { + durationMinutes: poll.durationMinutes, + slotMinutes: poll.grid.slotMinutes, + minAttendees: 1, + members: people.map((p) => p.userId), + }, + ).map((slot) => ({ + starts_at: slot.startsAt, + ends_at: slot.endsAt, + yes_count: slot.yesCount, + maybe_count: slot.maybeCount, + score: slot.score, + missing: slot.missing, + })) + const mine = answers.find((a) => a.mine) + return { people, rows, best, mineId: mine ? seatId(mine.seat) : undefined } +} diff --git a/apps/web/src/features/quick-polls/share-poll.tsx b/apps/web/src/features/quick-polls/share-poll.tsx new file mode 100644 index 00000000..383dfbfa --- /dev/null +++ b/apps/web/src/features/quick-polls/share-poll.tsx @@ -0,0 +1,74 @@ +import { t } from '@potluck/i18n' +import { Button, Card, toast } from '@potluck/ui' +import { Copy, Share2 } from 'lucide-react' +import { copyText, shareLink } from '@/features/invites/share' +import { quickPollUrl } from '@/lib/app-url' + +/** The phone's share sheet is worth a button of its own; elsewhere Copy link does the job. */ +const canShare = () => typeof navigator !== 'undefined' && typeof navigator.share === 'function' + +/** + * The poll's link with Copy and, where there is one, the share sheet. `prominent` is the + * creator's first look at a new poll: a saffron card that says the next step is sending it. + */ +export function SharePoll({ + code, + title, + prominent = false, +}: { + code: string + title: string + prominent?: boolean +}) { + const url = quickPollUrl(code) + const copy = async () => { + if (await copyText(url)) toast.success(t('quickPolls.page.copied')) + } + const share = () => + shareLink( + { + title: t('quickPolls.page.shareTitle', { title }), + text: t('quickPolls.page.shareText', { title, url }), + url, + }, + t('quickPolls.page.copied'), + ) + const buttons = ( +
+ + {canShare() && ( + + )} +
+ ) + + if (!prominent) return buttons + + return ( + +
+

{t('quickPolls.page.readyTitle')}

+

{t('quickPolls.page.readyBody')}

+
+

+ {t('quickPolls.page.linkLabel')}: + {url} +

+ {buttons} +
+ ) +} diff --git a/apps/web/src/features/shell/use-auth-redirects.test.tsx b/apps/web/src/features/shell/use-auth-redirects.test.tsx index e3ae7b3f..e73854f7 100644 --- a/apps/web/src/features/shell/use-auth-redirects.test.tsx +++ b/apps/web/src/features/shell/use-auth-redirects.test.tsx @@ -44,15 +44,20 @@ describe('useAuthRedirects', () => { await waitFor(() => expect(router.state.location.pathname).toBe('/sign-in')) }) - it.each(['/', '/sign-up', '/join/hikecrew-demo', '/auth/callback', '/forgot-password'])( - 'stays on the public page %s after sign out', - async (path) => { - const { router } = await renderAt(path) - act(() => emitAuth('SIGNED_OUT')) - await act(async () => {}) - expect(router.state.location.pathname).toBe(path) - }, - ) + it.each([ + '/', + '/sign-up', + '/join/hikecrew-demo', + '/auth/callback', + '/forgot-password', + '/poll', + '/p/abc123', + ])('stays on the public page %s after sign out', async (path) => { + const { router } = await renderAt(path) + act(() => emitAuth('SIGNED_OUT')) + await act(async () => {}) + expect(router.state.location.pathname).toBe(path) + }) it('opens the reset form from a recovery link', async () => { const { router } = await renderAt('/home') diff --git a/apps/web/src/features/shell/use-auth-redirects.ts b/apps/web/src/features/shell/use-auth-redirects.ts index 729c3948..7d2b1756 100644 --- a/apps/web/src/features/shell/use-auth-redirects.ts +++ b/apps/web/src/features/shell/use-auth-redirects.ts @@ -21,6 +21,8 @@ export function useAuthRedirects() { path.startsWith('/sign-') || path.startsWith('/join/') || path.startsWith('/a/') || + path === '/poll' || + path.startsWith('/p/') || path.startsWith('/friend/') || path.startsWith('/auth/') || path === '/unsubscribe' || diff --git a/apps/web/src/lib/app-url.ts b/apps/web/src/lib/app-url.ts index c86de30a..45305580 100644 --- a/apps/web/src/lib/app-url.ts +++ b/apps/web/src/lib/app-url.ts @@ -14,6 +14,11 @@ export function guestUrl(code: string): string { return `${appOrigin()}/a/${encodeURIComponent(code)}` } +/** A quick poll (`/p/`), for anyone with or without an account. */ +export function quickPollUrl(code: string): string { + return `${appOrigin()}/p/${encodeURIComponent(code)}` +} + export function friendUrl(code: string): string { return `${appOrigin()}/friend/${encodeURIComponent(code)}` } diff --git a/apps/web/src/routeTree.gen.ts b/apps/web/src/routeTree.gen.ts index f06cffc3..233f4f22 100644 --- a/apps/web/src/routeTree.gen.ts +++ b/apps/web/src/routeTree.gen.ts @@ -12,6 +12,7 @@ import { Route as rootRouteImport } from './routes/__root' import { Route as IndexRouteImport } from './routes/index' import { Route as AppRouteImport } from './routes/_app' import { Route as ForgotPasswordRouteImport } from './routes/forgot-password' +import { Route as PollRouteImport } from './routes/poll' import { Route as ResetPasswordRouteImport } from './routes/reset-password' import { Route as SignInRouteImport } from './routes/sign-in' import { Route as SignUpRouteImport } from './routes/sign-up' @@ -28,6 +29,7 @@ import { Route as AuthCallbackRouteImport } from './routes/auth.callback' import { Route as DevKitRouteImport } from './routes/dev.kit' import { Route as FriendCodeRouteImport } from './routes/friend.$code' import { Route as JoinCodeRouteImport } from './routes/join.$code' +import { Route as PCodeRouteImport } from './routes/p.$code' import { Route as AppExpensesExpenseIdRouteImport } from './routes/_app/expenses/$expenseId' import { Route as AppFriendsIndexRouteImport } from './routes/_app/friends/index' import { Route as AppFriendsFriendIdRouteImport } from './routes/_app/friends/$friendId' @@ -67,6 +69,11 @@ const ForgotPasswordRoute = ForgotPasswordRouteImport.update({ path: '/forgot-password', getParentRoute: () => rootRouteImport, } as any) +const PollRoute = PollRouteImport.update({ + id: '/poll', + path: '/poll', + getParentRoute: () => rootRouteImport, +} as any) const ResetPasswordRoute = ResetPasswordRouteImport.update({ id: '/reset-password', path: '/reset-password', @@ -147,6 +154,11 @@ const JoinCodeRoute = JoinCodeRouteImport.update({ path: '/join/$code', getParentRoute: () => rootRouteImport, } as any) +const PCodeRoute = PCodeRouteImport.update({ + id: '/p/$code', + path: '/p/$code', + getParentRoute: () => rootRouteImport, +} as any) const AppExpensesExpenseIdRoute = AppExpensesExpenseIdRouteImport.update({ id: '/expenses/$expenseId', path: '/expenses/$expenseId', @@ -275,6 +287,7 @@ const AppPaymentsPaymentIdEditRoute = export interface FileRoutesByFullPath { '/': typeof IndexRoute '/forgot-password': typeof ForgotPasswordRoute + '/poll': typeof PollRoute '/reset-password': typeof ResetPasswordRoute '/sign-in': typeof SignInRoute '/sign-up': typeof SignUpRoute @@ -291,6 +304,7 @@ export interface FileRoutesByFullPath { '/dev/kit': typeof DevKitRoute '/friend/$code': typeof FriendCodeRoute '/join/$code': typeof JoinCodeRoute + '/p/$code': typeof PCodeRoute '/expenses/$expenseId': typeof AppExpensesExpenseIdRoute '/friends/$friendId': typeof AppFriendsFriendIdRoute '/groups/$groupId': typeof AppGroupsGroupIdRouteWithChildren @@ -319,6 +333,7 @@ export interface FileRoutesByFullPath { export interface FileRoutesByTo { '/': typeof IndexRoute '/forgot-password': typeof ForgotPasswordRoute + '/poll': typeof PollRoute '/reset-password': typeof ResetPasswordRoute '/sign-in': typeof SignInRoute '/sign-up': typeof SignUpRoute @@ -335,6 +350,7 @@ export interface FileRoutesByTo { '/dev/kit': typeof DevKitRoute '/friend/$code': typeof FriendCodeRoute '/join/$code': typeof JoinCodeRoute + '/p/$code': typeof PCodeRoute '/expenses/$expenseId': typeof AppExpensesExpenseIdRoute '/friends/$friendId': typeof AppFriendsFriendIdRoute '/new/expense': typeof AppNewExpenseRoute @@ -364,6 +380,7 @@ export interface FileRoutesById { '/': typeof IndexRoute '/_app': typeof AppRouteWithChildren '/forgot-password': typeof ForgotPasswordRoute + '/poll': typeof PollRoute '/reset-password': typeof ResetPasswordRoute '/sign-in': typeof SignInRoute '/sign-up': typeof SignUpRoute @@ -380,6 +397,7 @@ export interface FileRoutesById { '/dev/kit': typeof DevKitRoute '/friend/$code': typeof FriendCodeRoute '/join/$code': typeof JoinCodeRoute + '/p/$code': typeof PCodeRoute '/_app/expenses/$expenseId': typeof AppExpensesExpenseIdRoute '/_app/friends/$friendId': typeof AppFriendsFriendIdRoute '/_app/groups/$groupId': typeof AppGroupsGroupIdRouteWithChildren @@ -410,6 +428,7 @@ export interface FileRouteTypes { fullPaths: | '/' | '/forgot-password' + | '/poll' | '/reset-password' | '/sign-in' | '/sign-up' @@ -426,6 +445,7 @@ export interface FileRouteTypes { | '/dev/kit' | '/friend/$code' | '/join/$code' + | '/p/$code' | '/expenses/$expenseId' | '/friends/$friendId' | '/groups/$groupId' @@ -454,6 +474,7 @@ export interface FileRouteTypes { to: | '/' | '/forgot-password' + | '/poll' | '/reset-password' | '/sign-in' | '/sign-up' @@ -470,6 +491,7 @@ export interface FileRouteTypes { | '/dev/kit' | '/friend/$code' | '/join/$code' + | '/p/$code' | '/expenses/$expenseId' | '/friends/$friendId' | '/new/expense' @@ -498,6 +520,7 @@ export interface FileRouteTypes { | '/' | '/_app' | '/forgot-password' + | '/poll' | '/reset-password' | '/sign-in' | '/sign-up' @@ -514,6 +537,7 @@ export interface FileRouteTypes { | '/dev/kit' | '/friend/$code' | '/join/$code' + | '/p/$code' | '/_app/expenses/$expenseId' | '/_app/friends/$friendId' | '/_app/groups/$groupId' @@ -544,6 +568,7 @@ export interface RootRouteChildren { IndexRoute: typeof IndexRoute AppRoute: typeof AppRouteWithChildren ForgotPasswordRoute: typeof ForgotPasswordRoute + PollRoute: typeof PollRoute ResetPasswordRoute: typeof ResetPasswordRoute SignInRoute: typeof SignInRoute SignUpRoute: typeof SignUpRoute @@ -555,6 +580,7 @@ export interface RootRouteChildren { DevKitRoute: typeof DevKitRoute FriendCodeRoute: typeof FriendCodeRoute JoinCodeRoute: typeof JoinCodeRoute + PCodeRoute: typeof PCodeRoute } declare module '@tanstack/react-router' { @@ -580,6 +606,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ForgotPasswordRouteImport parentRoute: typeof rootRouteImport } + '/poll': { + id: '/poll' + path: '/poll' + fullPath: '/poll' + preLoaderRoute: typeof PollRouteImport + parentRoute: typeof rootRouteImport + } '/reset-password': { id: '/reset-password' path: '/reset-password' @@ -692,6 +725,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof JoinCodeRouteImport parentRoute: typeof rootRouteImport } + '/p/$code': { + id: '/p/$code' + path: '/p/$code' + fullPath: '/p/$code' + preLoaderRoute: typeof PCodeRouteImport + parentRoute: typeof rootRouteImport + } '/_app/expenses/$expenseId': { id: '/_app/expenses/$expenseId' path: '/expenses/$expenseId' @@ -942,6 +982,7 @@ const rootRouteChildren: RootRouteChildren = { IndexRoute: IndexRoute, AppRoute: AppRouteWithChildren, ForgotPasswordRoute: ForgotPasswordRoute, + PollRoute: PollRoute, ResetPasswordRoute: ResetPasswordRoute, SignInRoute: SignInRoute, SignUpRoute: SignUpRoute, @@ -953,6 +994,7 @@ const rootRouteChildren: RootRouteChildren = { DevKitRoute: DevKitRoute, FriendCodeRoute: FriendCodeRoute, JoinCodeRoute: JoinCodeRoute, + PCodeRoute: PCodeRoute, } export const routeTree = rootRouteImport ._addFileChildren(rootRouteChildren) diff --git a/apps/web/src/routes/p.$code.tsx b/apps/web/src/routes/p.$code.tsx new file mode 100644 index 00000000..3cb5502c --- /dev/null +++ b/apps/web/src/routes/p.$code.tsx @@ -0,0 +1,12 @@ +import { createFileRoute } from '@tanstack/react-router' +import { PollPage } from '@/features/quick-polls/poll-page' + +// Public: anyone with the link answers a quick poll. No session wait, nothing else to load. +export const Route = createFileRoute('/p/$code')({ + component: QuickPollRoute, +}) + +function QuickPollRoute() { + const { code } = Route.useParams() + return +} diff --git a/apps/web/src/routes/poll.tsx b/apps/web/src/routes/poll.tsx new file mode 100644 index 00000000..d705cb41 --- /dev/null +++ b/apps/web/src/routes/poll.tsx @@ -0,0 +1,7 @@ +import { createFileRoute } from '@tanstack/react-router' +import { CreatePollPage } from '@/features/quick-polls/create-poll-page' + +// Public: anyone makes a quick poll, signed in or not. +export const Route = createFileRoute('/poll')({ + component: CreatePollPage, +}) From e3a660e6bc9b595ba05f29d089798f83388b6edc Mon Sep 17 00:00:00 2001 From: Musa Kaleem <131704022+Musa-Kal@users.noreply.github.com> Date: Sun, 22 Nov 2026 19:08:05 -0500 Subject: [PATCH 10/21] feat(web): quick poll entry on the landing page A saffron date chip under the hero buttons, "Find a time, no sign-up", with the same tile as The night below it, and a quiet link under The night itself. Co-authored-by: Ferrin <177692050+Ferrin-Y@users.noreply.github.com> Co-authored-by: noorelmosrati <182049385+noorelmosrati@users.noreply.github.com> --- .../src/features/shell/landing-page.test.tsx | 7 ++++ apps/web/src/features/shell/landing-page.tsx | 42 ++++++++++++++++++- 2 files changed, 47 insertions(+), 2 deletions(-) diff --git a/apps/web/src/features/shell/landing-page.test.tsx b/apps/web/src/features/shell/landing-page.test.tsx index 630bfdbe..e31ba808 100644 --- a/apps/web/src/features/shell/landing-page.test.tsx +++ b/apps/web/src/features/shell/landing-page.test.tsx @@ -36,6 +36,13 @@ describe('LandingPage', () => { 'href', '/sign-in', ) + // A quick poll needs no account: one way in under the buttons, a quieter one by the planner. + expect( + screen.getByRole('link', { name: new RegExp(`^${t('app.landing.quickPoll.title')}`) }), + ).toHaveAttribute('href', '/poll') + expect( + screen.getByRole('link', { name: t('app.landing.features.night.poll') }), + ).toHaveAttribute('href', '/poll') expect( screen.getByRole('heading', { name: t('app.landing.features.tab.title') }), ).toBeInTheDocument() diff --git a/apps/web/src/features/shell/landing-page.tsx b/apps/web/src/features/shell/landing-page.tsx index f3d55ebc..e8cad2c0 100644 --- a/apps/web/src/features/shell/landing-page.tsx +++ b/apps/web/src/features/shell/landing-page.tsx @@ -1,7 +1,7 @@ import { t } from '@potluck/i18n' import { Button } from '@potluck/ui' import { Link } from '@tanstack/react-router' -import { ArrowRightLeft, CalendarHeart, Receipt } from 'lucide-react' +import { ArrowRightLeft, CalendarClock, CalendarHeart, Receipt } from 'lucide-react' import { lazy, Suspense, type ReactNode } from 'react' import { HELP_PAGES } from '@/features/help/topics' import { docsUrl } from '@/lib/docs' @@ -19,11 +19,13 @@ function Feature({ tile, title, body, + children, }: { icon: ReactNode tile: string title: string body: string + children?: ReactNode }) { return (
@@ -35,10 +37,38 @@ function Feature({

{title}

{body}

+ {children}
) } +/** + * The way in for someone who only needs a time: a quick poll, no account. It sits under the + * sign up buttons as a saffron date chip (saffron is plans and dates here), with the same tile + * as "The night" below, so it reads as part of the table rather than a banner on top of it. + */ +function QuickPollEntry() { + return ( + + + + + + + {t('app.landing.quickPoll.title')} + + {t('app.landing.quickPoll.body')} + + + ) +} + /** Public front door for signed-out visitors. Signed-in people are sent to /home by the route. */ export function LandingPage() { return ( @@ -79,6 +109,7 @@ export function LandingPage() { {t('app.landing.secondary')}
+
}> @@ -105,7 +136,14 @@ export function LandingPage() { tile="bg-saffron text-on-saffron" title={t('app.landing.features.night.title')} body={t('app.landing.features.night.body')} - /> + > + + {t('app.landing.features.night.poll')} + + } tile="bg-olive text-on-olive" From 92d157fc4f5b4829e238ff79696fa469f4556a78 Mon Sep 17 00:00:00 2001 From: Musa Kaleem <131704022+Musa-Kal@users.noreply.github.com> Date: Sun, 22 Nov 2026 19:08:05 -0500 Subject: [PATCH 11/21] test(e2e): quick poll journey, full poll and accessibility Make a poll from the landing page signed out, copy the link, two browsers answer, the creator sees the second answer without a reload, the friend edits, the creator closes it. A full poll turns a new person away. The create page and a poll page join the accessibility audit. Each test empties the local create log first, the rate limit itself is unchanged. Co-authored-by: Ferrin <177692050+Ferrin-Y@users.noreply.github.com> Co-authored-by: noorelmosrati <182049385+noorelmosrati@users.noreply.github.com> --- apps/web/e2e/a11y.spec.ts | 26 ++++++- apps/web/e2e/quick-polls.spec.ts | 126 +++++++++++++++++++++++++++++++ apps/web/e2e/support/api.ts | 76 ++++++++++++++++++- 3 files changed, 226 insertions(+), 2 deletions(-) create mode 100644 apps/web/e2e/quick-polls.spec.ts diff --git a/apps/web/e2e/a11y.spec.ts b/apps/web/e2e/a11y.spec.ts index 8cf31a74..4f8283d1 100644 --- a/apps/web/e2e/a11y.spec.ts +++ b/apps/web/e2e/a11y.spec.ts @@ -2,7 +2,14 @@ import AxeBuilder from '@axe-core/playwright' import { addPlaceholderMember, createPlanEvent, fetchMyFriendLink } from '@potluck/api' import { t } from '@potluck/i18n' import type { Page, TestInfo } from '@playwright/test' -import { addEqualExpense, groupWith, guestLinkFor, pollIn } from './support/api' +import { + addEqualExpense, + answerQuickPoll, + groupWith, + guestLinkFor, + pollIn, + quickPoll, +} from './support/api' import { expect, test, unique, type TestUser } from './support/fixtures' /** Serious and critical WCAG 2.1 A/AA violations fail the test; the rest are reported. */ @@ -233,6 +240,23 @@ test.describe('accessibility', () => { await audit(page, testInfo) }) + test('quick poll pages, signed out', async ({ openAs }, testInfo) => { + const page = await openAs(null) + await page.goto('/poll') + await expect( + page.getByRole('heading', { level: 1, name: t('quickPolls.create.title') }), + ).toBeVisible() + await audit(page, testInfo) + + const title = unique('Picnic') + const poll = await quickPoll({ title }) + await answerQuickPoll(poll.code, unique('Cy')) + await page.goto(`/p/${poll.code}`) + await expect(page.getByRole('heading', { level: 1, name: title })).toBeVisible() + await expect(page.getByRole('grid').first()).toBeVisible() + await audit(page, testInfo) + }) + test('me', async ({ newUser, openAs }, testInfo) => { const page = await openAs(await newUser()) await page.goto('/me') diff --git a/apps/web/e2e/quick-polls.spec.ts b/apps/web/e2e/quick-polls.spec.ts new file mode 100644 index 00000000..88ff6109 --- /dev/null +++ b/apps/web/e2e/quick-polls.spec.ts @@ -0,0 +1,126 @@ +import { t } from '@potluck/i18n' +import type { Page } from '@playwright/test' +import { answerQuickPoll, clearQuickPollCreates, quickPoll } from './support/api' +import { expect, test, unique } from './support/fixtures' + +/** Paints the first `count` free cells of the poll's grid with the keyboard. */ +async function paint(page: Page, title: string, count: number) { + const painter = page.getByRole('grid', { name: t('quickPolls.page.gridLabel', { title }) }) + await expect(painter).toBeVisible() + await painter + .getByRole('gridcell', { name: /not set/ }) + .first() + .focus() + await page.keyboard.press('Space') + for (let i = 1; i < count; i++) await page.keyboard.press('Shift+ArrowDown') + await expect(page.getByText(t('availability.mySlots', { count }))).toBeVisible() +} + +async function answer(page: Page, title: string, name: string, count: number) { + await page.getByLabel(t('quickPolls.page.nameLabel')).fill(name) + await paint(page, title, count) + await page.getByRole('button', { name: t('quickPolls.page.submit') }).click() + await expect(page.getByText(t('quickPolls.page.sentTitle', { name }))).toBeVisible() +} + +test('make a quick poll from the landing page, two people answer without accounts', async ({ + openAs, +}) => { + clearQuickPollCreates() + const title = unique('Board games') + const ava = unique('Ava') + const ben = unique('Ben') + + // Someone signed out finds the poll in the hero and makes one from the defaults. + const creator = await openAs(null) + // WebKit has no clipboard permissions to grant, so keep what the page copies instead. + await creator.addInitScript(() => { + const keep = (text: string) => { + ;(window as unknown as { copied?: string }).copied = text + return Promise.resolve() + } + Object.defineProperty(navigator, 'clipboard', { + value: { writeText: keep }, + configurable: true, + }) + }) + await creator.goto('/') + await creator + .getByRole('link', { name: new RegExp(`^${t('app.landing.quickPoll.title')}`) }) + .click() + await expect( + creator.getByRole('heading', { level: 1, name: t('quickPolls.create.title') }), + ).toBeVisible() + await creator.getByLabel(t('quickPolls.create.titleLabel')).fill(title) + await creator.getByRole('button', { name: t('quickPolls.create.submit') }).click() + + // The new poll puts sharing first. + await expect(creator.getByRole('heading', { level: 1, name: title })).toBeVisible() + await expect(creator.getByText(t('quickPolls.page.readyTitle'))).toBeVisible() + await creator.getByRole('button', { name: t('quickPolls.page.copy') }).click() + await expect(creator.getByText(t('quickPolls.page.copied')).first()).toBeVisible() + const url = await creator.evaluate(() => (window as unknown as { copied?: string }).copied ?? '') + expect(url).toMatch(/\/p\/[\w-]+$/) + expect(new URL(url).pathname).toBe(new URL(creator.url()).pathname) + + // The creator answers like anyone else. + await answer(creator, title, ava, 3) + await expect(creator.getByText(t('quickPolls.page.readyTitle'))).toHaveCount(0) + + // A second person, also without an account, opens the link and adds their times. + const friend = await openAs(null) + await friend.goto(new URL(url).pathname) + await expect(friend.getByRole('heading', { level: 1, name: title })).toBeVisible() + await expect(friend.getByText(t('quickPolls.page.answered', { count: 1, max: 10 }))).toBeVisible() + await answer(friend, title, ben, 2) + const heatmap = friend.getByRole('grid', { name: t('quickPolls.page.heatGridLabel', { title }) }) + await expect(heatmap.getByRole('gridcell', { name: /: 2 free, 0 maybe/ })).toHaveCount(2) + + // The creator's page picks the new answer up without a reload. + await expect(creator.getByText(t('quickPolls.page.answered', { count: 2, max: 10 }))).toBeVisible( + { timeout: 25_000 }, + ) + await expect( + creator + .getByRole('region', { name: t('bestTime.title') }) + .getByText(t('bestTime.everyoneCanMake')) + .first(), + ).toBeVisible() + + // The friend comes back on the same browser and changes their answer. + await friend.reload() + await friend.getByRole('button', { name: t('quickPolls.page.edit') }).click() + await paint(friend, title, 3) + await friend.getByRole('button', { name: t('quickPolls.page.update') }).click() + await expect(friend.getByText(t('quickPolls.page.sentTitle', { name: ben }))).toBeVisible() + + // The creator closes the poll; the friend sees it read only. + await creator.getByRole('button', { name: t('quickPolls.page.close') }).click() + await creator + .getByRole('dialog', { name: t('quickPolls.page.closeTitle') }) + .getByRole('button', { name: t('quickPolls.page.close') }) + .click() + await expect( + creator.getByRole('heading', { name: t('quickPolls.page.closedTitle') }), + ).toBeVisible() + await friend.reload() + await expect( + friend.getByRole('heading', { name: t('quickPolls.page.closedTitle') }), + ).toBeVisible() + await expect(friend.getByRole('button', { name: t('quickPolls.page.edit') })).toHaveCount(0) +}) + +test('a full poll turns a new person away but shows the results', async ({ openAs }) => { + const title = unique('Picnic') + const poll = await quickPoll({ title, maxPeople: 2 }) + await answerQuickPoll(poll.code, unique('Cy')) + await answerQuickPoll(poll.code, unique('Dee')) + + const late = await openAs(null) + await late.goto(`/p/${poll.code}`) + await expect(late.getByRole('heading', { name: t('quickPolls.page.fullTitle') })).toBeVisible() + await expect(late.getByLabel(t('quickPolls.page.nameLabel'))).toHaveCount(0) + await expect( + late.getByRole('grid', { name: t('quickPolls.page.heatGridLabel', { title }) }), + ).toBeVisible() +}) diff --git a/apps/web/e2e/support/api.ts b/apps/web/e2e/support/api.ts index a657fc16..0600c469 100644 --- a/apps/web/e2e/support/api.ts +++ b/apps/web/e2e/support/api.ts @@ -5,10 +5,15 @@ import { createGuestLink, createInvite, createPlanEvent, + createQuickPoll, + setQuickPollAvailability, + type CreateQuickPollInput, type ExpensePayload, } from '@potluck/api' import { createClient } from '@supabase/supabase-js' -import { stackEnv } from './env' +import { execFileSync } from 'node:child_process' +import { readFileSync } from 'node:fs' +import { repoRoot, stackEnv } from './env' import { unique, type TestUser } from './fixtures' /** `days` from today as YYYY-MM-DD (UTC, like every e2e user). */ @@ -100,3 +105,72 @@ export async function addEqualExpense( ...extra, }) } + +/** + * Empties the quick poll create log on the local database. Creating is limited to 5 polls an + * hour per client address and every local call shares one address, so each test that makes a + * poll starts here; the limit itself stays as it is. Runs psql inside the local stack's database + * container (the stack's `project_id` names it), never against a hosted project. + */ +export function clearQuickPollCreates() { + const config = readFileSync(`${repoRoot}supabase/config.toml`, 'utf8') + const projectId = /^project_id\s*=\s*"([^"]+)"/m.exec(config)?.[1] ?? 'potluck' + execFileSync( + 'docker', + [ + 'exec', + `supabase_db_${projectId}`, + 'psql', + '-U', + 'postgres', + '-tAc', + 'delete from private.quick_poll_creates', + ], + { stdio: 'ignore' }, + ) +} + +/** A client with no account, like a browser that never signed in. */ +function anonymousClient() { + const env = stackEnv() + return createClient(env.url, env.publishableKey, { + auth: { persistSession: false, autoRefreshToken: false }, + }) +} + +/** + * A quick poll made without an account: tomorrow and the day after, 10:00 to 12:00 UTC, one hour + * long. Returns its code and the creator token. + */ +export async function quickPoll(input: Partial = {}) { + clearQuickPollCreates() + return createQuickPoll(anonymousClient(), { + title: unique('Picnic'), + timeZone: 'UTC', + windowStart: dayFromToday(1), + windowEnd: dayFromToday(2), + dayStartMinute: 600, + dayEndMinute: 720, + durationMinutes: 60, + slotMinutes: 30, + ttl: '7d', + namesRequired: true, + maxPeople: 10, + ...input, + }) +} + +/** Someone without an account answers `code` with tomorrow 10:00 to 11:00; returns their token. */ +export async function answerQuickPoll(code: string, name: string, token: string | null = null) { + const day = dayFromToday(1) + const saved = await setQuickPollAvailability(anonymousClient(), { + code, + name, + token, + slots: [ + { slot_start: `${day}T10:00:00.000Z`, level: 'yes' }, + { slot_start: `${day}T10:30:00.000Z`, level: 'yes' }, + ], + }) + return saved.token +} From 892127759f902e349fa1adcd61c4d924c2add2d6 Mon Sep 17 00:00:00 2001 From: Musa Kaleem <131704022+Musa-Kal@users.noreply.github.com> Date: Sun, 22 Nov 2026 19:08:53 -0500 Subject: [PATCH 12/21] docs: quick poll screens, journey and shared public page pieces Co-authored-by: Ferrin <177692050+Ferrin-Y@users.noreply.github.com> Co-authored-by: noorelmosrati <182049385+noorelmosrati@users.noreply.github.com> --- docs/agent-map.json | 7 +++++++ docs/architecture.md | 1 + docs/development.md | 1 + docs/testing.md | 3 ++- 4 files changed, 11 insertions(+), 1 deletion(-) diff --git a/docs/agent-map.json b/docs/agent-map.json index 6bbe3989..49588d21 100644 --- a/docs/agent-map.json +++ b/docs/agent-map.json @@ -213,6 +213,13 @@ "file": "apps/web/src/routes/join.$code.tsx", "signedIn": false }, + { + "id": "/p/$code", + "path": "/p/$code", + "file": "apps/web/src/routes/p.$code.tsx", + "signedIn": false + }, + { "id": "/poll", "path": "/poll", "file": "apps/web/src/routes/poll.tsx", "signedIn": false }, { "id": "/reset-password", "path": "/reset-password", diff --git a/docs/architecture.md b/docs/architecture.md index 33440895..20aa7542 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -550,6 +550,7 @@ Availability polls that need no account, group or event ([ADR 22](adr/0022-quick - `quick_poll_answers`: `id`, `poll_id`, `seat int` (1, 2, 3... in answer order, unique per poll, never reused), `display_name` (1 to 40 characters after `private.clean_guest_name`; null when the poll does not ask for names), `token_hash bytea` (unique per poll; the creator's answer reuses `creator_token_hash`), `saves` and `saves_window_start` (rate limit), timestamps. - `quick_poll_slots`: `(answer_id, slot_start)` pk, `level`. Same shape as `availability`. - `private.quick_poll_creates`: `creator_hash` (sha256 of the first `x-forwarded-for` entry, null without one), `created_at`. One row per poll made, kept an hour, for the create rate limit; deleting a poll leaves its row. +- Screens: `/poll` makes a poll and `/p/` shows it (`apps/web/src/features/quick-polls`), both open signed in or out. Results refresh by polling the preview (every 15 seconds while the tab is visible, and on focus): `anon` reads no tables, so there is no Realtime. `/p/*` is kept out of search engines by a robots meta tag and an `X-Robots-Tag` header (`apps/web/public/_headers`). ### Feed, notifications, platform diff --git a/docs/development.md b/docs/development.md index 93b383ef..97c06f1f 100644 --- a/docs/development.md +++ b/docs/development.md @@ -308,6 +308,7 @@ Notes for changing particular screens in `apps/web`. The general rules are in `a - Percent splits (`features/expenses/form/split-state.ts`): `PercentInput` passes on every keystroke and `typePercent` changes only that person, so a typed percent is never rewritten; `percentLeft` drives the "left to assign" or "too much" status, and core `splitPercent` refuses the save until the total is 100. Only the slider handles and "Even it out" move several people at once. - Receipts (`features/expenses/receipts`, [ADR 21](adr/0021-receipt-scanning-and-attachments.md)): only `ocr.ts` imports `tesseract.js`, lazily; a scan only fills the form (the merchant becomes the description, so the category suggestion follows it). Full rules in [receipts](receipts.md). - Plan pages add guests from `/a/$code` (guest links, signed out) to `members` with `guest: true`. +- Quick polls (`features/quick-polls`, [ADR 22](adr/0022-quick-polls-without-accounts.md)): `/poll` and `/p/$code`, signed in or out. The poll page renders from the preview's `status` plus one local mode (`viewing` or `editing`); the browser keeps `{ token, name }` per code with `pollMemory` (`src/lib/link-memory.ts`, the same store as guest links, which survives blocked storage), and the preview's `isCreator` decides the creator's controls. Answers feed the plan heatmap and `BestTimes` as people keyed by seat (`results.ts`, core `rankSlots`), with "Anonymous {seat}" when the poll takes no names. The page polls every 15 seconds instead of Realtime. Shared with the guest page: `PublicFrame`, `DeadEnd` and `Pitch` (`features/shell/public-page.tsx`), `SentCard` and `WindowFacts` (`features/availability`), `WindowFields` (`features/plans/window-fields.tsx`, also the plan form) and `shareLink` (`features/invites/share.ts`). The rate limit on making polls counts every local call as one client: e2e empties `private.quick_poll_creates` on the local database first (`clearQuickPollCreates` in `e2e/support/api.ts`). - Money: `fx_rate` arrives as decimal text; pass it to `convert()` unchanged. An expense can have several payers and be a refund ([ADR 12](adr/0012-several-payers-refunds-and-stored-items.md)): read who paid with `payersOf()` and feed core with `toBalanceExpense()` (`features/expenses/expense-math.ts`), never `paid_by` alone. What an expense means for the viewer (`viewerLine`) comes from core `expenseEffect` in the group currency, so a row can never disagree with the balance. - Repeating expenses (`features/recurring/`, [ADR 14](adr/0014-editable-recurring-templates.md)): a template opens in the expense form (`ExpenseForm mode="recurring"`, route `/recurring/$recurringId`) through `templateAsExpense()`, so payers, adjustments and items work as for an expense. Skip, pause and stop live in `useTemplateActions`; the expense page shows `RepeatCard`. - Language: `src/lib/language.ts` starts the app in the remembered (or browser) language before the first render; the root keys its outlet by language, so a switch redraws every screen. The profile's `locale` wins once it loads (`features/account/use-profile-language.ts`). Amounts and dates follow it: give components that take a `locale` `intlLocale()`, never `DEFAULT_LOCALE` (landing only). diff --git a/docs/testing.md b/docs/testing.md index b800cd67..4ef8c23b 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -170,8 +170,9 @@ Every test creates its own users and groups with unique names, so tests run in p | `me.spec.ts` | theme choice survives a reload, calendar feed link shown, deleting the account signs out and the password stops working | | `notifications.spec.ts` | turning Payments push off on the Me page survives a reload; a payment then still lands in the inbox but is not routed to push, while a new expense is | | `guest-links.spec.ts` | a member makes a guest link (cap and expiry) and copies it, a signed out guest opens `/a/`, names themselves and paints, comes back to edit, the host sees them live with a Guest tag; a full link turns a second guest away; an expired link says it has closed | +| `quick-polls.spec.ts` | signed out, make a quick poll from the landing page entry, copy its link, the creator and a second signed out browser answer, the creator sees the new answer without a reload, the second edits, the creator closes it and the second sees it read only; a full poll turns a new person away but shows the results | | `insights.spec.ts` | search from the app bar finds an expense in every group the viewer is in and nothing else, and a number in the address searches for that text; filtering a group to one person, a month and a category shows the matching total and keeps the filters on the Expenses tab; Totals adds up the viewer's share, a month column picked by keyboard, the table view, restoring a deleted expense and a deleted payment; a group's activity link; activity with a friend; Spending converted into your currency | -| `a11y.spec.ts` | axe (WCAG 2.1 A and AA) on landing, home, group expenses, add expense, balances, event page, the signed out guest link page, Me, Friends (owing both ways) and the unsubscribe page: fails on serious or critical violations and on any sideways page scroll | +| `a11y.spec.ts` | axe (WCAG 2.1 A and AA) on landing, home, group expenses, add expense, balances, event page, the signed out guest link page, the quick poll create and poll pages, Me, Friends (owing both ways) and the unsubscribe page: fails on serious or critical violations and on any sideways page scroll | | `account.spec.ts` | change password (wrong current refused, other devices signed out, a security email sent), sign out everywhere, a device left open reaching sign in by itself (the 30 second check) and saying why, two-step setup (codes only close with "I saved them") and sign in with a code (wrong code refused, API and Storage refused at aal1), turning it off clears the codes, a recovery code, five wrong recovery tries then a pause, email change through Mailpit links and calling one off, the language switching live (text and amounts) and following the account to a new device | | `recurring.spec.ts` | editing a repeating rent changes the series and leaves the posted copy; someone else sees it read only; making an expense repeat every 2 weeks from its page, then skipping the next one | | `receipts.spec.ts` | scan the fixture receipt (`e2e/fixtures/receipt.png`) on the device, check and edit what it read, fill the by-item editor, add a second photo, save, open both full screen; group members can sign the files, an outsider cannot | From 120609c7955d94e4fddf92cdd2a2ed7e7ecb6e4b Mon Sep 17 00:00:00 2001 From: Musa Kaleem <131704022+Musa-Kal@users.noreply.github.com> Date: Sun, 22 Nov 2026 19:18:25 -0500 Subject: [PATCH 13/21] test(e2e): count the friend's edit from the slots already painted Co-authored-by: Ferrin <177692050+Ferrin-Y@users.noreply.github.com> Co-authored-by: noorelmosrati <182049385+noorelmosrati@users.noreply.github.com> --- apps/web/e2e/quick-polls.spec.ts | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/apps/web/e2e/quick-polls.spec.ts b/apps/web/e2e/quick-polls.spec.ts index 88ff6109..8a615a7b 100644 --- a/apps/web/e2e/quick-polls.spec.ts +++ b/apps/web/e2e/quick-polls.spec.ts @@ -3,8 +3,11 @@ import type { Page } from '@playwright/test' import { answerQuickPoll, clearQuickPollCreates, quickPoll } from './support/api' import { expect, test, unique } from './support/fixtures' -/** Paints the first `count` free cells of the poll's grid with the keyboard. */ -async function paint(page: Page, title: string, count: number) { +/** + * Paints `count` cells down from the first free one with the keyboard; `total` is how many the + * answer then has. + */ +async function paint(page: Page, title: string, count: number, total = count) { const painter = page.getByRole('grid', { name: t('quickPolls.page.gridLabel', { title }) }) await expect(painter).toBeVisible() await painter @@ -13,7 +16,7 @@ async function paint(page: Page, title: string, count: number) { .focus() await page.keyboard.press('Space') for (let i = 1; i < count; i++) await page.keyboard.press('Shift+ArrowDown') - await expect(page.getByText(t('availability.mySlots', { count }))).toBeVisible() + await expect(page.getByText(t('availability.mySlots', { count: total }))).toBeVisible() } async function answer(page: Page, title: string, name: string, count: number) { @@ -90,7 +93,7 @@ test('make a quick poll from the landing page, two people answer without account // The friend comes back on the same browser and changes their answer. await friend.reload() await friend.getByRole('button', { name: t('quickPolls.page.edit') }).click() - await paint(friend, title, 3) + await paint(friend, title, 1, 3) await friend.getByRole('button', { name: t('quickPolls.page.update') }).click() await expect(friend.getByText(t('quickPolls.page.sentTitle', { name: ben }))).toBeVisible() From 2b49627fb3c5a85263a7281fe661c168d18c7529 Mon Sep 17 00:00:00 2001 From: Musa Kaleem <131704022+Musa-Kal@users.noreply.github.com> Date: Sun, 22 Nov 2026 20:46:14 -0500 Subject: [PATCH 14/21] review: fix quick poll stale refetch, unsaved flag, slot parsing Co-authored-by: Ferrin <177692050+Ferrin-Y@users.noreply.github.com> Co-authored-by: noorelmosrati <182049385+noorelmosrati@users.noreply.github.com> --- .../features/quick-polls/poll-page.test.tsx | 54 +++++++++++++++++++ .../src/features/quick-polls/poll-page.tsx | 18 +++++-- packages/api/src/quick-polls.test.ts | 23 ++++---- packages/api/src/quick-polls.ts | 8 ++- 4 files changed, 84 insertions(+), 19 deletions(-) diff --git a/apps/web/src/features/quick-polls/poll-page.test.tsx b/apps/web/src/features/quick-polls/poll-page.test.tsx index 5ce54e34..3fcf619c 100644 --- a/apps/web/src/features/quick-polls/poll-page.test.tsx +++ b/apps/web/src/features/quick-polls/poll-page.test.tsx @@ -367,6 +367,60 @@ describe('PollPage', () => { expect(await screen.findByRole('heading', { level: 1, name: 'Board games' })).toBeVisible() }) + it('closes a poll that is deleted while it is open on the page', async () => { + db().respond( + 'rpc:quick_poll_preview', + { data: [open] }, + { error: { message: 'quick_poll_not_found' } }, + ) + const { queryClient } = renderPage() + expect(await screen.findByRole('heading', { level: 1, name: 'Board games' })).toBeVisible() + + await queryClient.invalidateQueries() + + expect( + await screen.findByRole('heading', { name: t('quickPolls.ended.notFoundTitle') }), + ).toBeVisible() + expect(screen.queryByRole('heading', { name: 'Board games' })).not.toBeInTheDocument() + }) + + it('keeps the poll and the times being painted when a refresh fails', async () => { + const offline = { error: { message: 'TypeError: Failed to fetch' } } + db().respond('rpc:quick_poll_preview', { data: [open] }, offline) + const { queryClient } = renderPage() + await screen.findByRole('heading', { level: 1, name: 'Board games' }) + paint(slot('19:00')) + + // The refresh tries three times before it gives up. + await queryClient.invalidateQueries() + + expect(db().rpcArgs('quick_poll_preview')).toHaveLength(4) + expect(screen.getByRole('heading', { level: 1, name: 'Board games' })).toBeVisible() + expect(cell(slot('19:00'))).toHaveAttribute('aria-selected', 'true') + expect(screen.queryByText(t('quickPolls.page.loadFailedTitle'))).not.toBeInTheDocument() + }, 15_000) + + it('does not call times unsaved after the visitor backs out of editing', async () => { + pollMemory.write('poll123', { token: 'tok-ana', name: 'Ana' }) + const mine = { ...open, answers: [{ ...ana, mine: true }] } + db().respond( + 'rpc:quick_poll_preview', + { data: [mine] }, + { data: [{ ...mine, status: 'closed' }] }, + ) + const { queryClient } = renderPage() + + fireEvent.click(await screen.findByRole('button', { name: t('quickPolls.page.edit') })) + paint(slot('19:00')) + fireEvent.click(screen.getByRole('button', { name: t('quickPolls.page.cancel') })) + await queryClient.invalidateQueries() + + expect( + await screen.findByRole('heading', { name: t('quickPolls.page.closedTitle') }), + ).toBeVisible() + expect(screen.queryByText(t('quickPolls.page.unsaved'))).not.toBeInTheDocument() + }) + it('pitches an account to visitors without one, and not to people signed in', async () => { db().respond('rpc:quick_poll_preview', { data: [open] }) const first = renderPage() diff --git a/apps/web/src/features/quick-polls/poll-page.tsx b/apps/web/src/features/quick-polls/poll-page.tsx index 97bd6dd8..acce9e20 100644 --- a/apps/web/src/features/quick-polls/poll-page.tsx +++ b/apps/web/src/features/quick-polls/poll-page.tsx @@ -82,7 +82,10 @@ export function PollPage({ code }: { code: string }) { ) } - if (preview.isError && !isNotFoundError(preview.error)) { + const gone = preview.isError && isNotFoundError(preview.error) + const view = gone ? undefined : preview.data + + if (preview.isError && !gone && !view) { return ( {noIndex} @@ -102,7 +105,6 @@ export function PollPage({ code }: { code: string }) { ) } - const view = preview.data if (!view || view.status === 'expired') { return ( <> @@ -131,6 +133,7 @@ export function PollPage({ code }: { code: string }) { setMemory(next) }} onDirty={() => setUnsaved(true)} + onDiscarded={() => setUnsaved(false)} /> ) @@ -162,6 +165,7 @@ function Poll({ unsaved, onSaved, onDirty, + onDiscarded, }: { code: string view: LivePoll @@ -169,6 +173,7 @@ function Poll({ unsaved: boolean onSaved: (memory: PollMemory) => void onDirty: () => void + onDiscarded: () => void }) { const queryClient = useQueryClient() const session = useSession() @@ -284,7 +289,14 @@ function Poll({ model={model} title={title} memory={memory} - onCancel={mine ? () => setMode('viewing') : undefined} + onCancel={ + mine + ? () => { + setMode('viewing') + onDiscarded() + } + : undefined + } onSaved={(next) => { onSaved(next) setMode('viewing') diff --git a/packages/api/src/quick-polls.test.ts b/packages/api/src/quick-polls.test.ts index 14b36a35..f22b15f2 100644 --- a/packages/api/src/quick-polls.test.ts +++ b/packages/api/src/quick-polls.test.ts @@ -104,24 +104,25 @@ describe('fetchQuickPollPreview', () => { expect(await fetchQuickPollPreview(odd.client, 'abc', null)).toEqual({ status: 'expired' }) }) - it('reads odd answers defensively', async () => { + it('reads odd answers defensively, dropping slots that name no time', async () => { + const kept = { slot_start: '2026-06-01T08:30:00+00:00', level: 'maybe' } const row = { ...openRow, - answers: [null, { seat: 'x', name: 3, mine: 'yes', slots: [null, { level: 'no' }] }], + answers: [ + null, + { + seat: 'x', + name: 3, + mine: 'yes', + slots: [null, { level: 'yes' }, { slot_start: 5, level: 'yes' }, kept], + }, + ], } const fake = fakeSupabase().respond('rpc:quick_poll_preview', { data: [row] }) const view = await fetchQuickPollPreview(fake.client, 'abc', null) expect(view.status === 'open' && view.answers).toEqual([ { seat: 0, name: null, mine: false, slots: [] }, - { - seat: 0, - name: null, - mine: false, - slots: [ - { slot_start: 'undefined', level: 'yes' }, - { slot_start: 'undefined', level: 'yes' }, - ], - }, + { seat: 0, name: null, mine: false, slots: [kept] }, ]) const none = fakeSupabase().respond('rpc:quick_poll_preview', { data: [{ ...openRow, answers: null }], diff --git a/packages/api/src/quick-polls.ts b/packages/api/src/quick-polls.ts index b97c1669..c9434683 100644 --- a/packages/api/src/quick-polls.ts +++ b/packages/api/src/quick-polls.ts @@ -89,12 +89,10 @@ function parseAnswers(value: unknown): QuickPollAnswer[] { name: typeof a.name === 'string' ? a.name : null, mine: a.mine === true, slots: Array.isArray(a.slots) - ? a.slots.map((slot) => { + ? a.slots.flatMap((slot): QuickPollSlot[] => { const s = record(slot) - return { - slot_start: String(s.slot_start), - level: s.level === 'maybe' ? 'maybe' : 'yes', - } + if (typeof s.slot_start !== 'string') return [] + return [{ slot_start: s.slot_start, level: s.level === 'maybe' ? 'maybe' : 'yes' }] }) : [], } From a36b5f47e2133cbebbb6672d487bc0371e0df284 Mon Sep 17 00:00:00 2001 From: Musa Kaleem <131704022+Musa-Kal@users.noreply.github.com> Date: Sun, 22 Nov 2026 21:13:53 -0500 Subject: [PATCH 15/21] fix(quick-polls): the browser makes its answer token so a retried first save keeps one seat A first save whose reply was lost left the browser without a token, so the retry made a second answer under the same name: the first seat was orphaned, counted twice in best times and the heatmap, and used up the cap. The poll page now makes a random token (Web Crypto) for a visitor without one and keeps it in link memory, and in component state when storage is blocked, before the first save goes out. set_quick_poll_availability takes that token: one the poll does not know makes a new answer under it, a known one edits it, the creator token works as before, and a missing or malformed token is refused with invalid_quick_poll_token (22023). The return shape is unchanged and hands back the token as sent. Co-authored-by: Ferrin <177692050+Ferrin-Y@users.noreply.github.com> Co-authored-by: noorelmosrati <182049385+noorelmosrati@users.noreply.github.com> --- apps/web/e2e/support/api.ts | 3 +- .../src/features/quick-polls/poll-memory.ts | 5 +- .../features/quick-polls/poll-page.test.tsx | 48 +++++++++++++-- .../src/features/quick-polls/poll-page.tsx | 23 ++++++-- apps/web/src/lib/link-memory.ts | 5 +- docs/adr/0022-quick-polls-without-accounts.md | 5 +- docs/agent-map.json | 35 ++++++----- docs/architecture.md | 6 +- docs/security.md | 2 +- docs/testing.md | 2 +- packages/api/src/quick-polls.test.ts | 17 ++++-- packages/api/src/quick-polls.ts | 15 ++--- packages/i18n/src/de/quick-polls.ts | 2 + packages/i18n/src/en/quick-polls.ts | 2 + packages/i18n/src/es/quick-polls.ts | 2 + packages/i18n/src/fr/quick-polls.ts | 2 + packages/i18n/src/pt/quick-polls.ts | 2 + .../migrations/20261122232215_quick_polls.sql | 22 +++---- supabase/schema/current.sql | 10 ++-- supabase/tests/36_quick_polls.test.sql | 58 +++++++++++++------ 20 files changed, 184 insertions(+), 82 deletions(-) diff --git a/apps/web/e2e/support/api.ts b/apps/web/e2e/support/api.ts index 0600c469..aad9c570 100644 --- a/apps/web/e2e/support/api.ts +++ b/apps/web/e2e/support/api.ts @@ -12,6 +12,7 @@ import { } from '@potluck/api' import { createClient } from '@supabase/supabase-js' import { execFileSync } from 'node:child_process' +import { randomUUID } from 'node:crypto' import { readFileSync } from 'node:fs' import { repoRoot, stackEnv } from './env' import { unique, type TestUser } from './fixtures' @@ -161,7 +162,7 @@ export async function quickPoll(input: Partial = {}) { } /** Someone without an account answers `code` with tomorrow 10:00 to 11:00; returns their token. */ -export async function answerQuickPoll(code: string, name: string, token: string | null = null) { +export async function answerQuickPoll(code: string, name: string, token = randomUUID()) { const day = dayFromToday(1) const saved = await setQuickPollAvailability(anonymousClient(), { code, diff --git a/apps/web/src/features/quick-polls/poll-memory.ts b/apps/web/src/features/quick-polls/poll-memory.ts index ef20d0cc..9a7ee11e 100644 --- a/apps/web/src/features/quick-polls/poll-memory.ts +++ b/apps/web/src/features/quick-polls/poll-memory.ts @@ -2,8 +2,9 @@ import { linkMemory, parseTokenMemory, type TokenMemory } from '@/lib/link-memor /** * What a browser remembers per quick poll: its token (the creator token for whoever made the - * poll, else the answer token the first save handed back) and the name typed. Whether this - * browser made the poll is not kept here: the preview says so for the token (`isCreator`). + * poll, else the answer token the browser made, kept before its first save went out) and the + * name typed. Whether this browser made the poll is not kept here: the preview says so for the + * token (`isCreator`). */ export type PollMemory = TokenMemory diff --git a/apps/web/src/features/quick-polls/poll-page.test.tsx b/apps/web/src/features/quick-polls/poll-page.test.tsx index 3fcf619c..54284a05 100644 --- a/apps/web/src/features/quick-polls/poll-page.test.tsx +++ b/apps/web/src/features/quick-polls/poll-page.test.tsx @@ -17,6 +17,8 @@ vi.mock('@/lib/auth', async (importOriginal) => ({ })) const slot = (time: string) => `2026-06-12T${time}:00.000Z` +// A token the browser made: long enough for the server and safe in a URL. +const madeToken = expect.stringMatching(/^[\w-]{24,200}$/) const at = (time: string) => `2026-06-12T${time}:00+00:00` const ana = { @@ -68,6 +70,7 @@ function renderPage(code = 'poll123') { describe('PollPage', () => { beforeEach(() => { + vi.restoreAllMocks() resetDb() window.localStorage.clear() auth.session = null @@ -117,12 +120,13 @@ describe('PollPage', () => { { code: 'poll123', name: 'Ben', - token: '', + token: madeToken, slots: [{ slot_start: slot('18:00'), level: 'yes' }], }, ]) - expect(pollMemory.read('poll123')).toEqual({ token: 'tok-ben', name: 'Ben' }) - expect(db().rpcArgs('quick_poll_preview')).toContainEqual({ code: 'poll123', token: 'tok-ben' }) + const { token } = db().rpcArgs('set_quick_poll_availability')[0] as { token: string } + expect(pollMemory.read('poll123')).toEqual({ token, name: 'Ben' }) + expect(db().rpcArgs('quick_poll_preview')).toContainEqual({ code: 'poll123', token }) expect(screen.getByText(t('quickPolls.page.answered', { count: 2, max: 10 }))).toBeVisible() }) @@ -201,7 +205,10 @@ describe('PollPage', () => { t('quickPolls.page.sentTitleAnon', { name: t('quickPolls.anonymous', { seat: 2 }) }), ), ).toBeVisible() - expect(db().rpcArgs('set_quick_poll_availability')[0]).toMatchObject({ name: '', token: '' }) + expect(db().rpcArgs('set_quick_poll_availability')[0]).toMatchObject({ + name: '', + token: madeToken, + }) // The first answer suits seat 1 only, so the best time goes without seat 2. expect( screen.getByText(t('bestTime.missing', { names: t('quickPolls.anonymous', { seat: 2 }) })), @@ -322,6 +329,39 @@ describe('PollPage', () => { expect(screen.getByRole('alert')).toHaveTextContent(t('quickPolls.page.unsaved')) }) + it.each([ + ['kept in storage', false], + ['with storage blocked', true], + ])('sends a failed first save again under the same token, %s', async (_, blocked) => { + if (blocked) { + vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => { + throw new DOMException('blocked', 'SecurityError') + }) + } + const offline = { error: { message: 'TypeError: Failed to fetch' } } + db() + .respond('rpc:quick_poll_preview', { data: [open] }) + .respond('rpc:set_quick_poll_availability', offline, { + data: [{ answer_token: 'ignored', saved: 1 }], + }) + renderPage() + fireEvent.change(await screen.findByLabelText(t('quickPolls.page.nameLabel')), { + target: { value: 'Cy' }, + }) + paint(slot('19:00')) + + fireEvent.click(screen.getByRole('button', { name: t('quickPolls.page.submit') })) + expect(await screen.findByRole('alert')).toBeVisible() + const first = db().rpcArgs('set_quick_poll_availability')[0] as { token: string } + expect(first).toMatchObject({ token: madeToken }) + // Kept before the reply came, so a reload after a lost reply sends it too. + expect(pollMemory.read('poll123')?.token).toBe(blocked ? undefined : first.token) + + fireEvent.click(screen.getByRole('button', { name: t('quickPolls.page.submit') })) + await waitFor(() => expect(db().rpcArgs('set_quick_poll_availability')).toHaveLength(2)) + expect(db().rpcArgs('set_quick_poll_availability')[1]).toEqual(first) + }) + it('words other save errors in place', async () => { db() .respond('rpc:quick_poll_preview', { data: [open] }) diff --git a/apps/web/src/features/quick-polls/poll-page.tsx b/apps/web/src/features/quick-polls/poll-page.tsx index acce9e20..89663215 100644 --- a/apps/web/src/features/quick-polls/poll-page.tsx +++ b/apps/web/src/features/quick-polls/poll-page.tsx @@ -32,6 +32,7 @@ import { DeadEnd, Notice, Pitch, PublicFrame } from '@/features/shell/public-pag import { useSession } from '@/lib/auth' import { errorCode, errorMessage, isNotFoundError } from '@/lib/errors' import { detectTimezone } from '@/lib/locale' +import { newRequestId } from '@/lib/request-id' import { supabase } from '@/lib/supabase' import { pollMemory, type PollMemory } from './poll-memory' import { answerName, gridEvent, pollResults } from './results' @@ -61,7 +62,7 @@ export function PollPage({ code }: { code: string }) { const [memory, setMemory] = useState(() => pollMemory.read(code)) // Painted or typed but not saved: if the poll stops taking answers meanwhile, the page says so. const [unsaved, setUnsaved] = useState(false) - // Saving hands back a token, which changes the query key; keep showing the poll meanwhile. + // The first save keeps a new token, which changes the query key; keep showing the poll meanwhile. const preview = useQuery({ ...quickPollQueries.preview(supabase, code, memory?.token ?? null), placeholderData: (previous) => previous, @@ -393,18 +394,20 @@ function AnswerForm({ const [nameError, setNameError] = useState(null) const [formError, setFormError] = useState(null) const nameRef = useRef(null) + // The token a new visitor made for their first save, for when storage is blocked. + const madeToken = useRef(null) const cleanName = cleanGuestName(name) const save = useMutation({ - mutationFn: () => + mutationFn: (token: string) => setQuickPollAvailability(supabase, { code, name: poll.namesRequired ? cleanName : null, - token: memory?.token ?? null, + token, slots: [...value].map(([slot_start, level]) => ({ slot_start, level })), }), - onSuccess: async (result) => { - const next = { token: result.token, name: poll.namesRequired ? cleanName : '' } + onSuccess: async (_, token) => { + const next = { token, name: poll.namesRequired ? cleanName : '' } pollMemory.write(code, next) // Load the poll with the answer in it before leaving the form, so "Sent" has it to show. try { @@ -443,7 +446,15 @@ function AnswerForm({ setFormError(t('quickPolls.page.needTimes')) return } - save.mutate() + // A new visitor makes their token and keeps it before the first save goes out, so a retry + // after a lost reply (or a reload) sends the same one and edits that answer, not a second. + let token = memory?.token ?? madeToken.current + if (!token) { + token = newRequestId() + madeToken.current = token + pollMemory.write(code, { token, name: poll.namesRequired ? cleanName : '' }) + } + save.mutate(token) } return ( diff --git a/apps/web/src/lib/link-memory.ts b/apps/web/src/lib/link-memory.ts index 11ee2906..3b6397ee 100644 --- a/apps/web/src/lib/link-memory.ts +++ b/apps/web/src/lib/link-memory.ts @@ -1,6 +1,7 @@ /** - * What a browser remembers per shared link (a guest link, a quick poll): the token the server - * handed back, which proves this browser wrote the answer, plus whatever the page needs next time. + * What a browser remembers per shared link (a guest link, a quick poll): the token that proves + * this browser wrote the answer (a guest link's server hands it back, a quick poll's browser makes + * it), plus whatever the page needs next time. * Storage can be missing or blocked (private windows, strict settings); the page then works, it * just forgets on reload. */ diff --git a/docs/adr/0022-quick-polls-without-accounts.md b/docs/adr/0022-quick-polls-without-accounts.md index 88fbc7d7..869fb1f0 100644 --- a/docs/adr/0022-quick-polls-without-accounts.md +++ b/docs/adr/0022-quick-polls-without-accounts.md @@ -11,7 +11,7 @@ Finding a time with people who are not in a group (a one off dinner, a call with - Quick polls are their own tables, with no group, event or auth user: `quick_polls` (code, grid, expiry, settings), `quick_poll_answers` (one per browser, numbered by seat, a name only when the poll asks for one) and `quick_poll_slots` (the same shape as `availability`). Nothing in groups or plans changes, and no existing policy has to learn about them. - Clients never touch the tables. RLS is on with no policies and `anon` and `authenticated` hold no grants. Five `security definer` RPCs are the whole surface, callable by `anon` and `authenticated`: `create_quick_poll`, `quick_poll_preview`, `set_quick_poll_availability`, `close_quick_poll` and `delete_quick_poll`. -- Tokens, not sessions, as for guests. Creating a poll returns a 24 byte creator token; the database keeps its sha256. The same token is the creator's answer token, so the creator answers like anyone else and takes a seat. Every other browser gets its own token on its first save. Only the creator token closes or deletes a poll. +- Tokens, not sessions, as for guests. Creating a poll returns a 24 byte creator token; the database keeps its sha256. The same token is the creator's answer token, so the creator answers like anyone else and takes a seat. Every other browser makes its own answer token (a random UUID from Web Crypto) and keeps it before its first save goes out, then sends it with every save: a token the poll does not know makes a new answer under it, a known one edits that answer, and no token (or one outside 16 to 200 characters) is refused with `invalid_quick_poll_token`. So a first save resent after a lost reply, or after a reload, edits the answer it made instead of taking a second seat. Only the creator token closes or deletes a poll. - One owner per rule. `private.quick_poll_status` decides `expired`, `closed`, `full` or `open` for every RPC. The slot grid check moved out of `private.event_slots` into `private.grid_slots`, which both plans and quick polls call. The limits (2 to 15 people, 10 by default, 1 to 14 days, titles up to 80 characters, `24h` or `7d`) live in `packages/core` and the SQL checks together. - Polls are small and short lived: at most 15 people, and they last 24 hours or 7 days. The hourly `purge-quick-polls` job deletes expired polls with their answers. - The app is a static site that talks straight to Supabase, so the create rate limit lives in the database: 5 polls an hour per client and 200 an hour in all, serialized by an advisory lock. The client is the sha256 of the first `x-forwarded-for` entry PostgREST hands over in `request.headers`. Those hashes go in `private.quick_poll_creates`, kept an hour, not on the poll, so deleting a poll does not give quota back and nothing about the client outlives the hour. @@ -19,7 +19,8 @@ Finding a time with people who are not in a group (a one off dinner, a call with ## Consequences - Anyone with the code sees every answer's name and times until the poll expires; that is the feature. Creators choose whether to ask for names; without them answers show as seat numbers. -- Five more definer functions open to the internet. pgTAP (`36_quick_polls.test.sql`) covers table access, every create check, names on and off, seats and the cap, the creator token, each status, close, delete, the purge and both rate limits; `01_schema.test.sql` pins the anon allowlist and the cron job. +- Five more definer functions open to the internet. pgTAP (`36_quick_polls.test.sql`) covers table access, every create check, names on and off, browser made answer tokens and a resent first save, seats and the cap, the creator token, each status, close, delete, the purge and both rate limits; `01_schema.test.sql` pins the anon allowlist and the cron job. - The per client limit is only as good as `x-forwarded-for`. A client can send its own header, and its value then comes first, so the per client limit slows honest mistakes and casual scripts, not a determined abuser. The global 200 an hour is the backstop; raising it, or keying on a header the platform sets itself, is a migration. +- A client picks its own answer token. That is fine: the token only ever proves "this browser wrote this answer", the server keeps only its sha256, and it opens nothing else (not the poll's controls, not anyone else's answer). A browser that picks a weak token only risks its own answer being edited by someone who guesses it. - A browser that loses its token cannot edit its answer, and a creator who loses theirs cannot close or delete the poll; it still expires within 7 days. - Answers are never removed one by one, so seats are stable and never reused; the creator has no way to remove a stranger's answer short of deleting the poll. diff --git a/docs/agent-map.json b/docs/agent-map.json index 49588d21..3536bdf9 100644 --- a/docs/agent-map.json +++ b/docs/agent-map.json @@ -1070,6 +1070,7 @@ "execute": ["anon", "authenticated", "service_role"], "raises": [ "invalid_quick_poll_name", + "invalid_quick_poll_token", "quick_poll_closed", "quick_poll_expired", "quick_poll_full", @@ -1087,7 +1088,7 @@ "securityDefiner": true, "execute": ["authenticated", "service_role"], "raises": [], - "snapshotLine": 9967, + "snapshotLine": 9965, "definedIn": "supabase/migrations/20261113115301_group_debts_and_bulk_settle.sql" }, { @@ -1103,7 +1104,7 @@ "invalid_recipient", "member_not_found" ], - "snapshotLine": 10006, + "snapshotLine": 10004, "definedIn": "supabase/migrations/20261106010000_integrity_fixes.sql" }, { @@ -1113,7 +1114,7 @@ "securityDefiner": true, "execute": ["authenticated", "service_role"], "raises": [], - "snapshotLine": 10064, + "snapshotLine": 10062, "definedIn": "supabase/migrations/20261113115254_payments_v2.sql" }, { @@ -1123,7 +1124,7 @@ "securityDefiner": true, "execute": ["authenticated", "service_role"], "raises": [], - "snapshotLine": 10101, + "snapshotLine": 10099, "definedIn": "supabase/migrations/20261114193218_request_keys.sql" }, { @@ -1133,7 +1134,7 @@ "securityDefiner": true, "execute": ["authenticated", "service_role"], "raises": ["invalid_amount", "invalid_parties", "invalid_payload", "nothing_owed"], - "snapshotLine": 10129, + "snapshotLine": 10127, "definedIn": "supabase/migrations/20261113213127_deleted_groups_everywhere.sql" }, { @@ -1143,7 +1144,7 @@ "securityDefiner": true, "execute": ["authenticated", "service_role"], "raises": [], - "snapshotLine": 10213, + "snapshotLine": 10211, "definedIn": "supabase/migrations/20261105210000_query_performance.sql" }, { @@ -1153,7 +1154,7 @@ "securityDefiner": true, "execute": ["authenticated", "service_role"], "raises": ["not_allowed", "recurring_not_found"], - "snapshotLine": 10273, + "snapshotLine": 10271, "definedIn": "supabase/migrations/20261113153242_recurring_editing.sql" }, { @@ -1163,7 +1164,7 @@ "securityDefiner": true, "execute": ["authenticated", "service_role"], "raises": ["invalid_currency", "invalid_date_range"], - "snapshotLine": 10322, + "snapshotLine": 10320, "definedIn": "supabase/migrations/20261113172837_search_insights.sql" }, { @@ -1173,7 +1174,7 @@ "securityDefiner": true, "execute": ["authenticated", "service_role"], "raises": ["already_owner", "member_not_found", "not_allowed"], - "snapshotLine": 10467, + "snapshotLine": 10465, "definedIn": "supabase/migrations/20261105071504_rpc_groups.sql" }, { @@ -1183,7 +1184,7 @@ "securityDefiner": true, "execute": ["authenticated", "service_role"], "raises": ["expense_not_found"], - "snapshotLine": 10505, + "snapshotLine": 10503, "definedIn": "supabase/migrations/20261113091955_expense_entry.sql" }, { @@ -1193,7 +1194,7 @@ "securityDefiner": true, "execute": ["authenticated", "service_role"], "raises": ["expense_not_found"], - "snapshotLine": 10524, + "snapshotLine": 10522, "definedIn": "supabase/migrations/20261113091955_expense_entry.sql" }, { @@ -1209,7 +1210,7 @@ "placeholder_exists", "too_many_invites" ], - "snapshotLine": 10540, + "snapshotLine": 10538, "definedIn": "supabase/migrations/20261113201103_placeholder_members.sql" }, { @@ -1234,7 +1235,7 @@ "split_member_not_in_group", "splits_sum_mismatch" ], - "snapshotLine": 10643, + "snapshotLine": 10641, "definedIn": "supabase/migrations/20261113153242_recurring_editing.sql" }, { @@ -1250,7 +1251,7 @@ "settlement_deleted", "settlement_not_found" ], - "snapshotLine": 10913, + "snapshotLine": 10911, "definedIn": "supabase/migrations/20261113115254_payments_v2.sql" } ], @@ -4300,6 +4301,12 @@ "raisedBy": ["public.create_quick_poll"], "i18n": [] }, + { + "code": "invalid_quick_poll_token", + "sqlstates": ["22023"], + "raisedBy": ["public.set_quick_poll_availability"], + "i18n": [] + }, { "code": "invalid_quick_poll_ttl", "sqlstates": ["22023"], diff --git a/docs/architecture.md b/docs/architecture.md index 20aa7542..40ae3a57 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -547,7 +547,7 @@ erDiagram Availability polls that need no account, group or event ([ADR 22](adr/0022-quick-polls-without-accounts.md)). Clients read and write none of these tables; RLS is on with no policies and `anon` and `authenticated` hold no grants. - `quick_polls`: `id`, `code text unique` (16 url-safe chars), `title` (null, or 1 to 80 characters cleaned like guest names; the client shows a default for null), `timezone`, `window_start`, `window_end` (1 to 14 days, both included), `day_start_minute`, `day_end_minute`, `slot_minutes` (30 or 60), `duration_minutes` (15 to 1440), `names_required bool default true`, `max_people int default 10` (2 to 15), `creator_token_hash bytea` (sha256 of the creator's token), `expires_at`, `closed_at`, `created_at`. -- `quick_poll_answers`: `id`, `poll_id`, `seat int` (1, 2, 3... in answer order, unique per poll, never reused), `display_name` (1 to 40 characters after `private.clean_guest_name`; null when the poll does not ask for names), `token_hash bytea` (unique per poll; the creator's answer reuses `creator_token_hash`), `saves` and `saves_window_start` (rate limit), timestamps. +- `quick_poll_answers`: `id`, `poll_id`, `seat int` (1, 2, 3... in answer order, unique per poll, never reused), `display_name` (1 to 40 characters after `private.clean_guest_name`; null when the poll does not ask for names), `token_hash bytea` (sha256 of the token the answering browser made; unique per poll; the creator's answer reuses `creator_token_hash`), `saves` and `saves_window_start` (rate limit), timestamps. - `quick_poll_slots`: `(answer_id, slot_start)` pk, `level`. Same shape as `availability`. - `private.quick_poll_creates`: `creator_hash` (sha256 of the first `x-forwarded-for` entry, null without one), `created_at`. One row per poll made, kept an hour, for the create rate limit; deleting a poll leaves its row. - Screens: `/poll` makes a poll and `/p/` shows it (`apps/web/src/features/quick-polls`), both open signed in or out. Results refresh by polling the preview (every 15 seconds while the tab is visible, and on focus): `anon` reads no tables, so there is no Realtime. `/p/*` is kept out of search engines by a robots meta tag and an `X-Robots-Tag` header (`apps/web/public/_headers`). @@ -700,7 +700,7 @@ Codes: - Search and totals: `invalid_date_range` (a `from_day` after `to_day`), `invalid_query` (over 200 characters), `invalid_cursor` (a page cursor missing its day, time or id). - Plans: `event_not_found`, `event_not_polling`, `event_not_schedulable`, `event_done`, `starts_at_required`, `invalid_slot`, `invalid_slots`, `duplicate_slot`, `rsvp_closed` (RSVP after the event's `rsvp_deadline`). - Guest links: `invalid_guest_link_ttl`, `invalid_guest_limit`, `guest_link_limit` (20 open links per plan), `guest_removed` (a token whose answer the organizer removed), `guest_link_not_found`, `guest_link_revoked`, `guest_link_expired`, `guest_link_full`, `invalid_guest_name`, `guest_slots_required` (a new guest with no times), `guest_rate_limited`, `guest_not_found`. -- Quick polls: `invalid_quick_poll` (the payload is not an object, or a value has the wrong type), `invalid_quick_poll_title`, `invalid_quick_poll_timezone`, `invalid_quick_poll_window`, `invalid_quick_poll_hours`, `invalid_quick_poll_slot_minutes`, `invalid_quick_poll_duration`, `invalid_quick_poll_ttl`, `invalid_quick_poll_people`, `invalid_quick_poll_name`, `quick_poll_slots_required` (a new answer with no times), `quick_poll_not_found`, `quick_poll_expired`, `quick_poll_closed`, `quick_poll_full`, `quick_poll_rate_limited` (creates or saves). +- Quick polls: `invalid_quick_poll` (the payload is not an object, or a value has the wrong type), `invalid_quick_poll_title`, `invalid_quick_poll_timezone`, `invalid_quick_poll_window`, `invalid_quick_poll_hours`, `invalid_quick_poll_slot_minutes`, `invalid_quick_poll_duration`, `invalid_quick_poll_ttl`, `invalid_quick_poll_people`, `invalid_quick_poll_name`, `invalid_quick_poll_token` (an answer token missing or outside 16 to 200 characters), `quick_poll_slots_required` (a new answer with no times), `quick_poll_not_found`, `quick_poll_expired`, `quick_poll_closed`, `quick_poll_full`, `quick_poll_rate_limited` (creates or saves). ### RPC details and deviations @@ -781,7 +781,7 @@ Codes: - The grid rule has one owner, `private.grid_slots(timezone, window_start, window_end, day_start_minute, day_end_minute, slot_minutes, slots)`; `private.event_slots` hands an event's grid to it. - `create_quick_poll(payload)` checks every key (`22023` codes above), then takes an advisory lock and refuses a sixth poll in an hour from the same client (sha256 of the first `x-forwarded-for` entry of `request.headers`; no limit per client without one) and a 201st in an hour overall (`quick_poll_rate_limited`). It returns the code, a fresh 24 byte creator token (only its sha256 is kept) and `expires_at` (`ttl` `24h` or `7d`). - `quick_poll_preview(code, token?)` raises `quick_poll_not_found` for an unknown code. `expired` returns the status only. `open`, `full` and `closed` return the title, the grid, `names_required`, `max_people`, `expires_at`, `is_creator` (the token is the creator token) and `answers`: `[{seat, name, mine, slots: [{slot_start, level}]}]` by seat, `name` null when the poll does not ask for names, never ids or hashes. - - `set_quick_poll_availability(code, name, token, slots)` locks the poll row, refuses `expired`, `closed` and, for a new answer, `full`, cleans the name when the poll asks for names (ignores it otherwise) and checks the slots against the grid. A token that matches an answer edits it (60 saves an hour). Otherwise a new answer takes the next seat and needs at least one slot; the creator token makes the creator's answer under that same token, anything else gets a fresh token back. + - `set_quick_poll_availability(code, name, token, slots)` refuses a token that is missing or outside 16 to 200 characters (`invalid_quick_poll_token`), then locks the poll row, refuses `expired`, `closed` and, for a new answer, `full`, cleans the name when the poll asks for names (ignores it otherwise) and checks the slots against the grid. The browser makes the token (the creator uses the creator token) and keeps it before its first save, so a save resent after a lost reply sends the same one. A token that matches an answer edits it (60 saves an hour). Otherwise a new answer takes the next seat under that token and needs at least one slot. Only the sha256 is kept; `answer_token` is the token as sent. - `close_quick_poll(code, token)` sets `closed_at` (again changes nothing); `delete_quick_poll(code, token)` deletes the poll, its answers and slots. Both take the creator token only (`not_allowed`). - `schedule_event(event_id, starts_at)` also reschedules an already scheduled event and sets `ends_at = starts_at + duration`. `reminder_sent_at` is cleared only when the start time actually changes, so locking in the same time again does not send a second reminder. `cancel_event` is idempotent. Owner, admins or the event creator. - `my_timeline(from = now(), to = now() + 60 days)` returns `event_id, group_id, group_name, group_emoji, group_color, title, emoji, location, status, timezone, starts_at, ends_at, window_start, window_end, rsvp_deadline, my_rsvp, going_count, availability_requested, availability_submitted` for scheduled events in range and open polls overlapping it. diff --git a/docs/security.md b/docs/security.md index dc37aa1c..965b7586 100644 --- a/docs/security.md +++ b/docs/security.md @@ -47,7 +47,7 @@ These are real today. Each should become an issue. - **Edge function CORS is `*`.** Harmless for the secret- and token-protected functions, and `delete-account` requires a JWT, but it is wider than the app needs. - **Invite previews show first names** to anyone with the code. That is the point of the join page, but it means an invite link is a small leak of who is in the group. A claim link also shows the saved seat's first name and its masked email. - **A placeholder's name and masked email are visible to its group.** The full address is readable by no client; the person who typed it in knows it. -- **Quick polls are open to anyone with the code until they expire** ([ADR 22](adr/0022-quick-polls-without-accounts.md)). Anyone can make one (5 an hour per client, 200 an hour in all); anyone with the code sees every answer's name and times and can add one answer per browser up to the poll's cap of 15. The per client limit keys on the first `x-forwarded-for` entry, which a client can set itself, so the global limit is the real backstop. Only the creator token closes or deletes a poll; the hourly purge deletes it once expired. +- **Quick polls are open to anyone with the code until they expire** ([ADR 22](adr/0022-quick-polls-without-accounts.md)). Anyone can make one (5 an hour per client, 200 an hour in all); anyone with the code sees every answer's name and times and can add one answer per browser up to the poll's cap of 15. The per client limit keys on the first `x-forwarded-for` entry, which a client can set itself, so the global limit is the real backstop. Each browser makes its own answer token and the server keeps only its sha256: the token proves only "this browser wrote this answer", so a weak one puts nothing at risk but that browser's own answer. Only the creator token, which the server makes, closes or deletes a poll; the hourly purge deletes it once expired. - **Guest links are open doors until they close.** Anyone with the code can add names and times up to the link's cap, and the per link limits (20 new guests per 10 minutes, 60 saves per guest per hour) are counted in the database, not per IP. Organizers clean up with remove and turn off. The preview itself is a read and is not rate limited. - **Signing out elsewhere ends at the next request, not before.** "Sign out everywhere" and a password change delete every other session. The database then refuses those devices' tokens (`session_ended`, checked against `auth.sessions` in `private.check_request()`), and the app signs a device out when it sees that or when `getUser()` says the session is gone (on start, whenever the app comes back to the front, and at least every 30 seconds while it is on screen). Three paths do not check: Realtime keeps an open channel until the token expires (up to an hour, `jwt_expiry`), though each change it delivers makes the app refetch and so sign out; Storage downloads and edge functions accept the token until it expires. - **A fresh stolen session can change the password without the old one.** Within a day of signing in, Supabase sets a new password for the session alone; the Me page asks for the current password first, but the API does not unless the project turns on "require current password" (a dashboard setting, not in `config.toml`; the app already sends `current_password`). Older sessions need an emailed code (`secure_password_change`). Either way the account gets a "password changed" email. diff --git a/docs/testing.md b/docs/testing.md index 4ef8c23b..786c719f 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -118,7 +118,7 @@ Each file runs in its own transaction and rolls back, so tests do not leak into | `32_signed_out_sessions.test.sql` | `private.session_active` and the pre-request check: a token whose session was signed out is refused with `session_ended`, live sessions, other accounts, tokens without the claim and anon go through | | `33_expense_notice.test.sql` | a new expense's notification carries each recipient's `share_cents` and `paid_cents` (several payers, a payer outside the split, refunds) | | `35_request_keys.test.sql` | a save sent again with the same request id returns the first expense (`create_expense_v2`, `create_expense_with_attachments`) or payment (`settle_up_v3`), keys per person and kind, no key or a non uuid key saving each call, a refused try keeping no key, clients unable to read the keys | -| `36_quick_polls.test.sql` | quick polls: nobody reads or writes the tables, every create check, names on and off, seats and the cap, the creator token as answer token, each status in the preview, close, delete, the hourly purge, and the save and create rate limits | +| `36_quick_polls.test.sql` | quick polls: nobody reads or writes the tables, every create check, names on and off, answer tokens the browser makes (a resent first save keeps one seat), seats and the cap, the creator token as answer token, each status in the preview, close, delete, the hourly purge, and the save and create rate limits | Every table in `public` needs tests for both who can and who cannot read and write it. A new RPC needs tests for each error code it can raise. diff --git a/packages/api/src/quick-polls.test.ts b/packages/api/src/quick-polls.test.ts index f22b15f2..98879116 100644 --- a/packages/api/src/quick-polls.test.ts +++ b/packages/api/src/quick-polls.test.ts @@ -194,19 +194,24 @@ describe('quick poll writes', () => { ]) }) - it('saves an answer, sending empty strings for no name and no token', async () => { + it('saves an answer under the token given, sending an empty string for no name', async () => { const fake = fakeSupabase().respond('rpc:set_quick_poll_availability', { - data: [{ answer_token: 'fresh', saved: 1 }], + data: [{ answer_token: 'browser-made-token', saved: 1 }], }) const slots = [{ slot_start: 's1', level: 'yes' as const }] expect( - await setQuickPollAvailability(fake.client, { code: 'c', name: null, token: null, slots }), - ).toEqual({ token: 'fresh', saved: 1 }) + await setQuickPollAvailability(fake.client, { + code: 'c', + name: null, + token: 'browser-made-token', + slots, + }), + ).toEqual({ token: 'browser-made-token', saved: 1 }) await setQuickPollAvailability(fake.client, { code: 'c', name: 'Ana', token: 'old', slots }) expect(fake.rpcArgs('set_quick_poll_availability')).toEqual([ - { code: 'c', name: '', token: '', slots }, + { code: 'c', name: '', token: 'browser-made-token', slots }, { code: 'c', name: 'Ana', token: 'old', slots }, ]) }) @@ -226,7 +231,7 @@ describe('quick poll writes', () => { .respond('rpc:set_quick_poll_availability', { error }) .respond('rpc:close_quick_poll', { error }) .respond('rpc:delete_quick_poll', { error }) - const answer = { code: 'c', name: 'A', token: null, slots: [] } + const answer = { code: 'c', name: 'A', token: 'browser-made-token', slots: [] } const creator = { code: 'c', creatorToken: 'secret' } for (const write of [ () => createQuickPoll(fake.client, input), diff --git a/packages/api/src/quick-polls.ts b/packages/api/src/quick-polls.ts index c9434683..06d66805 100644 --- a/packages/api/src/quick-polls.ts +++ b/packages/api/src/quick-polls.ts @@ -1,6 +1,7 @@ /** * Quick polls (ADR 22): availability polls anyone can make and answer without an account. Every - * call goes through an anon-callable RPC; the browser keeps the tokens they hand back. + * call goes through an anon-callable RPC; the browser keeps the creator token and the answer + * token it makes. */ import type { QuickPollSlotMinutes, QuickPollTtl, SlotGrid } from '@potluck/core' import { queryOptions } from '@tanstack/react-query' @@ -168,20 +169,20 @@ export async function createQuickPoll( } /** - * Adds or replaces the visitor's answer. With no token (or one the poll does not know) the server - * makes a new answer and returns its token; keep it to edit later. The creator passes their - * creator token and gets it back. + * Adds or replaces the visitor's answer. The browser makes its token (16 to 200 characters) and + * keeps it before the first save, then sends the same one every time: a token the poll does not + * know makes a new answer, a known one edits it, so a save resent after a lost reply never takes + * a second seat. The creator passes their creator token. Returns the token as sent. */ export async function setQuickPollAvailability( client: PotluckClient, - input: { code: string; name: string | null; token: string | null; slots: QuickPollSlot[] }, + input: { code: string; name: string | null; token: string; slots: QuickPollSlot[] }, ): Promise<{ token: string; saved: number }> { const { data, error } = await client.rpc('set_quick_poll_availability', { code: input.code, // Ignored when the poll does not ask for names. name: input.name ?? '', - // An empty token is one the poll does not know, so the server makes a new answer. - token: input.token ?? '', + token: input.token, slots: input.slots, }) if (error) fail(error) diff --git a/packages/i18n/src/de/quick-polls.ts b/packages/i18n/src/de/quick-polls.ts index 52a68388..b087111c 100644 --- a/packages/i18n/src/de/quick-polls.ts +++ b/packages/i18n/src/de/quick-polls.ts @@ -113,6 +113,8 @@ export const quickPolls = { invalid_quick_poll_ttl: 'Wähle, wie lange die Umfrage offen bleibt.', invalid_quick_poll_people: 'Eine Umfrage nimmt 2 bis 15 Personen.', invalid_quick_poll_name: 'Namen haben 1 bis 40 Zeichen.', + invalid_quick_poll_token: + 'Dieser Browser konnte die Antwort nicht speichern. Lade die Seite neu und versuch es noch mal.', invalid_slot: 'Einige dieser Zeiten liegen außerhalb der Umfrage.', invalid_slots: 'Diese Zeiten wurden nicht gespeichert. Noch mal versuchen?', duplicate_slot: 'Eine Zeit kommt doppelt vor. Noch mal versuchen?', diff --git a/packages/i18n/src/en/quick-polls.ts b/packages/i18n/src/en/quick-polls.ts index 3136dc04..c262cdde 100644 --- a/packages/i18n/src/en/quick-polls.ts +++ b/packages/i18n/src/en/quick-polls.ts @@ -109,6 +109,8 @@ export const quickPolls = { invalid_quick_poll_ttl: 'Pick how long the poll stays open.', invalid_quick_poll_people: 'A poll takes 2 to 15 people.', invalid_quick_poll_name: 'Names are 1 to 40 characters.', + invalid_quick_poll_token: + 'This browser could not save its answer. Reload the page and try again.', invalid_slot: 'Some of those times are outside the poll.', invalid_slots: 'Those times did not save. Try again?', duplicate_slot: 'A time showed up twice. Try again?', diff --git a/packages/i18n/src/es/quick-polls.ts b/packages/i18n/src/es/quick-polls.ts index 10705515..7ed73f73 100644 --- a/packages/i18n/src/es/quick-polls.ts +++ b/packages/i18n/src/es/quick-polls.ts @@ -112,6 +112,8 @@ export const quickPolls = { invalid_quick_poll_ttl: 'Elige cuánto tiempo queda abierta la encuesta.', invalid_quick_poll_people: 'Una encuesta admite de 2 a 15 personas.', invalid_quick_poll_name: 'Los nombres tienen de 1 a 40 caracteres.', + invalid_quick_poll_token: + 'Este navegador no pudo guardar tu respuesta. Recarga la página e inténtalo de nuevo.', invalid_slot: 'Algunas de esas horas están fuera de la encuesta.', invalid_slots: 'Esas horas no se guardaron. ¿Lo intentamos otra vez?', duplicate_slot: 'Una hora aparece dos veces. ¿Lo intentamos otra vez?', diff --git a/packages/i18n/src/fr/quick-polls.ts b/packages/i18n/src/fr/quick-polls.ts index 228ee515..fd7298ec 100644 --- a/packages/i18n/src/fr/quick-polls.ts +++ b/packages/i18n/src/fr/quick-polls.ts @@ -112,6 +112,8 @@ export const quickPolls = { invalid_quick_poll_ttl: 'Choisis combien de temps le sondage reste ouvert.', invalid_quick_poll_people: 'Un sondage accepte de 2 à 15 personnes.', invalid_quick_poll_name: 'Les noms font de 1 à 40 caractères.', + invalid_quick_poll_token: + "Ce navigateur n'a pas pu enregistrer ta réponse. Recharge la page et réessaie.", invalid_slot: 'Certains de ces horaires sont hors du sondage.', invalid_slots: "Ces horaires n'ont pas été enregistrés. On réessaie ?", duplicate_slot: 'Un horaire apparaît deux fois. On réessaie ?', diff --git a/packages/i18n/src/pt/quick-polls.ts b/packages/i18n/src/pt/quick-polls.ts index e517b539..17df9610 100644 --- a/packages/i18n/src/pt/quick-polls.ts +++ b/packages/i18n/src/pt/quick-polls.ts @@ -112,6 +112,8 @@ export const quickPolls = { invalid_quick_poll_ttl: 'Escolha por quanto tempo a enquete fica aberta.', invalid_quick_poll_people: 'Uma enquete aceita de 2 a 15 pessoas.', invalid_quick_poll_name: 'Nomes têm de 1 a 40 caracteres.', + invalid_quick_poll_token: + 'Este navegador não conseguiu salvar sua resposta. Recarregue a página e tente de novo.', invalid_slot: 'Alguns desses horários estão fora da enquete.', invalid_slots: 'Esses horários não foram salvos. Tentamos de novo?', duplicate_slot: 'Um horário aparece duas vezes. Tentamos de novo?', diff --git a/supabase/migrations/20261122232215_quick_polls.sql b/supabase/migrations/20261122232215_quick_polls.sql index 7c4c146c..3e45605d 100644 --- a/supabase/migrations/20261122232215_quick_polls.sql +++ b/supabase/migrations/20261122232215_quick_polls.sql @@ -5,7 +5,8 @@ -- quick_polls one row per poll: its code, grid, expiry and the sha256 of the -- creator's token (the browser keeps the token) -- quick_poll_answers one row per browser that answered, with a seat number (1, 2, --- 3...) and, when the poll asks for names, a name; a token hash too +-- 3...) and, when the poll asks for names, a name; plus the sha256 +-- of the token that browser made -- quick_poll_slots the slots each answer painted, same shape as public.availability -- private.quick_poll_creates when polls were made and by which client (sha256 of the first -- x-forwarded-for entry), kept an hour, for the create rate limit @@ -446,9 +447,12 @@ $$; revoke execute on function public.quick_poll_preview(text, text) from public; grant execute on function public.quick_poll_preview(text, text) to anon, authenticated, service_role; --- Adds or replaces an answer. A token this poll does not know makes a new answer, if there is a --- seat, and returns a fresh token for the browser to keep; a known token edits its answer. The --- creator's token (from create_quick_poll) makes the creator's answer under that same token. The +-- Adds or replaces an answer. The browser makes its own token (16 to 200 characters) before its +-- first save and sends it every time, so a save resent after a lost reply edits the answer it +-- made instead of taking a second seat. A token this poll does not know makes a new answer under +-- it, if there is a seat; a known token edits its answer; the creator's token (from +-- create_quick_poll) makes or edits the creator's answer. No token, or a malformed one, is +-- invalid_quick_poll_token. Only the sha256 is kept, and the token is handed back as given. The -- poll row lock serializes seats and the cap. -- Limits: names 1 to 40 characters once cleaned when the poll asks for names (ignored and stored -- as null when it does not), a new answer needs at least one slot, 60 saves per answer per hour, @@ -466,9 +470,11 @@ declare hashed bytea := private.quick_poll_token_hash(set_quick_poll_availability.token); clean_name text; parsed jsonb; - fresh_token text; n int; begin + if hashed is null then + raise exception using message = 'invalid_quick_poll_token', detail = 'The answer token is missing or not valid', errcode = '22023'; + end if; select * into poll from public.quick_polls q where q.code = set_quick_poll_availability.code for update; if poll.id is null then raise exception using message = 'quick_poll_not_found', detail = 'This poll is not valid', errcode = 'PT404'; @@ -502,10 +508,6 @@ begin if jsonb_array_length(parsed) = 0 then raise exception using message = 'quick_poll_slots_required', detail = 'Pick at least one time', errcode = '22023'; end if; - if hashed is distinct from poll.creator_token_hash then - fresh_token := private.random_code(24); - hashed := sha256(convert_to(fresh_token, 'UTF8')); - end if; -- Answers only ever go with their poll, so the next seat is never one used before. insert into public.quick_poll_answers (poll_id, seat, display_name, token_hash) values ( @@ -534,7 +536,7 @@ begin from jsonb_to_recordset(parsed) as s (slot_start timestamptz, level public.availability_level); get diagnostics n = row_count; - return query select coalesce(fresh_token, set_quick_poll_availability.token), n; + return query select set_quick_poll_availability.token, n; end; $$; diff --git a/supabase/schema/current.sql b/supabase/schema/current.sql index 5d3ebe1a..16285837 100644 --- a/supabase/schema/current.sql +++ b/supabase/schema/current.sql @@ -9888,9 +9888,11 @@ declare hashed bytea := private.quick_poll_token_hash(set_quick_poll_availability.token); clean_name text; parsed jsonb; - fresh_token text; n int; begin + if hashed is null then + raise exception using message = 'invalid_quick_poll_token', detail = 'The answer token is missing or not valid', errcode = '22023'; + end if; select * into poll from public.quick_polls q where q.code = set_quick_poll_availability.code for update; if poll.id is null then raise exception using message = 'quick_poll_not_found', detail = 'This poll is not valid', errcode = 'PT404'; @@ -9924,10 +9926,6 @@ begin if jsonb_array_length(parsed) = 0 then raise exception using message = 'quick_poll_slots_required', detail = 'Pick at least one time', errcode = '22023'; end if; - if hashed is distinct from poll.creator_token_hash then - fresh_token := private.random_code(24); - hashed := sha256(convert_to(fresh_token, 'UTF8')); - end if; -- Answers only ever go with their poll, so the next seat is never one used before. insert into public.quick_poll_answers (poll_id, seat, display_name, token_hash) values ( @@ -9956,7 +9954,7 @@ begin from jsonb_to_recordset(parsed) as s (slot_start timestamptz, level public.availability_level); get diagnostics n = row_count; - return query select coalesce(fresh_token, set_quick_poll_availability.token), n; + return query select set_quick_poll_availability.token, n; end; $$; diff --git a/supabase/tests/36_quick_polls.test.sql b/supabase/tests/36_quick_polls.test.sql index f8d8e7db..6c6bfed9 100644 --- a/supabase/tests/36_quick_polls.test.sql +++ b/supabase/tests/36_quick_polls.test.sql @@ -1,9 +1,10 @@ -- Quick polls (ADR 22): nobody reads or writes the tables directly; creating a poll and its --- checks; names on and off; seats and the people cap; the creator token doubling as the creator's --- answer token; the preview per status; closing, expiry and deleting; the hourly purge; and the --- save and create rate limits (the same limits as packages/core quick-polls). +-- checks; names on and off; answer tokens the browser makes (a resent first save keeps one seat); +-- seats and the people cap; the creator token doubling as the creator's answer token; the preview +-- per status; closing, expiry and deleting; the hourly purge; and the save and create rate limits +-- (the same limits as packages/core quick-polls). begin; -select plan(80); +select plan(84); select tests.create_user('alice'); @@ -181,37 +182,60 @@ select throws_ok( 'PT404', 'quick_poll_not_found', 'unknown codes are not found' ); select throws_ok( - format($$ select * from public.set_quick_poll_availability(%L, ' ', null, %L) $$, + format($$ select * from public.set_quick_poll_availability(%L, ' ', 'ana-made-this-token-1', %L) $$, pg_temp.code('names'), jsonb_build_array(pg_temp.slot(1, '10:00'))), '22023', 'invalid_quick_poll_name', 'a poll with names needs a name' ); select throws_ok( - format($$ select * from public.set_quick_poll_availability(%L, 'Ana', null, '[]') $$, pg_temp.code('names')), + format($$ select * from public.set_quick_poll_availability(%L, 'Ana', 'ana-made-this-token-1', '[]') $$, pg_temp.code('names')), '22023', 'quick_poll_slots_required', 'a new answer picks at least one time' ); select throws_ok( - format($$ select * from public.set_quick_poll_availability(%L, 'Ana', null, %L) $$, + format($$ select * from public.set_quick_poll_availability(%L, 'Ana', 'ana-made-this-token-1', %L) $$, pg_temp.code('names'), jsonb_build_array(pg_temp.slot(1, '12:00'))), '22023', 'invalid_slot', 'times outside the grid are refused' ); select throws_ok( - format($$ select * from public.set_quick_poll_availability(%L, 'Ana', null, '{"no": 1}') $$, pg_temp.code('names')), + format($$ select * from public.set_quick_poll_availability(%L, 'Ana', 'ana-made-this-token-1', '{"no": 1}') $$, pg_temp.code('names')), '22023', 'invalid_slots', 'slots are a list' ); +select throws_ok( + format($$ select * from public.set_quick_poll_availability(%L, 'Ana', null, %L) $$, + pg_temp.code('names'), jsonb_build_array(pg_temp.slot(1, '10:00'))), + '22023', 'invalid_quick_poll_token', 'a save needs a token' +); +select throws_ok( + format($$ select * from public.set_quick_poll_availability(%L, 'Ana', 'too-short', %L) $$, + pg_temp.code('names'), jsonb_build_array(pg_temp.slot(1, '10:00'))), + '22023', 'invalid_quick_poll_token', 'a token under 16 characters is refused' +); +-- Each browser makes its own token and keeps it before its first save. insert into tok select 'ana', s.answer_token -from public.set_quick_poll_availability(pg_temp.code('names'), 'Ana', null, +from public.set_quick_poll_availability(pg_temp.code('names'), 'Ana', 'ana-made-this-token-1', jsonb_build_array(pg_temp.slot(1, '10:00'), pg_temp.slot(1, '10:30', 'maybe'))) s; +select is(pg_temp.tok('ana'), 'ana-made-this-token-1', 'a new answer keeps the token its browser made'); +-- The reply to that first save was lost, so the browser sends it again with the same token. +select is( + (select s.saved from public.set_quick_poll_availability(pg_temp.code('names'), 'Ana', pg_temp.tok('ana'), + jsonb_build_array(pg_temp.slot(1, '10:00'), pg_temp.slot(1, '10:30', 'maybe'))) s), + 2, + 'the same first save sent again saves' +); +select is( + (select jsonb_array_length(answers) from public.quick_poll_preview(pg_temp.code('names'))), + 1, + 'and is still one answer in one seat' +); insert into tok select 'cy', s.answer_token from public.set_quick_poll_availability(pg_temp.code('names'), 'Cy', pg_temp.creator('names'), jsonb_build_array(pg_temp.slot(2, '11:00'))) s; insert into tok select 'ben', s.answer_token -from public.set_quick_poll_availability(pg_temp.code('names'), 'Ben', 'not-a-token-this-poll-knows', +from public.set_quick_poll_availability(pg_temp.code('names'), 'Ben', 'ben-made-this-token-1', jsonb_build_array(pg_temp.slot(2, '11:30'))) s; select is(pg_temp.tok('cy'), pg_temp.creator('names'), 'the creator answers under their creator token'); -select isnt(pg_temp.tok('ben'), 'not-a-token-this-poll-knows', 'an unknown token gets a fresh one'); -select ok(char_length(pg_temp.tok('ana')) >= 16, 'a new answer gets a long token'); +select is(pg_temp.tok('ben'), 'ben-made-this-token-1', 'another browser answers under its own token'); reset role; select results_eq( @@ -234,7 +258,7 @@ select is( 'a full poll still shows its answers' ); select throws_ok( - format($$ select * from public.set_quick_poll_availability(%L, 'Dee', null, %L) $$, + format($$ select * from public.set_quick_poll_availability(%L, 'Dee', 'dee-made-this-token-1', %L) $$, pg_temp.code('names'), jsonb_build_array(pg_temp.slot(1, '10:00'))), '23514', 'quick_poll_full', 'a full poll takes no new answers' ); @@ -265,12 +289,12 @@ select is( insert into polls select 'nameless', q.code, q.creator_token from public.create_quick_poll(pg_temp.payload('{"names_required": false, "max_people": 2, "slot_minutes": 60}')) q; select lives_ok( - format($$ insert into tok select 'n1', s.answer_token from public.set_quick_poll_availability(%L, null, null, %L) s $$, + format($$ insert into tok select 'n1', s.answer_token from public.set_quick_poll_availability(%L, null, 'n1-made-this-token-1', %L) s $$, pg_temp.code('nameless'), jsonb_build_array(pg_temp.slot(1, '10:00'))), 'a poll without names takes an answer with no name' ); select lives_ok( - format($$ insert into tok select 'n2', s.answer_token from public.set_quick_poll_availability(%L, 'Ignored', null, %L) s $$, + format($$ insert into tok select 'n2', s.answer_token from public.set_quick_poll_availability(%L, 'Ignored', 'n2-made-this-token-1', %L) s $$, pg_temp.code('nameless'), jsonb_build_array(pg_temp.slot(1, '11:00'))), 'and ignores a name it is given' ); @@ -353,7 +377,7 @@ select is( insert into polls select 'gone', q.code, q.creator_token from public.create_quick_poll(pg_temp.payload()) q; insert into tok select 'g1', s.answer_token -from public.set_quick_poll_availability(pg_temp.code('gone'), 'Gil', null, jsonb_build_array(pg_temp.slot(1, '10:00'))) s; +from public.set_quick_poll_availability(pg_temp.code('gone'), 'Gil', 'gil-made-this-token-1', jsonb_build_array(pg_temp.slot(1, '10:00'))) s; reset role; select tests.remember('gone', (select id from public.quick_polls where code = pg_temp.code('gone'))); select tests.login_anon(); @@ -408,7 +432,7 @@ select is( select tests.login_anon(); insert into tok select 'r1', s.answer_token -from public.set_quick_poll_availability(pg_temp.code('big'), 'Rae', null, jsonb_build_array(pg_temp.slot(1, '10:00'))) s; +from public.set_quick_poll_availability(pg_temp.code('big'), 'Rae', 'rae-made-this-token-1', jsonb_build_array(pg_temp.slot(1, '10:00'))) s; reset role; update public.quick_poll_answers set saves = 60 where token_hash = sha256(convert_to(pg_temp.tok('r1'), 'UTF8')); select tests.login_anon(); From df9a7a92710f3a9360376fcf2d47c6b3874f254d Mon Sep 17 00:00:00 2001 From: Musa Kaleem <131704022+Musa-Kal@users.noreply.github.com> Date: Sun, 22 Nov 2026 21:15:05 -0500 Subject: [PATCH 16/21] fix(web): keep the quick poll window while its first day is cleared or typed With maxDays, the first day handler pulled the last day back for every value it saw. Clearing the field threw a RangeError (addDays on an empty day), and typing a year by keyboard passed through days like 0002-06-02, which clamped the last day and then collapsed the window to one day. The pull back now waits for a real first day from today on; anything else passes through and leaves the last day alone, and the submit check refuses the window. The plan form, which has no maxDays, is unchanged. Co-authored-by: Ferrin <177692050+Ferrin-Y@users.noreply.github.com> Co-authored-by: noorelmosrati <182049385+noorelmosrati@users.noreply.github.com> --- apps/web/src/features/plans/window-fields.tsx | 9 +++++-- .../quick-polls/create-poll-page.test.tsx | 24 +++++++++++++++++++ 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/apps/web/src/features/plans/window-fields.tsx b/apps/web/src/features/plans/window-fields.tsx index a1f25a84..20b5b308 100644 --- a/apps/web/src/features/plans/window-fields.tsx +++ b/apps/web/src/features/plans/window-fields.tsx @@ -7,7 +7,9 @@ import { addDays, windowDays, type PollWindow, type WindowField } from './window * The date range and daily hours of a poll, shared by plans and quick polls. Each control's id is * `-` so a form can focus the first one with an error. With `maxDays`, the last * day cannot be picked more than that many days after the first, and moving the first day pulls - * the last one along. + * the last one along. That waits for a first day from `today` on: clearing the field gives '', and + * typing a year passes through days like 0002-06-02, and neither should move the last day (the + * form's submit check refuses a window that is not valid). */ export function WindowFields({ value, @@ -26,7 +28,10 @@ export function WindowFields({ idPrefix: string }) { const days = windowDays(value) - const lastDay = (start: string) => (maxDays ? addDays(start, maxDays - 1) : undefined) + const lastDay = (start: string) => + maxDays && start >= today && !Number.isNaN(Date.parse(start)) + ? addDays(start, maxDays - 1) + : undefined const hourOptions = Array.from({ length: 49 }, (_, i) => i * 30).map((m) => ({ value: String(m), label: formatMinuteOfDay(m), diff --git a/apps/web/src/features/quick-polls/create-poll-page.test.tsx b/apps/web/src/features/quick-polls/create-poll-page.test.tsx index e4105915..cb6985af 100644 --- a/apps/web/src/features/quick-polls/create-poll-page.test.tsx +++ b/apps/web/src/features/quick-polls/create-poll-page.test.tsx @@ -123,6 +123,30 @@ describe('CreatePollPage', () => { expect(last).toHaveAttribute('max', '2026-07-03') }) + it('leaves the last day alone while the first day is cleared', async () => { + await renderPage() + const first = screen.getByLabelText(t('events.create.windowFrom')) + const last = screen.getByLabelText(t('events.create.windowTo')) + fireEvent.change(first, { target: { value: '' } }) + expect(first).toHaveValue('') + expect(last).toHaveValue('2026-06-08') + submit() + expect(await screen.findByText(t('quickPolls.errors.invalid_quick_poll_window'))).toBeVisible() + expect(db().rpcArgs('create_quick_poll')).toEqual([]) + }) + + it('keeps the window while a year is typed into the first day', async () => { + await renderPage() + const first = screen.getByLabelText(t('events.create.windowFrom')) + const last = screen.getByLabelText(t('events.create.windowTo')) + // Typing 2026 by keyboard goes through each of these. + for (const day of ['0002-06-03', '0020-06-03', '0202-06-03', '2026-06-03']) { + fireEvent.change(first, { target: { value: day } }) + } + expect(last).toHaveValue('2026-06-08') + expect(screen.getByText(t('events.create.windowDays', { count: 6 }))).toBeInTheDocument() + }) + it('stops a window longer than two weeks before sending it', async () => { await renderPage() fireEvent.change(screen.getByLabelText(t('events.create.windowTo')), { From ed84a10c0941c6e14b55d39aa3409bdd9c855348 Mon Sep 17 00:00:00 2001 From: Musa Kaleem <131704022+Musa-Kal@users.noreply.github.com> Date: Sun, 22 Nov 2026 21:15:33 -0500 Subject: [PATCH 17/21] refactor(core): drop isQuickPollTtl, which nothing calls Co-authored-by: Ferrin <177692050+Ferrin-Y@users.noreply.github.com> Co-authored-by: noorelmosrati <182049385+noorelmosrati@users.noreply.github.com> --- packages/core/src/quick-polls/index.ts | 1 - packages/core/src/quick-polls/limits.test.ts | 8 -------- packages/core/src/quick-polls/limits.ts | 4 ---- 3 files changed, 13 deletions(-) diff --git a/packages/core/src/quick-polls/index.ts b/packages/core/src/quick-polls/index.ts index 09a709be..5277e1b2 100644 --- a/packages/core/src/quick-polls/index.ts +++ b/packages/core/src/quick-polls/index.ts @@ -1,5 +1,4 @@ export { - isQuickPollTtl, QUICK_POLL_DEFAULT_PEOPLE, QUICK_POLL_MAX_DAYS, QUICK_POLL_MAX_PEOPLE, diff --git a/packages/core/src/quick-polls/limits.test.ts b/packages/core/src/quick-polls/limits.test.ts index bb990e95..4b65a57d 100644 --- a/packages/core/src/quick-polls/limits.test.ts +++ b/packages/core/src/quick-polls/limits.test.ts @@ -1,6 +1,5 @@ import { describe, expect, it } from 'vitest' import { - isQuickPollTtl, QUICK_POLL_DEFAULT_PEOPLE, QUICK_POLL_MAX_PEOPLE, QUICK_POLL_MIN_PEOPLE, @@ -15,13 +14,6 @@ describe('quick poll limits', () => { ]) }) - it('lasts 24 hours or 7 days', () => { - expect(isQuickPollTtl('24h')).toBe(true) - expect(isQuickPollTtl('7d')).toBe(true) - expect(isQuickPollTtl('30d')).toBe(false) - expect(isQuickPollTtl(null)).toBe(false) - }) - it('covers 1 to 14 days, both ends included', () => { expect(quickPollWindowFits('2026-06-01', '2026-06-01')).toBe(true) expect(quickPollWindowFits('2026-06-01', '2026-06-14')).toBe(true) diff --git a/packages/core/src/quick-polls/limits.ts b/packages/core/src/quick-polls/limits.ts index d6939fe4..c1dc63f2 100644 --- a/packages/core/src/quick-polls/limits.ts +++ b/packages/core/src/quick-polls/limits.ts @@ -14,10 +14,6 @@ export type QuickPollTtl = (typeof QUICK_POLL_TTLS)[number] export const QUICK_POLL_SLOT_MINUTES = [30, 60] as const export type QuickPollSlotMinutes = (typeof QUICK_POLL_SLOT_MINUTES)[number] -export function isQuickPollTtl(value: unknown): value is QuickPollTtl { - return QUICK_POLL_TTLS.some((ttl) => ttl === value) -} - /** True when the days from `windowStart` to `windowEnd` (`YYYY-MM-DD`, both included) fit a poll. */ export function quickPollWindowFits(windowStart: string, windowEnd: string): boolean { const days = From 56246868be102e16c87cc179ad5745f437179e30 Mon Sep 17 00:00:00 2001 From: Musa Kaleem <131704022+Musa-Kal@users.noreply.github.com> Date: Sun, 22 Nov 2026 21:31:26 -0500 Subject: [PATCH 18/21] review: keep made poll token in page state so refetches carry it --- .../features/quick-polls/poll-page.test.tsx | 51 +++++++++++++++++++ .../src/features/quick-polls/poll-page.tsx | 21 +++++--- 2 files changed, 65 insertions(+), 7 deletions(-) diff --git a/apps/web/src/features/quick-polls/poll-page.test.tsx b/apps/web/src/features/quick-polls/poll-page.test.tsx index 54284a05..ca6c2a0f 100644 --- a/apps/web/src/features/quick-polls/poll-page.test.tsx +++ b/apps/web/src/features/quick-polls/poll-page.test.tsx @@ -362,6 +362,57 @@ describe('PollPage', () => { expect(db().rpcArgs('set_quick_poll_availability')[1]).toEqual(first) }) + it('keeps the form for a retry when the last seat was saved but the reply was lost', async () => { + // The server as ADR 22 has it: the last seat reads `full` to anyone but the people in it. + let stored = false + const cy = { seat: 2, name: 'Cy', slots: [{ slot_start: at('19:00'), level: 'yes' }] } + db() + .respond('rpc:quick_poll_preview', (call) => { + const { token } = (call as { args: { token?: string } }).args + if (!stored) return { data: [{ ...open, max_people: 2 }] } + const mine = token !== undefined + return { + data: [ + { + ...open, + max_people: 2, + status: mine ? 'open' : 'full', + answers: [ana, { ...cy, mine }], + }, + ], + } + }) + .respond( + 'rpc:set_quick_poll_availability', + () => { + stored = true + return { error: { message: 'TypeError: Failed to fetch' } } + }, + { data: [{ answer_token: 'ignored', saved: 1 }] }, + ) + const { queryClient } = renderPage() + fireEvent.change(await screen.findByLabelText(t('quickPolls.page.nameLabel')), { + target: { value: 'Cy' }, + }) + paint(slot('19:00')) + fireEvent.click(screen.getByRole('button', { name: t('quickPolls.page.submit') })) + expect(await screen.findByRole('alert')).toBeVisible() + const first = db().rpcArgs('set_quick_poll_availability')[0] as { token: string } + + await queryClient.invalidateQueries() + + expect( + await screen.findByText(t('quickPolls.page.answered', { count: 2, max: 2 })), + ).toBeVisible() + expect( + screen.queryByRole('heading', { name: t('quickPolls.page.fullTitle') }), + ).not.toBeInTheDocument() + expect(cell(slot('19:00'))).toHaveAttribute('aria-selected', 'true') + fireEvent.click(screen.getByRole('button', { name: t('quickPolls.page.update') })) + expect(await screen.findByText(t('quickPolls.page.sentTitle', { name: 'Cy' }))).toBeVisible() + expect(db().rpcArgs('set_quick_poll_availability')[1]).toEqual(first) + }) + it('words other save errors in place', async () => { db() .respond('rpc:quick_poll_preview', { data: [open] }) diff --git a/apps/web/src/features/quick-polls/poll-page.tsx b/apps/web/src/features/quick-polls/poll-page.tsx index 89663215..3bf96706 100644 --- a/apps/web/src/features/quick-polls/poll-page.tsx +++ b/apps/web/src/features/quick-polls/poll-page.tsx @@ -62,7 +62,8 @@ export function PollPage({ code }: { code: string }) { const [memory, setMemory] = useState(() => pollMemory.read(code)) // Painted or typed but not saved: if the poll stops taking answers meanwhile, the page says so. const [unsaved, setUnsaved] = useState(false) - // The first save keeps a new token, which changes the query key; keep showing the poll meanwhile. + // A new visitor's token is kept as their first save goes out, which changes the query key; keep + // showing the poll meanwhile. const preview = useQuery({ ...quickPollQueries.preview(supabase, code, memory?.token ?? null), placeholderData: (previous) => previous, @@ -129,6 +130,7 @@ export function PollPage({ code }: { code: string }) { view={view} memory={memory} unsaved={unsaved} + onToken={setMemory} onSaved={(next) => { setUnsaved(false) setMemory(next) @@ -164,6 +166,7 @@ function Poll({ view, memory, unsaved, + onToken, onSaved, onDirty, onDiscarded, @@ -172,6 +175,7 @@ function Poll({ view: LivePoll memory: PollMemory | null unsaved: boolean + onToken: (memory: PollMemory) => void onSaved: (memory: PollMemory) => void onDirty: () => void onDiscarded: () => void @@ -298,6 +302,7 @@ function Poll({ } : undefined } + onToken={onToken} onSaved={(next) => { onSaved(next) setMode('viewing') @@ -367,6 +372,7 @@ function AnswerForm({ title, memory, onCancel, + onToken, onSaved, onDirty, onStopped, @@ -377,6 +383,7 @@ function AnswerForm({ title: string memory: PollMemory | null onCancel?: () => void + onToken: (memory: PollMemory) => void onSaved: (memory: PollMemory) => void onDirty: () => void onStopped: () => void @@ -394,8 +401,6 @@ function AnswerForm({ const [nameError, setNameError] = useState(null) const [formError, setFormError] = useState(null) const nameRef = useRef(null) - // The token a new visitor made for their first save, for when storage is blocked. - const madeToken = useRef(null) const cleanName = cleanGuestName(name) const save = useMutation({ @@ -447,12 +452,14 @@ function AnswerForm({ return } // A new visitor makes their token and keeps it before the first save goes out, so a retry - // after a lost reply (or a reload) sends the same one and edits that answer, not a second. - let token = memory?.token ?? madeToken.current + // after a lost reply (or a reload) sends the same one and edits that answer, not a second, + // and every refresh meanwhile asks for the poll as that visitor. + let token = memory?.token if (!token) { token = newRequestId() - madeToken.current = token - pollMemory.write(code, { token, name: poll.namesRequired ? cleanName : '' }) + const made = { token, name: poll.namesRequired ? cleanName : '' } + pollMemory.write(code, made) + onToken(made) } save.mutate(token) } From a4a72d0ecb17edd52b857254732ea040b276c13b Mon Sep 17 00:00:00 2001 From: Musa Kaleem <131704022+Musa-Kal@users.noreply.github.com> Date: Sun, 22 Nov 2026 21:38:22 -0500 Subject: [PATCH 19/21] review: keep poll on screen and read fresh after a first save --- .../features/quick-polls/poll-page.test.tsx | 121 ++++++++++++++++++ .../src/features/quick-polls/poll-page.tsx | 22 ++-- 2 files changed, 135 insertions(+), 8 deletions(-) diff --git a/apps/web/src/features/quick-polls/poll-page.test.tsx b/apps/web/src/features/quick-polls/poll-page.test.tsx index ca6c2a0f..99d6d02a 100644 --- a/apps/web/src/features/quick-polls/poll-page.test.tsx +++ b/apps/web/src/features/quick-polls/poll-page.test.tsx @@ -58,6 +58,37 @@ function paint(s: string) { fireEvent.pointerUp(screen.getByRole('grid', { name: /^Your times for/ }), { pointerId: 1 }) } +/** + * A slow network for one poll read: once armed, the next `quick_poll_preview` call is held back + * and, when released, answers with `stale` (the poll as it was when the read went out). + */ +function slowPreview(stale: unknown) { + const client = db().client as unknown as { rpc: (name: string, args?: unknown) => unknown } + const real = client.rpc.bind(client) + let armed = false + let held = 0 + let release = () => {} + const gate = new Promise((resolve) => { + release = resolve + }) + vi.spyOn(client, 'rpc').mockImplementation((name, args) => { + if (name !== 'quick_poll_preview' || !armed) return real(name, args) + armed = false + held += 1 + return { + then: (onFulfilled?: (v: unknown) => unknown, onRejected?: (e: unknown) => unknown) => + gate.then(() => ({ data: [stale], error: null })).then(onFulfilled, onRejected), + } + }) + return { + arm: () => { + armed = true + }, + held: () => held, + release, + } +} + function renderPage(code = 'poll123') { return renderWithProviders( <> @@ -413,6 +444,96 @@ describe('PollPage', () => { expect(db().rpcArgs('set_quick_poll_availability')[1]).toEqual(first) }) + it('keeps the form and its times when nothing gets through after the first send', async () => { + const offline = { error: { message: 'TypeError: Failed to fetch' } } + db() + .respond('rpc:quick_poll_preview', { data: [open] }, offline) + .respond('rpc:set_quick_poll_availability', offline) + const { queryClient } = renderPage() + fireEvent.change(await screen.findByLabelText(t('quickPolls.page.nameLabel')), { + target: { value: 'Cy' }, + }) + paint(slot('19:00')) + fireEvent.click(screen.getByRole('button', { name: t('quickPolls.page.submit') })) + expect(await screen.findByRole('alert')).toBeVisible() + + // The refresh that follows the send tries three times before it gives up. + await waitFor(() => expect(db().rpcArgs('quick_poll_preview')).toHaveLength(4), { + timeout: 10_000, + }) + await waitFor(() => expect(queryClient.isFetching()).toBe(0)) + + expect(screen.getByRole('heading', { level: 1, name: 'Board games' })).toBeVisible() + expect(cell(slot('19:00'))).toHaveAttribute('aria-selected', 'true') + expect(screen.getByLabelText(t('quickPolls.page.nameLabel'))).toHaveValue('Cy') + expect(screen.queryByText(t('quickPolls.page.loadFailedTitle'))).not.toBeInTheDocument() + }, 15_000) + + it('shows a first answer as sent though a slower read left before it was saved', async () => { + const cy = { + seat: 2, + name: 'Cy', + mine: true, + slots: [{ slot_start: at('19:00'), level: 'yes' }], + } + let stored = false + db() + .respond('rpc:quick_poll_preview', () => ({ + data: [stored ? { ...open, answers: [ana, cy] } : open], + })) + .respond('rpc:set_quick_poll_availability', () => { + stored = true + return { data: [{ answer_token: 'ignored', saved: 1 }] } + }) + renderPage() + fireEvent.change(await screen.findByLabelText(t('quickPolls.page.nameLabel')), { + target: { value: 'Cy' }, + }) + paint(slot('19:00')) + const slow = slowPreview(open) + slow.arm() + fireEvent.click(screen.getByRole('button', { name: t('quickPolls.page.submit') })) + + expect(await screen.findByText(t('quickPolls.page.sentTitle', { name: 'Cy' }))).toBeVisible() + expect(slow.held()).toBe(1) + slow.release() + await Promise.resolve() + expect(screen.getByText(t('quickPolls.page.sentTitle', { name: 'Cy' }))).toBeVisible() + expect(screen.getByText(t('quickPolls.page.answered', { count: 2, max: 10 }))).toBeVisible() + }) + + it('shows an edit as saved though a slower refresh left before it', async () => { + pollMemory.write('poll123', { token: 'tok-ana', name: 'Ana' }) + const before = { ...open, answers: [{ ...ana, mine: true }] } + const after = { + ...open, + answers: [ + { ...ana, mine: true, slots: [...ana.slots, { slot_start: at('19:00'), level: 'yes' }] }, + ], + } + let stored = false + db() + .respond('rpc:quick_poll_preview', () => ({ data: [stored ? after : before] })) + .respond('rpc:set_quick_poll_availability', () => { + stored = true + return { data: [{ answer_token: 'ignored', saved: 3 }] } + }) + const { queryClient } = renderPage() + fireEvent.click(await screen.findByRole('button', { name: t('quickPolls.page.edit') })) + paint(slot('19:00')) + const slow = slowPreview(before) + slow.arm() + void queryClient.invalidateQueries() + await waitFor(() => expect(slow.held()).toBe(1)) + fireEvent.click(screen.getByRole('button', { name: t('quickPolls.page.update') })) + + expect(await screen.findByText(t('quickPolls.page.sentTitle', { name: 'Ana' }))).toBeVisible() + slow.release() + await Promise.resolve() + fireEvent.click(screen.getByRole('button', { name: t('quickPolls.page.edit') })) + expect(cell(slot('19:00'))).toHaveAttribute('aria-selected', 'true') + }) + it('words other save errors in place', async () => { db() .respond('rpc:quick_poll_preview', { data: [open] }) diff --git a/apps/web/src/features/quick-polls/poll-page.tsx b/apps/web/src/features/quick-polls/poll-page.tsx index 3bf96706..fbd84f61 100644 --- a/apps/web/src/features/quick-polls/poll-page.tsx +++ b/apps/web/src/features/quick-polls/poll-page.tsx @@ -62,11 +62,9 @@ export function PollPage({ code }: { code: string }) { const [memory, setMemory] = useState(() => pollMemory.read(code)) // Painted or typed but not saved: if the poll stops taking answers meanwhile, the page says so. const [unsaved, setUnsaved] = useState(false) - // A new visitor's token is kept as their first save goes out, which changes the query key; keep - // showing the poll meanwhile. + const queryClient = useQueryClient() const preview = useQuery({ ...quickPollQueries.preview(supabase, code, memory?.token ?? null), - placeholderData: (previous) => previous, refetchInterval: REFRESH_MS, refetchOnWindowFocus: 'always', }) @@ -130,7 +128,15 @@ export function PollPage({ code }: { code: string }) { view={view} memory={memory} unsaved={unsaved} - onToken={setMemory} + onToken={(made) => { + // The token changes the query key: the poll on screen goes with it, so it stays up + // whatever becomes of the next refresh. + queryClient.setQueryData( + quickPollQueries.preview(supabase, code, made.token).queryKey, + view, + ) + setMemory(made) + }} onSaved={(next) => { setUnsaved(false) setMemory(next) @@ -415,11 +421,11 @@ function AnswerForm({ const next = { token, name: poll.namesRequired ? cleanName : '' } pollMemory.write(code, next) // Load the poll with the answer in it before leaving the form, so "Sent" has it to show. + // A refresh already on its way may have read the poll before the save: drop it. + const query = quickPollQueries.preview(supabase, code, next.token) + await queryClient.cancelQueries({ queryKey: query.queryKey, exact: true }) try { - await queryClient.fetchQuery({ - ...quickPollQueries.preview(supabase, code, next.token), - staleTime: 0, - }) + await queryClient.fetchQuery({ ...query, staleTime: 0 }) } catch { // Saved all the same; the next refresh shows it. } From 9e2a166a9710f3ae8ee498f9270af3e8fbe701f1 Mon Sep 17 00:00:00 2001 From: Musa Kaleem <131704022+Musa-Kal@users.noreply.github.com> Date: Sun, 22 Nov 2026 21:52:15 -0500 Subject: [PATCH 20/21] document: docs: list quick polls in the README features --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 77d71ada..304a8dfe 100644 --- a/README.md +++ b/README.md @@ -25,6 +25,7 @@ Live at https://potluck.fermulate.com (user guide at https://docs.potluck.fermul - Ranked best times, with who can and cannot make each one - Lock in a time, RSVP, and get reminders the day before - Personal calendar feed (`.ics`) for every plan you are part of +- Quick polls: share an availability link that up to 15 people answer without an account **Everywhere** From 714390d4d8c733f1ddffcda8a7dcd739ddcbcefa Mon Sep 17 00:00:00 2001 From: Musa Kaleem <131704022+Musa-Kal@users.noreply.github.com> Date: Sun, 22 Nov 2026 21:54:53 -0500 Subject: [PATCH 21/21] document: docs: name quick poll routes as signed out in web AGENTS --- apps/web/AGENTS.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md index d786d89a..114eea6e 100644 --- a/apps/web/AGENTS.md +++ b/apps/web/AGENTS.md @@ -18,8 +18,8 @@ Per-feature notes (payers and refunds, repeating expenses, language, two-step si a validator returns every key, `undefined` when dropped, or the raw value shows through), no feature imports beyond the screen. A `loader` may call `prefetch.()` from `src/lib/prefetch.ts` and must not await it. -- `/a/$code` (guest links) is signed out. `/` is prerendered (`prerender-landing.ts`): nothing on the - landing page may touch `window` during render. +- `/a/$code` (guest links), `/poll` and `/p/$code` (quick polls) are signed out. `/` is prerendered + (`prerender-landing.ts`): nothing on the landing page may touch `window` during render. - Server data goes through `@potluck/api` functions and `queryOptions`; never `supabase.from()` in a component. - Realtime: subscribe with `useRealtime` / `useBatchedInvalidate` (`src/lib/realtime.ts`) and invalidate query keys; never patch the cache from the payload.