Files
heidi/lib/db/schema.ts

939 lines
40 KiB
TypeScript

// Accounts: the same tables in every fleet product (@bitbaum/accountkit/auth).
export * from "@bitbaum/accountkit/auth/schema";
import { bigint, boolean, date, index, integer, jsonb, pgTable, primaryKey, text, timestamp, uniqueIndex, uuid } from "drizzle-orm/pg-core";
import { DEFAULT_COURSE } from "../course/registry.ts";
/**
* Which course a row is about (`lib/course/registry.ts`).
*
* The default is the course every row written before the column existed
* belongs to, so adding it changed nothing about them. Code that writes a row
* names the course itself rather than leaning on the default.
*/
const course = () => text("course").notNull().default(DEFAULT_COURSE.id);
/**
* Study groups — the first thing in Heidi that outlives a browser tab.
*
* WHO A ROW BELONGS TO. `created_by`, `actor_id` and `author_id` hold the
* person's actor id, as text, with no foreign key: the account id for someone
* who registered here, or the OrangeCat actor id for someone whose first way
* in was OrangeCat (lib/auth — that keeps every row written before Heidi had
* accounts theirs). The account tables themselves come from
* @bitbaum/accountkit/auth, re-exported above.
*
* The consequence is that a display name has to be DENORMALISED onto the
* membership row. There is nothing to join to. It is captured at join time
* from the OIDC profile and may drift if someone renames themselves upstream;
* that is a real cost, accepted knowingly, and much cheaper than mirroring an
* identity provider.
*
* Heidi herself is NOT a member row. She participates in every group by
* construction, so storing her would be a row that must be written correctly
* for every group forever and can only ever say the same thing. She is
* composed into the threadkit participant list at read time instead.
*/
export const studyGroups = pgTable("study_groups", {
id: uuid("id").primaryKey().defaultRandom(),
name: text("name").notNull(),
/** OIDC `sub` of whoever made it. They see the thread from its start. */
createdBy: text("created_by").notNull(),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
/**
* The invite link's secret. Unguessable and rotatable — knowing a group's
* id must never be enough to join it, because ids travel in URLs and logs.
* Unique so a link resolves to exactly one group.
*/
inviteToken: text("invite_token").notNull().unique(),
/**
* The situation domain a TEAM works on (`care`, `everyday`, …), set by its
* organiser. Null for an ordinary study group. With a focus, members may
* choose to show the organiser their standing in those situations — see
* `lib/domain/teams/overview.ts`.
*/
focus: text("focus"),
});
export const groupMembers = pgTable(
"group_members",
{
groupId: uuid("group_id")
.notNull()
.references(() => studyGroups.id, { onDelete: "cascade" }),
/** OIDC `sub`. No foreign key: the person lives in OrangeCat, not here. */
actorId: text("actor_id").notNull(),
/** Denormalised from the OIDC profile — see the note above. */
displayName: text("display_name").notNull(),
joinedAt: timestamp("joined_at", { withTimezone: true }).notNull().defaultNow(),
/**
* Set rather than deleted. threadkit gates visibility on `leftAt`, so a
* departure has to be a fact with a time on it; a deleted row would make
* the messages they wrote authorless.
*/
leftAt: timestamp("left_at", { withTimezone: true }),
/**
* Whether this member shows the organiser their situation standings. OFF
* until they turn it on, per team, and only ever standings — never which
* lines or answers.
*/
sharesProgress: boolean("shares_progress").notNull().default(false),
},
(t) => [
primaryKey({ columns: [t.groupId, t.actorId] }),
// "Which groups am I in" is the portal's first query on every page load.
index("group_members_actor_idx").on(t.actorId),
],
);
export const groupMessages = pgTable(
"group_messages",
{
id: uuid("id").primaryKey().defaultRandom(),
groupId: uuid("group_id")
.notNull()
.references(() => studyGroups.id, { onDelete: "cascade" }),
/** An OIDC `sub`, or the assistant's fixed id. */
authorId: text("author_id").notNull(),
body: text("body").notNull(),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
/**
* Heidi's structured answer — glosses, suggestions, the model that wrote
* it — kept whole rather than shredded into columns.
*
* It is a rendering detail of one message, never queried across rows, and
* its shape is owned by `lib/domain/chat/types.ts`, which changes when the
* prompt changes. Columns would turn every prompt revision into a
* migration. Null for anything a human wrote.
*/
answer: jsonb("answer"),
},
// Every read is "this group's messages, oldest first".
(t) => [index("group_messages_group_created_idx").on(t.groupId, t.createdAt)],
);
/**
* A private conversation with Heidi, and its messages.
*
* NOT the group tables with one member. That was the tempting reuse and it
* fails on the two things that matter: `study_groups.invite_token` is
* `NOT NULL UNIQUE` and is a CREDENTIAL, so every private chat would mint a
* joinable room key nobody asked for — and deletion means the opposite in each
* case. A group departure sets `left_at` precisely so the messages someone
* wrote keep an author; deleting a conversation means destroying the text. One
* table cannot honour both.
*
* Same identity rule as everywhere else here: `actor_id` is the OIDC `sub`,
* stored as bare text with no foreign key, because the row it would point at
* lives in OrangeCat.
*/
export const conversations = pgTable(
"conversations",
{
id: uuid("id").primaryKey().defaultRandom(),
actorId: text("actor_id").notNull(),
/**
* Derived from the first message, never asked for. Every product that asks
* collects a thousand "Untitled"; what someone pasted is also the best
* possible label, because it is how they will recognise the thread later.
*/
title: text("title").notNull().default(""),
/**
* Which language Heidi explained in.
*
* On the conversation rather than the request: re-opening a six-month-old
* thread from a browser negotiated to French and having Heidi continue in
* French mid-conversation is a bug you only find in production.
*/
locale: text("locale").notNull(),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
/** Bumped on every message. The sidebar's sort key. */
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
/**
* A tombstone, and the messages are GONE.
*
* Deleting sets this and hard-deletes every `conversation_messages` row in
* the same transaction. A `deleted_at` that leaves the text sitting in the
* table forever is exactly the lie the privacy section would then have to
* tell. What the tombstone buys is worth keeping: a deleted id answers a
* stable 404 rather than one that might be a permissions bug, and the
* per-actor count survives a delete loop.
*/
deletedAt: timestamp("deleted_at", { withTimezone: true }),
},
(t) => [index("conversations_actor_updated_idx").on(t.actorId, t.updatedAt)],
);
export const conversationMessages = pgTable(
"conversation_messages",
{
id: uuid("id").primaryKey().defaultRandom(),
conversationId: uuid("conversation_id")
.notNull()
.references(() => conversations.id, { onDelete: "cascade" }),
/** An OIDC `sub`, or the assistant's fixed id. */
authorId: text("author_id").notNull(),
body: text("body").notNull(),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
/** Heidi's structured answer, kept whole. Null for anything a human wrote. */
answer: jsonb("answer"),
/**
* HOW MANY pictures rode along, never the pictures.
*
* Attachments are downscaled data URLs: they would be the largest rows in
* this database and the single most private artefact the product touches.
* The count is enough for a re-opened thread to say "2 pictures" honestly
* without Heidi holding them, and it is what keeps the privacy section
* short.
*/
imageCount: integer("image_count").notNull().default(0),
},
(t) => [index("conversation_messages_conversation_created_idx").on(t.conversationId, t.createdAt)],
);
/**
* Speaking rounds: the topics people propose, and the sittings they become.
*
* WHAT IS NOT HERE IS THE POINT.
*
* There is no audio table and no table of anybody's takes. A recording is
* measured in the browser (`domain/speaking/delivery.ts`); the numbers, and
* the learner's own write-up of what they said, are kept in their own
* localStorage. Neither the sound nor the text ever reaches this database. §10
* calls voice notes among the most private things a person owns, and the
* cheapest way to honour that is to never hold one. It is the call
* `image_count` already made for pictures, taken one step further because
* there is not even a count worth keeping.
*
* So what is stored here is only the SOCIAL half — who proposed what, who is
* coming, and when it sits. All of it is meant to be seen by the other people
* in the round, which is exactly the property the private half does not have.
*
* Same identity rule as everywhere else: an actor id is the OIDC `sub`, bare
* text, no foreign key, with the display name denormalised at write time.
*/
export const speakingTopics = pgTable(
"speaking_topics",
{
id: uuid("id").primaryKey().defaultRandom(),
title: text("title").notNull(),
/** One line of why it is worth an hour. */
pitch: text("pitch").notNull(),
proposedBy: text("proposed_by").notNull(),
proposerName: text("proposer_name").notNull(),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
},
(t) => [index("speaking_topics_created_idx").on(t.createdAt)],
);
/**
* "I would come to that."
*
* A row rather than a counter on the topic, because a count cannot answer the
* question the page actually asks — whether YOU already said yes — and a
* counter with no rows behind it can only ever go up.
*/
export const topicInterest = pgTable(
"topic_interest",
{
topicId: uuid("topic_id")
.notNull()
.references(() => speakingTopics.id, { onDelete: "cascade" }),
actorId: text("actor_id").notNull(),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
},
(t) => [primaryKey({ columns: [t.topicId, t.actorId] })],
);
export const speakingRounds = pgTable(
"speaking_rounds",
{
id: uuid("id").primaryKey().defaultRandom(),
/**
* The proposal it came from. Nullable, and `set null` on delete: a round
* people are coming to is a fact, and removing the topic it grew out of
* must not remove the meeting.
*/
topicId: uuid("topic_id").references(() => speakingTopics.id, { onDelete: "set null" }),
title: text("title").notNull(),
/** `webinar` or `circle` — see domain/speaking/types.ts. */
format: text("format").notNull(),
hostId: text("host_id").notNull(),
hostName: text("host_name").notNull(),
/**
* The first sitting, absolute. Every later one is COMPUTED from this plus
* the cadence and the zone, never stored — see domain/speaking/schedule.ts.
* A table of generated occurrences would have to be extended by a job
* nobody would notice had stopped.
*/
startsAt: timestamp("starts_at", { withTimezone: true }).notNull(),
durationMinutes: integer("duration_minutes").notNull(),
/** `once`, `weekly` or `fortnightly`. */
cadence: text("cadence").notNull(),
/**
* The zone the repeat is anchored in. Kept even though `starts_at` is
* absolute: "every Tuesday at 19:00" survives a daylight-saving change and
* an instant plus seven days does not.
*/
timeZone: text("time_zone").notNull(),
/** An https room somewhere else. Heidi carries no video. Validated on write. */
meetingUrl: text("meeting_url"),
capacity: integer("capacity").notNull(),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
/**
* Called off, rather than deleted. People have it in their calendar; a row
* that vanishes tells them nothing and a row that says cancelled does.
*/
cancelledAt: timestamp("cancelled_at", { withTimezone: true }),
},
(t) => [index("speaking_rounds_starts_idx").on(t.startsAt)],
);
export const roundAttendance = pgTable(
"round_attendance",
{
roundId: uuid("round_id")
.notNull()
.references(() => speakingRounds.id, { onDelete: "cascade" }),
actorId: text("actor_id").notNull(),
/** Denormalised from the OIDC profile, like every other name here. */
displayName: text("display_name").notNull(),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
},
(t) => [primaryKey({ columns: [t.roundId, t.actorId] }), index("round_attendance_actor_idx").on(t.actorId)],
);
/**
* Feedback on the roadmap and the changelog — the storage behind bip-kit's
* `FeedbackStore` contract (`lib/feedback/store.ts`).
*
* `voter` is NOT an identity. It is the random key the reader's browser keeps
* (bip-kit's `x-bip-voter`), so a vote needs no sign-in and says nothing about
* who cast it. `target_id` is a bip-kit id (`roadmap:teams`,
* `changelog:2026-09-25:1`), validated against the published roadmap and
* changelog by the route before anything is written.
*/
export const feedbackStances = pgTable(
"feedback_stances",
{
targetId: text("target_id").notNull(),
voter: text("voter").notNull(),
/** `needed` | `not-needed`. Withdrawing a stance deletes the row. */
stance: text("stance").notNull(),
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
},
(t) => [primaryKey({ columns: [t.targetId, t.voter] })],
);
export const feedbackComments = pgTable(
"feedback_comments",
{
id: uuid("id").primaryKey().defaultRandom(),
targetId: text("target_id").notNull(),
voter: text("voter").notNull(),
body: text("body").notNull(),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
},
(t) => [index("feedback_comments_target_idx").on(t.targetId, t.createdAt)],
);
export const feedbackSuggestions = pgTable("feedback_suggestions", {
id: uuid("id").primaryKey().defaultRandom(),
body: text("body").notNull(),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
});
/** One row per voter who asked for a suggestion, its author included. */
export const feedbackSupport = pgTable(
"feedback_support",
{
suggestionId: uuid("suggestion_id")
.notNull()
.references(() => feedbackSuggestions.id, { onDelete: "cascade" }),
voter: text("voter").notNull(),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
},
(t) => [primaryKey({ columns: [t.suggestionId, t.voter] })],
);
/**
* Progress synced between a learner's devices — OPT-IN, signed in, off by
* default (settings). One row per device per record kind; see
* `lib/domain/progress/sync.ts` for why devices are kept apart rather than
* merged into one row: a page adds them up when it shows them, and nothing is
* ever counted twice.
*
* `device_id` is random and names only "a browser"; `actor_id` is the OIDC
* subject, like everywhere else here. Turning sync off deletes this device's
* rows; "delete synced progress" deletes all of them.
*/
export const progressDevices = pgTable(
"progress_devices",
{
actorId: text("actor_id").notNull(),
deviceId: text("device_id").notNull(),
/** `model` | `history` | `streak` | `saved`. */
key: text("key").notNull(),
value: jsonb("value").notNull(),
/**
* The course the record is about. Not part of the primary key: a second
* course needs the key widened to include it, in its own migration, and
* until one exists every row is the same course.
*/
course: course(),
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
},
(t) => [primaryKey({ columns: [t.actorId, t.deviceId, t.key] })],
);
/**
* A certificate for one situation, issued by the SERVER from the learner's
* synced progress — never from a browser's say-so, which is what makes the
* public page worth showing to somebody else.
*
* It records what was measured when it was issued (`askable`, `held`,
* `stuck`), because situations grow: a certificate from a 10-line scene says
* 10, and stays true about what it certified after the scene has 20.
* No name: the page is public, and a name there would be a directory of who
* is learning Swiss German. The learner may type one for printing; it is not
* stored.
*/
export const certificates = pgTable(
"certificates",
{
id: uuid("id").primaryKey().defaultRandom(),
actorId: text("actor_id").notNull(),
sceneId: text("scene_id").notNull(),
/** Scene ids are unique within a course, not across them. */
course: course(),
askable: integer("askable").notNull(),
held: integer("held").notNull(),
stuck: integer("stuck").notNull(),
issuedAt: timestamp("issued_at", { withTimezone: true }).notNull().defaultNow(),
},
(t) => [index("certificates_actor_scene_idx").on(t.actorId, t.sceneId)],
);
/**
* What a signed-in learner chose for themselves, so a new device starts from
* it instead of from German.
*
* Only the site language today. The `heidi_locale` cookie already remembers a
* choice per browser; this row is what lets it follow the PERSON — somebody
* who reads the site in Züridütsch should not be handed Hochdeutsch again on
* every phone they sign in on. Written only when they pick a language while
* signed in (or sign in from a page that is not the German default), read
* only on the way back from signing in. See `lib/domain/preferences/`.
*/
export const preferences = pgTable("preferences", {
/** OIDC `sub`. No foreign key: the person lives in OrangeCat, not here. */
actorId: text("actor_id").primaryKey(),
/** One of `LOCALES`; checked on write and again on read. */
locale: text("locale").notNull(),
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
});
/**
* What a signed-in learner has agreed to be written to about — one row, one
* switch. Off until they turn it on (`reminders`); the sweep that sends
* (`lib/mail/reminder-sweep.ts`) reads only rows where it is on, and the rules
* for when it may actually write live in `lib/mail/reminder-policy.ts`.
*
* `tz` is the browser's IANA zone at the moment they switched it on, so the
* mail arrives in their evening and not the server's. `ignored` counts
* reminders in a row that were not followed by practice; three and it goes
* quiet by itself.
*/
export const mailPreferences = pgTable("mail_preferences", {
actorId: text("actor_id").primaryKey(),
reminders: boolean("reminders").notNull().default(false),
tz: text("tz"),
lastReminderAt: timestamp("last_reminder_at", { withTimezone: true }),
ignored: integer("ignored").notNull().default(0),
/**
* The weekly mail to admins (`lib/mail/digest-sweep.ts`). On unless somebody
* turned it off: null and true send, false does not. Only read for a user
* whose role is `admin`.
*/
digest: boolean("digest"),
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
});
/**
* Channels a learner follows, and what came out on them.
*
* WHY THIS IS ON THE SERVER AT ALL, when the learner model, the saved words
* and the streak are deliberately in the browser. Following a channel means
* being told when it publishes, and a browser that is closed cannot poll
* YouTube. So the follow is a row, the sweep that reads the feeds runs here,
* and the thing we keep about the person is exactly one fact: which channels.
* What they answered about a video stays in their browser
* (`heidi.videos.v1`), like every other measurement of them.
*
* `channels.id` is the platform's own channel id (the `UC…` string), so two
* learners following the same channel share one row and one feed read. The
* transcript and the questions are per VIDEO and shared the same way: a
* transcript is the publisher's text and the questions are ours about it —
* neither is about a learner.
*/
export const channels = pgTable("channels", {
/**
* The platform's channel id (`UC…` on YouTube), or for a podcast an id
* derived from its feed URL (`f` + 24 hex — `lib/channels/rss.ts`).
*/
id: text("id").primaryKey(),
/** `youtube` | `podcast`. A "channel" here is anything with a feed of episodes. */
kind: text("kind").notNull().default("youtube"),
name: text("name").notNull(),
/** The `@handle`, when the channel was added by one; for the link we show. */
handle: text("handle"),
url: text("url").notNull(),
/** The feed the sweep reads: YouTube's Atom feed or the podcast's RSS. */
feedUrl: text("feed_url").notNull().default(""),
/** What is spoken, when the register knows the source (`dialect` | `standard` | `mixed`). */
spoken: text("spoken"),
/** The podcast's artwork; null for a YouTube channel (each video has its own). */
imageUrl: text("image_url"),
/** When the feed was last read. Null until the first sweep. */
checkedAt: timestamp("checked_at", { withTimezone: true }),
/** Why the last read failed, in a word; null after a good one. */
lastError: text("last_error"),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
});
export const channelVideos = pgTable(
"channel_videos",
{
/** The platform's video id. */
id: text("id").primaryKey(),
channelId: text("channel_id")
.notNull()
.references(() => channels.id, { onDelete: "cascade" }),
title: text("title").notNull(),
publishedAt: timestamp("published_at", { withTimezone: true }).notNull(),
thumbnailUrl: text("thumbnail_url"),
description: text("description"),
/** A podcast episode's audio (the enclosure); null for a YouTube video. */
mediaUrl: text("media_url"),
mediaType: text("media_type"),
durationSeconds: integer("duration_seconds"),
/** A transcript the publisher linked (`<podcast:transcript>`), and its MIME type. */
transcriptUrl: text("transcript_url"),
transcriptType: text("transcript_type"),
/**
* `{ lines, source, lang }` — see `lib/channels/transcript.ts`. Null until
* somebody opened the video and it could be fetched or was pasted.
*/
transcript: jsonb("transcript"),
/**
* `unknown` | `ready` | `none` | `blocked`. `none` is the platform saying
* there are no captions; `blocked` is the platform refusing to tell us —
* which is what sends the learner to the paste path.
*/
transcriptState: text("transcript_state").notNull().default("unknown"),
/** The generated question set, once a learner asked for one. */
questions: jsonb("questions"),
/** When followers were told about it. Null until the sweep sends. */
notifiedAt: timestamp("notified_at", { withTimezone: true }),
fetchedAt: timestamp("fetched_at", { withTimezone: true }).notNull().defaultNow(),
},
(t) => [index("channel_videos_channel_published_idx").on(t.channelId, t.publishedAt)],
);
export const channelFollows = pgTable(
"channel_follows",
{
actorId: text("actor_id").notNull(),
channelId: text("channel_id")
.notNull()
.references(() => channels.id, { onDelete: "cascade" }),
followedAt: timestamp("followed_at", { withTimezone: true }).notNull().defaultNow(),
/** The last time this learner looked at the channel's videos — what "new" means. */
seenAt: timestamp("seen_at", { withTimezone: true }),
},
(t) => [primaryKey({ columns: [t.actorId, t.channelId] }), index("channel_follows_channel_idx").on(t.channelId)],
);
/**
* A browser that asked to be told. The endpoint is the push service's URL for
* that one browser and is the identity: re-subscribing from the same browser
* replaces the row rather than adding one. Deleted when the push service
* answers 404 or 410, which is how a browser that forgot us tells us so.
*/
export const pushSubscriptions = pgTable(
"push_subscriptions",
{
endpoint: text("endpoint").primaryKey(),
actorId: text("actor_id").notNull(),
p256dh: text("p256dh").notNull(),
auth: text("auth").notNull(),
/** The site language the browser was in, so the notification is in it. */
locale: text("locale").notNull(),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
lastSeenAt: timestamp("last_seen_at", { withTimezone: true }).notNull().defaultNow(),
},
(t) => [index("push_subscriptions_actor_idx").on(t.actorId)],
);
/**
* A thumb under one of Heidi's answers — the reader's half of the fleet's
* chat-review loop (chatkit 0.14, `AnswerFeedback`).
*
* `conversation_id` is TEXT and carries no foreign key, on purpose. A signed-in
* conversation's id is a `conversations` row; a signed-out one has no row at
* all (nothing anonymous reaches the database — §10) and files its thumb under
* the literal `draft`, so a bad answer in the browser-only chat is still
* counted, even though no transcript can ever be joined to it. `message_id` is
* likewise the product's own id — a `conversation_messages` row, or the
* client's local id for a draft — and never a person.
*
* Nothing here names who pressed it. The nightly review (`/api/chat/
* review-export`) reads these beside the conversation they belong to; a thumb
* with no owner is exactly as useful to it and exactly as private as the
* conversation row already is.
*/
export const chatFeedback = pgTable(
"chat_feedback",
{
id: uuid("id").primaryKey().defaultRandom(),
conversationId: text("conversation_id").notNull(),
messageId: text("message_id").notNull(),
/** `up` | `down`. */
verdict: text("verdict").notNull(),
/** One of chatkit's `FEEDBACK_REASONS`, when the person picked one. */
reason: text("reason"),
/** Their own words, at most 1000 characters, when they typed any. */
text: text("text"),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
},
// The export joins thumbs to the conversations it is about to ship.
(t) => [index("chat_feedback_conversation_idx").on(t.conversationId, t.createdAt)],
);
/**
* Passes: what was offered for payment, and what access it bought.
*
* `pay_checkouts` is one row per invoice Heidi asked OrangeCat for. It is the
* only link from a settled payment back to a person: OrangeCat's
* `payment.settled` names the payment and nothing else. `handle` is the token
* that reads the payment's status and never leaves the server. `settled_at`
* is the idempotency mark: a payment grants its days once, however often the
* webhook is delivered and however the status poll races it.
*
* `entitlements` is one row per person: the pass they hold and when it ends.
*/
export const payCheckouts = pgTable(
"pay_checkouts",
{
id: text("id").primaryKey(),
actorId: text("actor_id").notNull(),
provider: text("provider").notNull(),
planId: text("plan_id").notNull(),
amount: integer("amount").notNull(),
currency: text("currency").notNull(),
invoice: text("invoice"),
payUrl: text("pay_url"),
handle: text("handle"),
expiresAt: timestamp("expires_at", { withTimezone: true }),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
settledAt: timestamp("settled_at", { withTimezone: true }),
},
(t) => [index("pay_checkouts_actor_idx").on(t.actorId, t.createdAt)],
);
export const entitlements = pgTable("entitlements", {
actorId: text("actor_id").primaryKey(),
planId: text("plan_id").notNull(),
/** The course the pass was bought for. Recorded by the column's default. */
course: course(),
expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
});
/**
* Pass codes: a pass that was paid for somewhere Heidi cannot see.
*
* An organisation pays for its people in francs, by bank transfer, and there
* is no invoice of OrangeCat's to settle. So the owner issues one code per
* person and the person redeems it: the same `entitlements` row a Bitcoin
* payment writes, through the same arithmetic (`lib/pay/codes.ts`).
*
* `id` is the SHA-256 of the code. The code itself is shown once, to the
* owner who issued it, and is stored nowhere: a copy of this table is not a
* list of passes anybody can take. `hint` is its last four characters, so the
* owner can tell which of a batch has been used. `label` is who the batch was
* issued for, in the owner's words. `redeemed_at` is the idempotency mark, as
* `settled_at` is on a checkout: a code grants its days once.
*/
export const passCodes = pgTable(
"pass_codes",
{
id: text("id").primaryKey(),
hint: text("hint").notNull(),
days: integer("days").notNull(),
label: text("label").notNull(),
/** The course the pass is for. Recorded by the column's default. */
course: course(),
createdBy: text("created_by").notNull(),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
redeemedBy: text("redeemed_by"),
redeemedAt: timestamp("redeemed_at", { withTimezone: true }),
},
(t) => [index("pass_codes_label_idx").on(t.label, t.createdAt)],
);
/**
* Who asked to be told when a language Heidi does not teach yet is ready.
*
* WHAT IT IS FOR, AND NOTHING ELSE: to learn which language to build next,
* and to write to that address once when it exists. It is a list of
* addresses and a wish each — never an account, never a subscription to
* anything else, and no page may call it a waiting list for a product that
* has a date. `lib/config/languages.ts` holds which languages can be asked
* for; `lib/config/privacy.ts` states this table on the privacy page.
*
* The person is the `email`: there is no `actor_id`, because the form works
* signed out. Deleting an account deletes the rows with that account's
* address (`eraseActorData`). One row per address and language, so asking
* twice changes nothing but the region.
*
* `region` is their own words for the canton or region they live in or are
* moving to, when they gave one. `locale` is the interface language they
* asked in, so the one mail can be written in it.
*/
export const languageInterest = pgTable(
"language_interest",
{
id: uuid("id").primaryKey().defaultRandom(),
email: text("email").notNull(),
/** A `PlannedLanguageId` from `lib/config/languages.ts`. */
language: text("language").notNull(),
region: text("region"),
locale: text("locale").notNull(),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
/**
* Double opt-in (2026-11-25). `confirmedAt` is when the person opened the
* link in the one confirmation mail; null on every row from before, and
* on a row whose mail was never opened. `confirmToken` is the SHA-256 of
* the link's token while one is outstanding, never the token itself;
* `confirmSentAt` is when that mail last went out, so an address is not
* mailed again and again by whoever types it into the form.
*/
confirmedAt: timestamp("confirmed_at", { withTimezone: true }),
confirmToken: text("confirm_token"),
confirmSentAt: timestamp("confirm_sent_at", { withTimezone: true }),
},
(t) => [
uniqueIndex("language_interest_email_language_idx").on(t.email, t.language),
uniqueIndex("language_interest_confirm_token_idx").on(t.confirmToken),
],
);
/**
* Rate-limit counters for signed-in callers (`lib/domain/limit-counter.ts`).
*
* One row per key and time bucket; a key is `<purpose>:<course>:<account>`
* and has at most two live rows. Nothing here says what anybody did: a
* purpose is the name of a limit ("chat", "speak"), the count is how many
* requests were allowed in that bucket, and rows older than a day are
* removed. Anonymous callers are counted in memory and never reach this
* table, so it holds no address.
*/
export const rateLimits = pgTable(
"rate_limits",
{
key: text("key").notNull(),
/** The start of the bucket, in epoch milliseconds. */
bucket: bigint("bucket", { mode: "number" }).notNull(),
count: integer("count").notNull().default(0),
},
(t) => [primaryKey({ columns: [t.key, t.bucket] }), index("rate_limits_bucket_idx").on(t.bucket)],
);
/**
* Server errors, grouped (`lib/domain/errors/sink.ts`).
*
* One row per KIND of error, not per occurrence: the route pattern it
* happened in (`/api/chat`, `/[locale]/practice`: the file's path, never the
* address that was requested), the error's name and a message with
* addresses, ids and long tokens removed, how often, and when first and
* last. No request, no body, no header, no account. Capped at a few hundred
* rows; a row not seen for thirty days is removed.
*/
export const errorEvents = pgTable(
"error_events",
{
/** sha-256 of route, name and scrubbed message: what makes two errors "the same". */
hash: text("hash").primaryKey(),
route: text("route").notNull(),
name: text("name").notNull(),
message: text("message").notNull(),
count: integer("count").notNull().default(1),
firstSeen: timestamp("first_seen", { withTimezone: true }).notNull().defaultNow(),
lastSeen: timestamp("last_seen", { withTimezone: true }).notNull().defaultNow(),
},
(t) => [index("error_events_last_seen_idx").on(t.lastSeen)],
);
/**
* Anonymous totals: how often something happened on a day, and nothing about
* who did it.
*
* WHY. Practice lives in the browser, so nobody — the owner included — could
* say whether people finish a situation, which question everybody gets
* wrong, or whether an exercise is used at all. A product that cannot see
* that cannot be made better on purpose. Decided by the owner on 2026-11-28.
*
* WHAT A ROW IS. A day, a key from a closed vocabulary (`usage/keys.ts`:
* «a run of this situation was started», «this question was answered
* wrong») and a count. No account, no visitor id, no address, no time of
* day, no text anybody typed. Two people cannot be told apart in it, and one
* person cannot be followed through it; that is the design, not a setting.
*/
export const usageCounts = pgTable(
"usage_counts",
{
day: date("day").notNull(),
key: text("key").notNull(),
count: integer("count").notNull().default(0),
},
(t) => [primaryKey({ columns: [t.day, t.key] })],
);
/**
* What a native speaker said about a line of a situation.
*
* WHY. On 2026-11-28 none of the 793 lines of the situations had been read
* by anybody who speaks the variety, and the pages say so. That is the first
* thing a care home's own staff would notice. A reader goes through a scene
* line by line and says "that is how we say it", "not like this" (with how
* they would say it) or "not sure"; the owner reads the verdicts and corrects
* the pack, and only then is a line marked reviewed (`Provenance`).
*
* NO ACCOUNT. The reader is a nurse who was sent a link; an account between
* her and the first line is the end of the review. `reader` is a random id
* her browser made up (`heidi.review.reader.v1`), which says only that two
* verdicts came from the same browser. One row per reader and line: a reader
* who changes their mind replaces their verdict.
*
* The line is stored AS IT WAS SHOWN, so a verdict on a line that has since
* been corrected is not mistaken for one on the new wording.
*/
export const lineReviews = pgTable(
"line_reviews",
{
reader: text("reader").notNull(),
scene: text("scene").notNull(),
line: integer("line").notNull(),
/** `ok` | `other` (fine, but I say it differently) | `wrong` | `unsure`. */
verdict: text("verdict").notNull(),
/** How the reader would say it; only with `wrong` or `unsure`. */
suggestion: text("suggestion"),
/** Where the reader's own dialect is from, in their words, if they said. */
origin: text("origin"),
/**
* Which invitation the reader came through (`?via=` on the link), so the
* owner can tell a care home's own staff from a link passed round among
* friends. A short code the sender chose, never a name.
*/
via: text("via"),
/** The line as the reader saw it. */
shown: text("shown").notNull(),
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
},
(t) => [primaryKey({ columns: [t.reader, t.scene, t.line] }), index("line_reviews_scene_idx").on(t.scene, t.line)],
);
/**
* The daily chat benchmark (`lib/domain/bench`): a fixed set of messages sent
* through the real chat, and the translations also sent to the same models
* WITHOUT Heidi's prompt or check, so the page can show what the check is
* worth. One row per run; nothing in it is about a person.
*/
export const benchRuns = pgTable("bench_runs", {
ranAt: timestamp("ran_at", { withTimezone: true }).primaryKey(),
results: jsonb("results").notNull(),
});
/**
* An account the owner linked by mail (`lib/domain/owner/link.ts`): somebody
* who signs in through OrangeCat has no real address here, so `OWNER_EMAILS`
* can never match them. A link mailed to the owner address and opened makes
* that account an owner, with no change on the server.
*/
export const ownerLinks = pgTable("owner_links", {
actorId: text("actor_id").primaryKey(),
/** Which owner address the confirming mail went to. */
confirmedBy: text("confirmed_by").notNull(),
linkedAt: timestamp("linked_at", { withTimezone: true }).notNull().defaultNow(),
});
/**
* A run of the understanding test (`bench/understand.ts`): course lines the
* chat was asked to explain with the line itself held back, each judged
* against the line's known meaning. Started by hand; holds no person.
*/
export const understandRuns = pgTable("understand_runs", {
ranAt: timestamp("ran_at", { withTimezone: true }).primaryKey(),
results: jsonb("results").notNull(),
});
/**
* A pilot asked for on a sector page (`/organisations/<sector>`): who, from
* where, how to reach them, and what they wrote. The owner reads them at
* `/api/owner/requests` and gets a mail for each when mail is set up.
*/
export const orgRequests = pgTable("org_requests", {
id: uuid("id").primaryKey().defaultRandom(),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
sector: text("sector").notNull(),
locale: text("locale").notNull(),
name: text("name").notNull(),
organisation: text("organisation").notNull(),
role: text("role"),
email: text("email").notNull(),
people: text("people"),
message: text("message"),
/** When somebody in the back office marked it done (`/manage/inbox`). */
handledAt: timestamp("handled_at", { withTimezone: true }),
/** What was answered from the back office, and when; the mail itself went to `email`. */
replyText: text("reply_text"),
repliedAt: timestamp("replied_at", { withTimezone: true }),
});
/**
* An invitation into the back office (`lib/domain/admin/people.ts`): a
* single-use link carrying a role. Only the hash of the link is kept.
*/
export const adminInvites = pgTable("admin_invites", {
tokenHash: text("token_hash").primaryKey(),
role: text("role").notNull(),
/** Actor id of who invited; shown on the People screen. */
invitedBy: text("invited_by").notNull(),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
usedBy: text("used_by"),
usedAt: timestamp("used_at", { withTimezone: true }),
});
/**
* Who was let into the back office, by whom, and who was taken out: an
* append-only history (security review, 2026-11-30). Written by
* `lib/domain/admin/people.ts` in the same statement as the change itself,
* never updated and never deleted; an account that is deleted stays in it as
* nobody (`account/erase.ts`).
*/
export const adminEvents = pgTable("admin_events", {
id: uuid("id").primaryKey().defaultRandom(),
at: timestamp("at", { withTimezone: true }).notNull().defaultNow(),
/** `users.id` of who did it, or `system` (the owner link, a deploy). */
actor: text("actor").notNull(),
/** invited · accepted · revoked · removed · made-admin · first-admin */
action: text("action").notNull(),
/** `users.id` of whose access changed; none for an invitation, which names nobody yet. */
target: text("target"),
/** The role it was about. */
detail: text("detail"),
});