Files
CatoandClaude Opus 5.5 7e37e20616 fix: invitations that work (and are safe), one project payment section, AI fill keeps your edits, events on their own clock (#1262)
* fix(wallets): an extended public key never lands in a public address column

Linking an xpub wallet copied the key into the entity's bitcoin_address,
which public pages render as a payable address. A key on a public page
reveals every address the wallet will ever derive, and wallets reject it.
The selector now leaves the column empty (payers get a fresh address from
the linked wallet), and the entity schemas refuse a key server-side so the
Cat and the API cannot write one either.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BQdyreKqCfy8iwRBRUVm39

* fix(create): AI fill never undoes an edit, a template keeps what was typed, success says live when it is live

- handleAIPrefill merged the whole echoed snapshot, so a field typed while
  the AI was thinking went back to its old value. It now applies only the
  fields the AI changed, and skips any the person edited since the send.
- A template pick (Previous → template) replaced the whole form. On create a
  dirty form now takes template values only for untouched fields.
- The success screen called every new item a draft and offered Publish Now,
  which 400s on an already-live assistant, circle or active wishlist. It now
  reads the created row: live items say so and link to themselves.
- A new group linked to the literal /groups/[slug]. One fillUrlTemplate
  fills every placeholder for both the success screen and the redirect.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BQdyreKqCfy8iwRBRUVm39

* fix(dates): real date pickers, events on their own clock, availability names its zone

- 'date' fields fell through to a text box: no picker, and edit forms showed
  the raw stored timestamp. They are date inputs now; events get a
  datetime-local input instead of 'Format: YYYY-MM-DDTHH:mm' text.
- Events defaulted to UTC, so a creator in Zurich typing 19:00 published
  21:00. A new event starts on the browser's zone, picked from a list of
  real zones; stored instants and template defaults are shown as that zone's
  wall time, so an edit cannot keep a stray +00:00 and move the night.
- The availability editor dropped the schedule's zone on every change and
  the public page printed hours with no clock. The zone is kept (the
  browser's for a new schedule) and shown: '09:00–17:00 (Zurich time)'.
- Bookings send the booker's zone instead of being stored as UTC.
- A wishlist's event date read a day early west of Greenwich.
- zoneLabel moves to utils/timezone (re-exported from domain/events/time).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BQdyreKqCfy8iwRBRUVm39

* fix(projects): one payment section — a project's own address becomes its linked wallet

The project page rendered a second payment box from the legacy
projects.bitcoin_address, beside the shared section that never reads it:
the page could show one address and pay another, a project whose owner had
no wallet showed a pay button that could not pay, and the box claimed the
address was 'verified and monitored'.

- Migration: each project's legacy address (on-chain, Lightning, or an xpub)
  becomes a wallet linked to that project, which payment resolution already
  prefers. Skips projects with an explicit link, group-owned projects and
  unclaimed owners; per-row savepoints so one odd row cannot abort a
  deploy; idempotent. Verified against Postgres 16.
- ProjectDonationSection, BitcoinPaymentButton and useProjectDonation are
  gone; ProjectFavoriteButton keeps the favourite (neutral, not error red).
  Wishlist tiers move beside the payment section.
- The floating mobile 'Support' button scrolled to an element that only
  existed on legacy-address projects; it targets #pay.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BQdyreKqCfy8iwRBRUVm39

* fix(groups): invitations reach the invitee, can be accepted, and only by them

Three implementations wrote group_invitations and none worked end to end:
- Accepting inserted into group_members as the invitee, which that table's
  policy forbids to non-admins, so no invitation could be accepted.
- Nobody was told: no notification type existed, and the only live writer
  (the Cat) did a raw insert with no admin, member or duplicate checks.
- Security: 'Token invitations are viewable' let anyone read pending link
  invitations, and accept_group_invitation (SECURITY DEFINER, granted to
  anon) skipped its owner check for them — anyone could join such a group.

Now:
- Migration: drop that policy; both answer functions require the invitation
  to name the caller, lock the row, pin search_path and are not callable by
  anon; group_invite joins the notification type CHECK. Verified on Postgres
  16 (stranger refused, invitee joins once, anon cannot execute).
- The domain answers through those functions, notifies the invitee on
  create, and is the one implementation: the Cat uses it, the dead browser
  copy is removed. Link/e-mail invitations (undeliverable, 404 link) are no
  longer offered.
- /dashboard/invitations/[id]: the invitee sees who invited them into what,
  and joins or declines — a private group is unreadable on its own page to
  someone not yet a member.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BQdyreKqCfy8iwRBRUVm39

* fix(groups): 'Invite' invites — nobody is added to a group without saying yes

The member dialog's Invite button called addMember and put the person in
the group outright, unasked. It now sends an invitation (notification +
answer page), shows who is already invited, and says they join once they
accept.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BQdyreKqCfy8iwRBRUVm39

* fix(search): one escape for search terms — commas and brackets no longer rewrite the filter

A dozen copies of term.replace(/[%_]/g, ...) fed user text into PostgREST
.or('a.ilike.%x%,b.ilike.%x%') filters. None escaped LIKE's own backslash,
and none quoted the value, so a comma in a search ('Smith, J') ended the
condition and parentheses opened a group the caller never wrote.

lib/db/likePattern: escapeLike, containsPattern for .ilike(), and ilikeAny
for .or(), which double-quotes the value as PostgREST reads it. Every copy
now uses it; sanitizeQuery is gone. The profile search's in-memory city
filter compared against the escaped term and missed cities with _ or %.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BQdyreKqCfy8iwRBRUVm39

* refactor(create): date inputs in their own field component; app locale for wall time

FormField went over the 300-line component limit with the date and
datetime cases; they move to fields/DateInputs, and a redundant fragment
around the textarea goes. instantToWallTime reads numeric parts in
APP_LOCALE, as check:app-locale requires.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BQdyreKqCfy8iwRBRUVm39

* refactor(create): one Pay-into group for every entity that receives money

Seven configs carried their own copy of the wallet group (two ids, two
shapes). walletFieldGroup() is the one definition; tables that still have
address columns opt into declaring them, which a wizard needs to place the
group on the right step — a group with no fields shows on every step.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BQdyreKqCfy8iwRBRUVm39

* refactor(bitcoin): one explorer link builder; the unused bitcoin service goes

Explorer links were built by hand in three places — two on mempool.space,
one on blockstream.info — and none followed NEXT_PUBLIC_BITCOIN_NETWORK.
lib/bitcoin/explorer builds them all. src/services/bitcoin/index.ts (347
lines, no importers) is removed and the docs that named it point at the
modules that do the work.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BQdyreKqCfy8iwRBRUVm39

* fix(a11y): a button-styled link is one control, not a button inside a link

94 places wrapped <Button> in <Link>: a <button> inside an <a> — invalid
HTML, two tab stops for one action, announced twice. <Button href> already
renders the link itself, but dropped aria-label, title, id and disabled,
which is why callers avoided it. It now carries them (a disabled link is
announced and inert) and passes onClick through.

52 sites converted mechanically (plain href on the link, no handler on the
button); 42 put a class or target on the outer link and need a look each,
held by a ratchet test that may only fall. The signed-out purchase line no
longer promises 'a Lightning invoice' — an xpub wallet issues a fresh
on-chain address.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BQdyreKqCfy8iwRBRUVm39

* refactor(bitcoin): one address-balance fetcher — refresh reports rate limits and is never stale

Three fetchers read an address balance. services/blockchain (used by the
wallet and project refresh) had no timeout, threw errors that matched none
of the codes its caller maps, and was cached by Next for five minutes, so
'refresh' could return the old number. The treasury's had no timeout and
counted confirmed funds only. lib/bitcoin/addressBalance is the one: timeout,
RATE_LIMITED / API_ERROR_<status> codes, confirmed plus unconfirmed, no
cache, testnet-aware. services/blockchain.ts is removed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BQdyreKqCfy8iwRBRUVm39

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-10-07 10:30:40 -07:00

108 lines
3.8 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* Weekly availability for bookable entities (services).
*
* Mirrors the existing `availability_schedule` jsonb shape — the
* AvailabilitySchedule interface in domain/commerce/service.ts and the Zod in
* lib/validation/commerce.ts: a set of available `days` + one or more `hours`
* ranges that apply to those days. This module is the shared client-side type +
* display/parse helpers so the editor and public display agree on the shape.
*/
import { DAYS_OF_WEEK, type DayOfWeek } from '@/config/schedule';
import { isValidTimeZone, zoneLabel } from '@/utils/timezone';
export interface AvailabilityHours {
start: string; // "HH:MM" 24h
end: string; // "HH:MM" 24h
}
export interface AvailabilitySchedule {
days?: DayOfWeek[];
hours?: AvailabilityHours[];
timezone?: string;
}
/** Day metadata in week order, with short labels for compact display. */
export const WEEKDAYS: Array<{ key: DayOfWeek; label: string; short: string }> = [
{ key: 'monday', label: 'Monday', short: 'Mon' },
{ key: 'tuesday', label: 'Tuesday', short: 'Tue' },
{ key: 'wednesday', label: 'Wednesday', short: 'Wed' },
{ key: 'thursday', label: 'Thursday', short: 'Thu' },
{ key: 'friday', label: 'Friday', short: 'Fri' },
{ key: 'saturday', label: 'Saturday', short: 'Sat' },
{ key: 'sunday', label: 'Sunday', short: 'Sun' },
];
const DAY_ORDER: Record<DayOfWeek, number> = WEEKDAYS.reduce(
(acc, d, i) => {
acc[d.key] = i;
return acc;
},
{} as Record<DayOfWeek, number>
);
/** Narrow unknown jsonb into a clean AvailabilitySchedule (defensive). */
export function parseAvailability(value: unknown): AvailabilitySchedule {
if (!value || typeof value !== 'object') {
return {};
}
const v = value as { days?: unknown; hours?: unknown; timezone?: unknown };
const days = Array.isArray(v.days)
? (v.days.filter(d => (DAYS_OF_WEEK as readonly string[]).includes(d as string)) as DayOfWeek[])
: undefined;
const hours = Array.isArray(v.hours)
? (v.hours.filter(
(h): h is AvailabilityHours =>
!!h &&
typeof h === 'object' &&
typeof (h as AvailabilityHours).start === 'string' &&
typeof (h as AvailabilityHours).end === 'string'
) as AvailabilityHours[])
: undefined;
return {
...(days && days.length ? { days } : {}),
...(hours && hours.length ? { hours } : {}),
...(typeof v.timezone === 'string' ? { timezone: v.timezone } : {}),
};
}
/** True when there's at least one day AND one hour range to show. */
export function hasAvailability(value: unknown): boolean {
const a = parseAvailability(value);
return !!a.days?.length && !!a.hours?.length;
}
const shortOf = (d: DayOfWeek) => WEEKDAYS.find(w => w.key === d)?.short ?? d;
/**
* Compact human-readable summary, e.g.:
* { days: ['monday','tuesday','wednesday','thursday','friday'], hours:[{09:00–17:00}] }
* → ["Mon–Fri", "09:00–17:00"]
* Consecutive days collapse into a range; otherwise they're comma-joined.
*/
export function formatAvailabilityLines(value: unknown): string[] {
const { days, hours, timezone } = parseAvailability(value);
if (!days?.length || !hours?.length) {
return [];
}
const sorted = [...days].sort((a, b) => DAY_ORDER[a] - DAY_ORDER[b]);
// Collapse consecutive days into ranges.
const groups: string[] = [];
let i = 0;
while (i < sorted.length) {
let j = i;
while (j + 1 < sorted.length && DAY_ORDER[sorted[j + 1]] === DAY_ORDER[sorted[j]] + 1) {
j++;
}
groups.push(i === j ? shortOf(sorted[i]) : `${shortOf(sorted[i])}–${shortOf(sorted[j])}`);
i = j + 1;
}
const daysLine = groups.join(', ');
// Name the clock: the provider's hours, not the reader's.
const clock = isValidTimeZone(timezone) ? ` (${zoneLabel(timezone)})` : '';
const hoursLine = hours.map(h => `${h.start}–${h.end}`).join(', ') + clock;
return [daysLine, hoursLine];
}