import { writableChangelogStatus } from "@feeblo/domain/changelog/machine"; import type { CommentReaction } from "@feeblo/domain/comment-reaction/schema"; import type { TPostActivity } from "@feeblo/domain/post-activity/schema"; import type { PostReaction } from "@feeblo/domain/post-reaction/schema"; import type { PostSubscription } from "@feeblo/domain/post-subscription/schema"; import type { TPostCreateAuthor } from "@feeblo/domain/post/schema"; import type { Upvote } from "@feeblo/domain/upvote/schema"; /** * post-ui attaches a transient `author` to comment insert payloads so * on-behalf attribution rides the same onInsert path; it is not a persisted * column (see docs/on-behalf.md). Post on-behalf attribution flows via the * surface's `persistPost` input instead (slim list rows carry no body). */ type PostWithTransientAuthor = { author?: TPostCreateAuthor; }; import { eqFilterValue, postSlugFromPath, refetchInBackground, } from "@feeblo/web-shared/collections"; import { getCommentReactionCollectionKey, getPostReactionCollectionKey, getPostSubscriptionCollectionKey, getUpvoteCollectionKey, } from "@feeblo/web-shared/reaction-keys"; import { queryCollectionOptions } from "@tanstack/query-db-collection"; import { BasicIndex, collectionOptions, DbClient, parseLoadSubsetOptions, } from "@tanstack/react-db"; import type { CollectionOptions, NonSingleResult, UtilsRecord, } from "@tanstack/react-db"; import type { QueryClient } from "@tanstack/react-query"; import { createIsomorphicFn } from "@tanstack/react-start"; import { getRequestUrl } from "@tanstack/react-start/server"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import type * as Schema from "effect/Schema"; import { getDbClient } from "@/lib/db-client"; import { getContext } from "~/integrations/tanstack-query/root-provider"; import { type DashboardCollectionScope, organizationScopedCollectionId, organizationScopedQueryKey, scopePostSlug, slugScopedCollectionId, slugScopedQueryKey, } from "./collection-scope"; import { fetchRpc } from "./runtime"; type CommentReactionRow = Schema.Schema.Type; type PostReactionRow = Schema.Schema.Type; type PostSubscriptionRow = Schema.Schema.Type; type UpvoteRow = Schema.Schema.Type; /** * The request's pathname. * * Server rendering reads it from the request rather than `window`, which is * what lets a collection resolve its scope during SSR. The dashboard's * organization is the first path segment and the post slug sits in the path * too, so both branches parse the same string the same way. */ const currentPathname = createIsomorphicFn() .client(() => window.location.pathname) .server(() => getRequestUrl().pathname); function currentScope(): DashboardCollectionScope { return { organizationId: getCurrentOrganizationId(), postSlug: getCurrentPostSlug(), }; } /** * The client the dashboard's collections materialize through. * * Shared with `getRouter()` so `useDbClient()` and the module-level * `dashboardCollections` accessor cannot end up with two clients (which would * mean two collections per descriptor, two syncs, and two sets of rows). */ function getBrowserDbClient(): DbClient { return getDbClient(() => getContext().queryClient); } /** * The dashboard's organization, taken from the first path segment. * * Read when a descriptor is materialized (`currentScope`), which is what pins * the descriptor and its query key to one scope. The dashboard is client-only, * so `currentPathname` resolves from `window`. */ function getCurrentOrganizationId() { const organizationId = currentPathname() .split("/") .find((segment) => segment.length > 0); return organizationId ? decodeURIComponent(organizationId) : undefined; } /** * Post detail pages live at `/:organizationId/.../post/:boardSlug/:postSlug`; * parse the post slug from the current URL so a collection created without an * explicit filter (e.g. from a route loader) captures the post it belongs to * and keys itself to that post, not to whichever post is on screen later. */ function getCurrentPostSlug() { return postSlugFromPath(currentPathname(), "post", 2); } export function postCollection(scope: DashboardCollectionScope) { const id = organizationScopedCollectionId("postCollection", scope); return collectionOptions(id, (client) => queryCollectionOptions({ id, queryClient: client.requireDependency("queryClient"), queryKey: () => organizationScopedQueryKey(scope, "post"), queryFn: async (ctx) => { const organizationId = scope.organizationId; if (!organizationId) { return []; } const boardId: string | null = null; const data = await fetchRpc( (rpc) => rpc.ListPosts({ boardId, organizationId }), { signal: ctx.signal, } ); return [...data]; }, getKey: (item) => item.id, // No `onInsert`: creation persists through the surface's `persistPost` // inside the shared form's optimistic action, so a bare insert fails // fast with `MissingInsertHandlerError` instead of persisting without // a body. Updates and deletes sync here as before. onUpdate: async ({ collection, transaction }) => { const mutation = transaction.mutations[0]; const { modified: updatedPost } = mutation; await fetchRpc((rpc) => rpc.UpdatePost({ id: updatedPost.id, statusId: updatedPost.statusId, boardId: updatedPost.boardId, organizationId: updatedPost.organizationId, }) ); // The activity entry is derived from the post row: refresh the entry // detached, then read the post row itself back so the settled // transaction keeps the server's version of the mutation target. refetchInBackground( client.collection(postActivityCollection(scope)).utils.refetch() ); await collection.utils.refetch({ throwOnError: true }); }, onDelete: async ({ transaction }) => { const [firstMutation] = transaction.mutations; if (!firstMutation) { return; } const { organizationId } = firstMutation.original; // Deletes can arrive one at a time (row actions) or as one transaction // with many mutations (bulk selection). Group them into one bulk RPC // per board so both paths share the server call. const postIdsByBoardId = new Map(); for (const mutation of transaction.mutations) { const { original: deletedPost } = mutation; const postIds = postIdsByBoardId.get(deletedPost.boardId) ?? []; postIds.push(deletedPost.id); postIdsByBoardId.set(deletedPost.boardId, postIds); } // Settle every board's RPC before rejecting: `Promise.all` fail-fast // would strand a successful board's optimistic deletes behind the // failing one. The read-back below then runs in both outcomes, so the // rollback a rejection triggers reveals the reconciled rows instead of // resurrecting posts the server already deleted. const results = await Promise.allSettled( [...postIdsByBoardId.entries()].map(([boardId, postIds]) => fetchRpc((rpc) => rpc.DeletePost({ id: postIds, boardId, organizationId, }) ) ) ); // Deleting a survivor also reverts its merged children server-side, so // the synced rows must be refreshed or the restored duplicates stay // hidden behind their stale `mergedIntoPostId`. This collection is the // mutation target, so the read-back is awaited. await client .collection(postCollection(scope)) .utils.refetch({ throwOnError: true }); // The delete-hint set is derived: refresh it detached so the delete // settles without waiting on a second round trip. refetchInBackground( client.collection(deleteEligibilityCollection(scope)).utils.refetch() ); const failure = results.find((result) => result.status === "rejected"); if (failure) { throw failure.reason; } }, }) ); } /** * Full-post detail collection backing post detail routes. The org-scoped * `postCollection` carries slim `PostListItem` rows (no `content`); this * slug-scoped, on-demand collection resolves the body through `GetPost`. * Detail routes preload + subscribe it and merge `content` over the list * row. Content edits apply here through `createOptimisticAction` (ambient * transaction, so no sync handlers by design); all other mutations stay on * the list collection. */ export function postDetailCollection(scope: DashboardCollectionScope) { const id = slugScopedCollectionId("postDetailCollection", scope); return collectionOptions(id, (client) => queryCollectionOptions({ id, queryClient: client.requireDependency("queryClient"), // Keyed by the explicit `slug` filter with a fallback to the route // slug, so detail subscribers (routes, content views) share one cache // entry per post regardless of where they subscribe from. queryKey: (opts) => { const filters = parseLoadSubsetOptions(opts).filters; const slug = eqFilterValue(filters, "slug") ?? scopePostSlug(scope, filters); return organizationScopedQueryKey(scope, "post-detail", slug); }, syncMode: "on-demand", queryFn: async (ctx) => { const organizationId = scope.organizationId; const filters = parseLoadSubsetOptions( ctx.meta?.loadSubsetOptions ).filters; const slug = eqFilterValue(filters, "slug") ?? scopePostSlug(scope, filters); if (!(organizationId && slug)) { return []; } const post = await fetchRpc( (rpc) => rpc .GetPost({ organizationId, slug }) // A missing slug is an empty lookup, not a failed one: the live // query resolves to no row and the route renders its "Post not // found" state. Without this the not-found error rejects the // preload, and a stale or mistyped post URL lands on the route's // error boundary instead of that state. .pipe( Effect.catchTag("PostNotFoundError", () => Effect.succeed(null)) ), { signal: ctx.signal } ); return post === null ? [] : [post]; }, getKey: (item) => item.id, }) ); } export function postStatusCollection(scope: DashboardCollectionScope) { const id = organizationScopedCollectionId("postStatusCollection", scope); return collectionOptions(id, (client) => queryCollectionOptions({ id, queryClient: client.requireDependency("queryClient"), queryKey: () => organizationScopedQueryKey(scope, "post-status"), queryFn: async (ctx) => { const organizationId = scope.organizationId; if (!organizationId) { return []; } const data = await fetchRpc( (rpc) => rpc.ListPostStatuses({ organizationId }), { signal: ctx.signal, } ); return [...data]; }, getKey: (item) => item.id, onInsert: async ({ collection, transaction }) => { const mutation = transaction.mutations[0]; const { modified: newStatus } = mutation; const organizationId = scope.organizationId; if (!organizationId) { throw new Error("Missing organization id"); } await fetchRpc((rpc) => rpc.CreatePostStatus({ id: newStatus.id, organizationId, type: newStatus.type, label: newStatus.label, color: newStatus.color ?? null, icon: newStatus.icon ?? null, orderIndex: newStatus.orderIndex, }) ); await collection.utils.refetch({ throwOnError: true }); }, onUpdate: async ({ collection, transaction }) => { const mutation = transaction.mutations[0]; const { modified: updatedStatus } = mutation; const organizationId = scope.organizationId; if (!organizationId) { throw new Error("Missing organization id"); } await fetchRpc((rpc) => rpc.UpdatePostStatus({ id: updatedStatus.id, organizationId, type: updatedStatus.type, label: updatedStatus.label, color: updatedStatus.color ?? null, icon: updatedStatus.icon ?? null, }) ); await collection.utils.refetch({ throwOnError: true }); }, }) ); } export function changelogCollection(scope: DashboardCollectionScope) { const id = organizationScopedCollectionId("changelogCollection", scope); return collectionOptions(id, (client) => queryCollectionOptions({ id, queryClient: client.requireDependency("queryClient"), queryKey: () => organizationScopedQueryKey(scope, "changelog"), queryFn: async (ctx) => { const organizationId = scope.organizationId; if (!organizationId) { return []; } const data = await fetchRpc( (rpc) => rpc.ListChangelogs({ organizationId }), { signal: ctx.signal, } ); return [...data]; }, getKey: (item) => item.id, onUpdate: async ({ collection, transaction }) => { const mutation = transaction.mutations[0]; const { modified: updatedChangelog } = mutation; await fetchRpc((rpc) => rpc.UpdateChangelog({ id: updatedChangelog.id, title: updatedChangelog.title, slug: updatedChangelog.slug, content: updatedChangelog.content, assetIds: updatedChangelog.assetIds ?? [], coverImage: updatedChangelog.coverImage ?? null, // A row read back as `scheduled` — filed before scheduling was // disabled — is saved as the draft it effectively is. // `writableChangelogStatus` is the machine's answer rather than a // cast, so a real scheduling event would change it here. status: writableChangelogStatus(updatedChangelog.status), scheduledAt: updatedChangelog.scheduledAt, publishedAt: updatedChangelog.publishedAt, organizationId: updatedChangelog.organizationId, }) ); await collection.utils.refetch({ throwOnError: true }); }, onDelete: async ({ collection, transaction }) => { const mutation = transaction.mutations[0]; const { original: deletedChangelog } = mutation; await fetchRpc((rpc) => rpc.DeleteChangelog({ id: deletedChangelog.id, organizationId: deletedChangelog.organizationId, }) ); await collection.utils.refetch({ throwOnError: true }); }, onInsert: async ({ collection, transaction }) => { const mutation = transaction.mutations[0]; const { modified: newChangelog } = mutation; await fetchRpc((rpc) => rpc.CreateChangelog({ id: newChangelog.id, title: newChangelog.title, slug: newChangelog.slug, content: newChangelog.content, assetIds: newChangelog.assetIds ?? [], coverImage: newChangelog.coverImage ?? null, status: writableChangelogStatus(newChangelog.status), scheduledAt: newChangelog.scheduledAt, publishedAt: newChangelog.publishedAt, organizationId: newChangelog.organizationId, }) ); await collection.utils.refetch({ throwOnError: true }); }, }) ); } export function changelogCategoryLinkCollection( scope: DashboardCollectionScope ) { const id = organizationScopedCollectionId( "changelogCategoryLinkCollection", scope ); return collectionOptions(id, (client) => queryCollectionOptions({ id, queryClient: client.requireDependency("queryClient"), queryKey: () => organizationScopedQueryKey(scope, "changelog-category-link"), queryFn: async (ctx) => { const organizationId = scope.organizationId; if (!organizationId) { return []; } const data = await fetchRpc( (rpc) => rpc.ListChangelogCategoryLinks({ organizationId }), { signal: ctx.signal, } ); return [...data]; }, getKey: (item) => item.id, }) ); } export function changelogCategoryCollection(scope: DashboardCollectionScope) { const id = organizationScopedCollectionId( "changelogCategoryCollection", scope ); return collectionOptions(id, (client) => queryCollectionOptions({ id, queryClient: client.requireDependency("queryClient"), queryKey: () => organizationScopedQueryKey(scope, "changelog-category"), queryFn: async (ctx) => { const organizationId = scope.organizationId; if (!organizationId) { return []; } const data = await fetchRpc( (rpc) => rpc.ListChangelogCategories({ organizationId }), { signal: ctx.signal, } ); return [...data]; }, getKey: (item) => item.id, onInsert: async ({ collection, transaction }) => { const mutation = transaction.mutations[0]; const { modified: newCategory } = mutation; const iconType = newCategory.iconType; if (iconType !== "color") { throw new Error( "Unsupported changelog category icon type; only color is supported" ); } await fetchRpc((rpc) => rpc.CreateChangelogCategory({ id: newCategory.id, name: newCategory.name, iconType, icon: newCategory.icon, organizationId: newCategory.organizationId, }) ); await collection.utils.refetch({ throwOnError: true }); }, onUpdate: async ({ collection, transaction }) => { const mutation = transaction.mutations[0]; const { modified: updatedCategory } = mutation; const iconType = updatedCategory.iconType; if (iconType !== "color") { throw new Error( "Unsupported changelog category icon type; only color is supported" ); } await fetchRpc((rpc) => rpc.UpdateChangelogCategory({ id: updatedCategory.id, name: updatedCategory.name, iconType, icon: updatedCategory.icon, organizationId: updatedCategory.organizationId, }) ); await collection.utils.refetch({ throwOnError: true }); }, onDelete: async ({ collection, transaction }) => { const mutation = transaction.mutations[0]; const { original: deletedCategory } = mutation; await fetchRpc((rpc) => rpc.DeleteChangelogCategory({ id: deletedCategory.id, organizationId: deletedCategory.organizationId, }) ); await collection.utils.refetch({ throwOnError: true }); }, }) ); } /** * The help center's topics. * * A topic is the article's container and is not plan-limited — the allowance * counts articles (see `helpCenterArticleCollection`), so a workspace at its * ceiling can still reorganise the documentation it already has. */ export function helpCenterTopicCollection(scope: DashboardCollectionScope) { const id = organizationScopedCollectionId("helpCenterTopicCollection", scope); return collectionOptions(id, (client) => queryCollectionOptions({ id, queryClient: client.requireDependency("queryClient"), queryKey: () => organizationScopedQueryKey(scope, "help-center-topic"), queryFn: async (ctx) => { const organizationId = scope.organizationId; if (!organizationId) { return []; } const data = await fetchRpc( (rpc) => rpc.ListHelpCenterTopics({ organizationId }), { signal: ctx.signal } ); return [...data]; }, getKey: (item) => item.id, onInsert: async ({ collection, transaction }) => { const { modified } = transaction.mutations[0]; await fetchRpc((rpc) => rpc.CreateHelpCenterTopic({ id: modified.id, organizationId: modified.organizationId, name: modified.name, slug: modified.slug, description: modified.description, icon: modified.icon, // Omitted rather than sent as `0`: the server appends to the end of // the list, which is what "new section" means and what a blank // client-side position cannot know. position: undefined, }) ); await collection.utils.refetch({ throwOnError: true }); }, onUpdate: async ({ collection, transaction }) => { const { modified } = transaction.mutations[0]; await fetchRpc((rpc) => rpc.UpdateHelpCenterTopic({ id: modified.id, organizationId: modified.organizationId, name: modified.name, slug: modified.slug, description: modified.description, icon: modified.icon, }) ); await collection.utils.refetch({ throwOnError: true }); }, onDelete: async ({ collection, transaction }) => { const { original } = transaction.mutations[0]; await fetchRpc((rpc) => rpc.DeleteHelpCenterTopic({ id: original.id, organizationId: original.organizationId, }) ); await collection.utils.refetch({ throwOnError: true }); }, }) ); } /** * The help center's articles. * * The row carries the three counters, so a list can render "read 1.2k times, * 87% found it helpful" without a second query per row. They are derived * server-side — see the table's own doc comment for why they are not stored. */ export function helpCenterArticleCollection(scope: DashboardCollectionScope) { const id = organizationScopedCollectionId( "helpCenterArticleCollection", scope ); return collectionOptions(id, (client) => queryCollectionOptions({ id, queryClient: client.requireDependency("queryClient"), queryKey: () => organizationScopedQueryKey(scope, "help-center-article"), queryFn: async (ctx) => { const organizationId = scope.organizationId; if (!organizationId) { return []; } const data = await fetchRpc( (rpc) => rpc.ListHelpCenterArticles({ organizationId }), { signal: ctx.signal } ); return [...data]; }, getKey: (item) => item.id, // Read-only: a row is a *summary*, and the body lives only on the // single-article read. The editor writes through the help center's atom // mutations and refetches this list, so no collection callback has to // round-trip a field these rows never held. }) ); } export const getChangelogPostKey = ({ changelogId, postId, }: { changelogId: string; postId: string; }) => `${changelogId}:${postId}`; export function changelogPostCollection(scope: DashboardCollectionScope) { const id = organizationScopedCollectionId("changelogPostCollection", scope); return collectionOptions(id, (client) => queryCollectionOptions({ id, queryClient: client.requireDependency("queryClient"), queryKey: () => organizationScopedQueryKey(scope, "changelog-post"), queryFn: async (ctx) => { const organizationId = scope.organizationId; if (!organizationId) { return []; } const data = await fetchRpc( (rpc) => rpc.ListChangelogPosts({ organizationId }), { signal: ctx.signal } ); return [...data]; }, getKey: getChangelogPostKey, onInsert: async ({ collection, transaction }) => { const { modified } = transaction.mutations[0]; await fetchRpc((rpc) => rpc.CreateChangelogPost({ changelogId: modified.changelogId, postId: modified.postId, organizationId: modified.organizationId, }) ); await collection.utils.refetch({ throwOnError: true }); }, onDelete: async ({ collection, transaction }) => { const { original } = transaction.mutations[0]; await fetchRpc((rpc) => rpc.DeleteChangelogPost({ changelogId: original.changelogId, postId: original.postId, organizationId: original.organizationId, }) ); await collection.utils.refetch({ throwOnError: true }); }, }) ); } export function boardCollection(scope: DashboardCollectionScope) { const id = organizationScopedCollectionId("boardCollection", scope); return collectionOptions(id, (client) => queryCollectionOptions({ id, queryClient: client.requireDependency("queryClient"), queryKey: () => organizationScopedQueryKey(scope, "board"), refetchInterval: Duration.toMillis(Duration.minutes(5)), queryFn: async (ctx) => { const organizationId = scope.organizationId; if (!organizationId) { return []; } const data = await fetchRpc( (rpc) => rpc.ListBoards({ organizationId }), { signal: ctx.signal, } ); return [...data]; }, getKey: (item) => item.id, onInsert: async ({ collection, transaction }) => { const mutation = transaction.mutations[0]; const { modified: newBoard } = mutation; await fetchRpc( (rpc) => rpc.CreateBoard({ id: newBoard.id, name: newBoard.name, icon: newBoard.icon ?? null, visibility: newBoard.visibility, organizationId: newBoard.organizationId, }), {} ); await collection.utils.refetch({ throwOnError: true }); }, onDelete: async ({ collection, transaction }) => { const mutation = transaction.mutations[0]; const { original: deletedBoard } = mutation; await fetchRpc( (rpc) => rpc.DeleteBoard({ id: deletedBoard.id, organizationId: deletedBoard.organizationId, }), {} ); await collection.utils.refetch({ throwOnError: true }); }, onUpdate: async ({ collection, transaction }) => { const mutation = transaction.mutations[0]; const { modified: updatedBoard, original: previousBoard } = mutation; // Only the fields this edit actually changed. `UpdateBoard` treats an // omitted field as "leave it alone", so a concurrent change to another // field is not overwritten by this row's cached copy. await fetchRpc( (rpc) => rpc.UpdateBoard({ id: updatedBoard.id, organizationId: updatedBoard.organizationId, ...(updatedBoard.name === previousBoard.name ? {} : { name: updatedBoard.name }), ...(updatedBoard.icon === previousBoard.icon ? {} : { icon: updatedBoard.icon }), ...(updatedBoard.visibility === previousBoard.visibility ? {} : { visibility: updatedBoard.visibility }), }), {} ); await collection.utils.refetch({ throwOnError: true }); }, }) ); } export function tagCollection(scope: DashboardCollectionScope) { const id = organizationScopedCollectionId("tagCollection", scope); return collectionOptions(id, (client) => queryCollectionOptions({ id, queryClient: client.requireDependency("queryClient"), queryKey: () => organizationScopedQueryKey(scope, "tag"), queryFn: async (ctx) => { const organizationId = scope.organizationId; if (!organizationId) { return []; } const data = await fetchRpc((rpc) => rpc.ListTags({ organizationId }), { signal: ctx.signal, }); return [...data]; }, getKey: (item) => item.id, onInsert: async ({ collection, transaction }) => { const mutation = transaction.mutations[0]; const { modified: newTag } = mutation; await fetchRpc((rpc) => rpc.CreateTag({ id: newTag.id, name: newTag.name, organizationId: newTag.organizationId, }) ); await collection.utils.refetch({ throwOnError: true }); }, onUpdate: async ({ collection, transaction }) => { const mutation = transaction.mutations[0]; const { modified: updatedTag } = mutation; await fetchRpc((rpc) => rpc.UpdateTag({ id: updatedTag.id, name: updatedTag.name, organizationId: updatedTag.organizationId, }) ); await collection.utils.refetch({ throwOnError: true }); }, onDelete: async ({ collection, transaction }) => { const mutation = transaction.mutations[0]; const { original: deletedTag } = mutation; await fetchRpc((rpc) => rpc.DeleteTag({ id: deletedTag.id, organizationId: deletedTag.organizationId, }) ); await collection.utils.refetch({ throwOnError: true }); }, }) ); } export function postTagCollection(scope: DashboardCollectionScope) { const id = organizationScopedCollectionId("postTagCollection", scope); return collectionOptions(id, (client) => queryCollectionOptions({ id, queryClient: client.requireDependency("queryClient"), queryKey: () => organizationScopedQueryKey(scope, "post-tag"), queryFn: async (ctx) => { const organizationId = scope.organizationId; if (!organizationId) { return []; } const data = await fetchRpc( (rpc) => rpc.ListPostTags({ organizationId }), { signal: ctx.signal, } ); return [...data]; }, getKey: (item) => item.id, }) ); } export function membershipCollection(_scope: DashboardCollectionScope) { const id = "membershipCollection"; return collectionOptions(id, (client) => queryCollectionOptions({ id, queryClient: client.requireDependency("queryClient"), queryKey: ["membership"], staleTime: Duration.toMillis(Duration.minutes(10)), queryFn: async (ctx) => fetchRpc((rpc) => rpc.ListMemberships(), { signal: ctx.signal }).then( (data) => [...data] ), getKey: (item) => item.id, }) ); } export function organizationCollection(_scope: DashboardCollectionScope) { const id = "organizationCollection"; return collectionOptions(id, (client) => queryCollectionOptions({ id, queryClient: client.requireDependency("queryClient"), queryKey: ["organizations"], queryFn: async (ctx) => { const data = await fetchRpc((rpc) => rpc.ListOrganizations(), { signal: ctx.signal, }); return [...data]; }, getKey: (item) => item.id, onUpdate: async ({ collection, transaction }) => { const mutation = transaction.mutations[0]; const { modified: updatedOrganization } = mutation; await fetchRpc((rpc) => rpc.UpdateOrganization({ organizationId: updatedOrganization.id, name: updatedOrganization.name, logo: updatedOrganization.logo, }) ); await collection.utils.refetch({ throwOnError: true }); }, }) ); } export function membersCollection(scope: DashboardCollectionScope) { const id = organizationScopedCollectionId("membersCollection", scope); return collectionOptions(id, (client) => queryCollectionOptions({ id, queryClient: client.requireDependency("queryClient"), staleTime: Duration.toMillis(Duration.minutes(20)), queryKey: () => organizationScopedQueryKey(scope, "members"), queryFn: async (ctx) => { const organizationId = scope.organizationId; if (!organizationId) { return []; } const data = await fetchRpc( (rpc) => rpc.ListOrganizationMembers({ organizationId }), { signal: ctx.signal } ); return [...data]; }, getKey: (item) => item.id, onDelete: async ({ collection, transaction }) => { const mutation = transaction.mutations[0]; const { original: deletedMember } = mutation; await fetchRpc((rpc) => rpc.RemoveOrganizationMember({ memberId: deletedMember.id, organizationId: deletedMember.organizationId, }) ); await collection.utils.refetch({ throwOnError: true }); }, onUpdate: async ({ collection, transaction }) => { const mutation = transaction.mutations[0]; const { modified: updatedMember } = mutation; await fetchRpc((rpc) => rpc.UpdateOrganizationMemberRole({ memberId: updatedMember.id, organizationId: updatedMember.organizationId, role: updatedMember.role, }) ); await collection.utils.refetch({ throwOnError: true }); }, }) ); } export function invitationsCollection(scope: DashboardCollectionScope) { const id = organizationScopedCollectionId("invitationsCollection", scope); return collectionOptions(id, (client) => queryCollectionOptions({ id, queryClient: client.requireDependency("queryClient"), queryKey: () => organizationScopedQueryKey(scope, "invitations"), queryFn: async (ctx) => { const organizationId = scope.organizationId; if (!organizationId) { return []; } const data = await fetchRpc( (rpc) => rpc.ListOrganizationInvitations({ organizationId }), { signal: ctx.signal } ); return [...data]; }, getKey: (item) => item.id, onDelete: async ({ collection, transaction }) => { const mutation = transaction.mutations[0]; const { original: deletedInvitation } = mutation; await fetchRpc((rpc) => rpc.CancelOrganizationInvitation({ invitationId: deletedInvitation.id, organizationId: deletedInvitation.organizationId, }) ); await collection.utils.refetch({ throwOnError: true }); }, }) ); } export function commentCollection(scope: DashboardCollectionScope) { const id = slugScopedCollectionId("commentCollection", scope); return collectionOptions(id, (client) => queryCollectionOptions({ id, queryClient: client.requireDependency("queryClient"), queryKey: (opts) => slugScopedQueryKey( scope, "comment", parseLoadSubsetOptions(opts).filters ), syncMode: "on-demand", queryFn: async (ctx) => { const organizationId = scope.organizationId; const slug = scopePostSlug( scope, parseLoadSubsetOptions(ctx.meta?.loadSubsetOptions).filters ); if (!(organizationId && slug)) { return []; } // No catch: a policy denial, a lost session or a dropped connection is // the query's error state, not an empty thread. An empty list is a // successful RPC that found no comments. const data = await fetchRpc( (rpc) => rpc.ListComments({ organizationId, slug }), { signal: ctx.signal } ); return [...data]; }, getKey: (item) => item.id, onInsert: async ({ collection, transaction }) => { const mutation = transaction.mutations[0]; const { modified: newComment } = mutation; // SAFETY: post-ui attaches the transient author payload declared on // PostWithTransientAuthor above. const author = (newComment as PostWithTransientAuthor).author; await fetchRpc( (rpc) => rpc.CreateComment({ organizationId: newComment.organizationId, visibility: newComment.visibility, content: newComment.content, postId: newComment.postId, parentCommentId: newComment.parentCommentId, id: newComment.id, ...(author ? { author } : undefined), statusUpdateId: newComment.statusUpdateId ?? null, }), {} ); // The comment row is the mutation target and is already reconciled // optimistically; the activity timeline, post rows, and delete-hint set // are derived from it, so they refresh detached rather than holding the // insert open for three round trips. refetchInBackground( client.collection(postActivityCollection(scope)).utils.refetch(), client.collection(postCollection(scope)).utils.refetch(), client.collection(deleteEligibilityCollection(scope)).utils.refetch() ); await collection.utils.refetch({ throwOnError: true }); }, onDelete: async ({ collection, transaction }) => { const mutation = transaction.mutations[0]; const { original: deletedComment } = mutation; await fetchRpc( (rpc) => rpc.DeleteComment({ id: deletedComment.id, organizationId: deletedComment.organizationId, postId: deletedComment.postId, }), {} ); // Same as the insert path: the optimistic delete already removed the // row, so the derived collections refresh detached. refetchInBackground( client.collection(postActivityCollection(scope)).utils.refetch(), client.collection(postCollection(scope)).utils.refetch(), client.collection(deleteEligibilityCollection(scope)).utils.refetch() ); await collection.utils.refetch({ throwOnError: true }); }, onUpdate: async ({ collection, transaction }) => { const mutation = transaction.mutations[0]; const { modified: updatedComment } = mutation; await fetchRpc( (rpc) => rpc.UpdateComment({ id: updatedComment.id, organizationId: updatedComment.organizationId, postId: updatedComment.postId, content: updatedComment.content, visibility: updatedComment.visibility, }), {} ); // Only the activity entry is derived from an edit: refresh it detached. refetchInBackground( client.collection(postActivityCollection(scope)).utils.refetch() ); await collection.utils.refetch({ throwOnError: true }); }, }) ); } export function postActivityCollection(scope: DashboardCollectionScope) { const id = organizationScopedCollectionId("postActivityCollection", scope); return collectionOptions(id, (client) => queryCollectionOptions({ id, queryClient: client.requireDependency("queryClient"), queryKey: (opts) => { const postId = eqFilterValue( parseLoadSubsetOptions(opts).filters, "postId" ); return postId ? organizationScopedQueryKey(scope, "post-activity", "postId", postId) : organizationScopedQueryKey(scope, "post-activity"); }, syncMode: "on-demand", queryFn: async (ctx) => { const organizationId = scope.organizationId; const postId = eqFilterValue( parseLoadSubsetOptions(ctx.meta?.loadSubsetOptions).filters, "postId" ); if (!(organizationId && postId)) { return []; } const existingData = client .requireDependency("queryClient") .getQueryData(ctx.queryKey) ?? []; const since = existingData.reduce( (latest, activity) => latest === undefined || activity.createdAt > latest ? activity.createdAt : latest, undefined ); const changes = await fetchRpc( (rpc) => rpc.ListPostActivities({ organizationId, postId, ...(since === undefined ? undefined : { since }), }), { signal: ctx.signal } ); const merged = new Map( existingData.map((activity) => [activity.id, activity]) ); for (const activity of changes) { merged.set(activity.id, activity); } // Preserve the full merged history: the timeline renders every activity // and `since` only moves forward, so dropping entries would make that // history permanently unreachable (the backend offers no backfill for // older-than-window rows). const ordered = [...merged.values()].sort( (left, right) => +left.createdAt - +right.createdAt ); return ordered; }, getKey: (item) => item.id, }) ); } export function commentReactionCollection(scope: DashboardCollectionScope) { const id = slugScopedCollectionId("commentReactionCollection", scope); return collectionOptions(id, (client) => queryCollectionOptions({ id, queryClient: client.requireDependency("queryClient"), queryKey: (opts) => slugScopedQueryKey( scope, "comment-reaction", parseLoadSubsetOptions(opts).filters ), syncMode: "on-demand", queryFn: async (ctx) => { const organizationId = scope.organizationId; const slug = scopePostSlug( scope, parseLoadSubsetOptions(ctx.meta?.loadSubsetOptions).filters ); if (!(organizationId && slug)) { return []; } const data = await fetchRpc( (rpc) => rpc.ListCommentReactions({ organizationId, slug }), { signal: ctx.signal, } ); return [...data]; }, // SAFETY: The endpoint/API contract guarantees this response shape. getKey: getCommentReactionCollectionKey as ( item: CommentReactionRow ) => string, onInsert: async ({ collection, transaction }) => { const mutation = transaction.mutations[0]; const { modified: newCommentReaction } = mutation; await fetchRpc((rpc) => rpc.ToggleCommentReaction({ organizationId: newCommentReaction.organizationId, postId: newCommentReaction.postId, commentId: newCommentReaction.commentId, emoji: newCommentReaction.emoji, }) ); await collection.utils.refetch({ throwOnError: true }); }, onDelete: async ({ collection, transaction }) => { const mutation = transaction.mutations[0]; const { original: deletedCommentReaction } = mutation; await fetchRpc((rpc) => rpc.ToggleCommentReaction({ organizationId: deletedCommentReaction.organizationId, postId: deletedCommentReaction.postId, commentId: deletedCommentReaction.commentId, emoji: deletedCommentReaction.emoji, }) ); await collection.utils.refetch({ throwOnError: true }); }, }) ); } export function upvoteCollection(scope: DashboardCollectionScope) { const id = organizationScopedCollectionId("upvoteCollection", scope); return collectionOptions(id, (client) => queryCollectionOptions({ id, queryClient: client.requireDependency("queryClient"), // Lazy key: resolved at query time so navigation between organizations // never reuses another organization's cache entry (matches queryFn). queryKey: () => organizationScopedQueryKey(scope, "upvote"), queryFn: async (ctx) => { const organizationId = scope.organizationId; if (!organizationId) { return []; } const data = await fetchRpc( (rpc) => rpc.ListUpvotes({ organizationId }), { signal: ctx.signal, } ); return [...data]; }, // SAFETY: The endpoint/API contract guarantees this response shape. // SAFETY: The endpoint/API contract guarantees this response shape. getKey: getUpvoteCollectionKey as (item: UpvoteRow) => string, onInsert: async ({ collection, transaction }) => { const mutation = transaction.mutations[0]; const { modified: newUpvote } = mutation; await fetchRpc((rpc) => rpc.ToggleUpvote({ organizationId: newUpvote.organizationId, postId: newUpvote.postId, }) ); // The upvote row is the mutation target and holds the toggle // optimistically; vote counts derive from this collection client-side // (post rows carry no count), so the post rows and the delete-hint set // are derived refreshes that run detached. refetchInBackground( client.collection(postCollection(scope)).utils.refetch(), client.collection(deleteEligibilityCollection(scope)).utils.refetch() ); await collection.utils.refetch({ throwOnError: true }); }, onDelete: async ({ collection, transaction }) => { const mutation = transaction.mutations[0]; const { original: deletedUpvote } = mutation; await fetchRpc((rpc) => rpc.ToggleUpvote({ organizationId: deletedUpvote.organizationId, postId: deletedUpvote.postId, }) ); // Same as the insert path: derived refreshes run detached. refetchInBackground( client.collection(postCollection(scope)).utils.refetch(), client.collection(deleteEligibilityCollection(scope)).utils.refetch() ); await collection.utils.refetch({ throwOnError: true }); }, }) ); } /** * Creator delete hints for the whole organization, synced once. List rows * carry no delete hint (per-row probes on every list fetch); contributor * affordances derive from this small set client-side instead, and the * backend delete path re-validates. Presence of a row means eligible. * Refetch after engagement mutations (see the call sites below). */ export function deleteEligibilityCollection(scope: DashboardCollectionScope) { const id = organizationScopedCollectionId( "deleteEligibilityCollection", scope ); return collectionOptions(id, (client) => queryCollectionOptions({ id, queryClient: client.requireDependency("queryClient"), queryKey: () => organizationScopedQueryKey(scope, "delete-eligibility"), queryFn: async (ctx) => { const organizationId = scope.organizationId; if (!organizationId) { return []; } const result = await fetchRpc( (rpc) => rpc.ListPostDeleteEligibility({ organizationId }), { signal: ctx.signal } ); return result.eligibleIds.map((postId) => ({ organizationId, postId, })); }, getKey: (item) => item.postId, }) ); } export function postReactionCollection(scope: DashboardCollectionScope) { const id = slugScopedCollectionId("postReactionCollection", scope); return collectionOptions(id, (client) => queryCollectionOptions({ id, queryClient: client.requireDependency("queryClient"), queryKey: (opts) => slugScopedQueryKey( scope, "post-reaction", parseLoadSubsetOptions(opts).filters ), syncMode: "on-demand", queryFn: async (ctx) => { const organizationId = scope.organizationId; const slug = scopePostSlug( scope, parseLoadSubsetOptions(ctx.meta?.loadSubsetOptions).filters ); if (!(organizationId && slug)) { return []; } const data = await fetchRpc( (rpc) => rpc.ListPostReactions({ organizationId, slug }), { signal: ctx.signal, } ); return [...data]; // SAFETY: The endpoint/API contract guarantees this response shape. }, // SAFETY: The endpoint/API contract guarantees this response shape. // SAFETY: The endpoint/API contract guarantees this response shape. getKey: getPostReactionCollectionKey as (item: PostReactionRow) => string, onInsert: async ({ collection, transaction }) => { const mutation = transaction.mutations[0]; const { modified: newPostReaction } = mutation; await fetchRpc((rpc) => rpc.TogglePostReaction({ organizationId: newPostReaction.organizationId, postId: newPostReaction.postId, emoji: newPostReaction.emoji, }) ); await collection.utils.refetch({ throwOnError: true }); }, onDelete: async ({ collection, transaction }) => { const mutation = transaction.mutations[0]; const { original: deletedPostReaction } = mutation; await fetchRpc((rpc) => rpc.TogglePostReaction({ organizationId: deletedPostReaction.organizationId, postId: deletedPostReaction.postId, emoji: deletedPostReaction.emoji, }) ); await collection.utils.refetch({ throwOnError: true }); }, }) ); } export function siteCollection(scope: DashboardCollectionScope) { const id = organizationScopedCollectionId("siteCollection", scope); return collectionOptions(id, (client) => queryCollectionOptions({ id, queryClient: client.requireDependency("queryClient"), queryKey: () => organizationScopedQueryKey(scope, "site"), queryFn: async (ctx) => { const organizationId = scope.organizationId; if (!organizationId) { return []; } const data = await fetchRpc( (rpc) => rpc.ListSites({ organizationId }), { signal: ctx.signal, } ); return [...data]; }, getKey: (item) => item.id, refetchInterval: Duration.toMillis(Duration.minutes(30)), onUpdate: async ({ collection, transaction }) => { const mutation = transaction.mutations[0]; const { modified: updatedSite, original: previousSite } = mutation; await fetchRpc((rpc) => rpc.UpdateSite({ id: updatedSite.id, organizationId: updatedSite.organizationId, changelogVisibility: updatedSite.changelogVisibility, roadmapVisibility: updatedSite.roadmapVisibility, // Omitted unless this update is what changed it. Sending the cached // value on every save would let a rename revert a toggle another // member flipped while this page was open. ...(previousSite.helpCenterVisibility !== updatedSite.helpCenterVisibility ? { helpCenterVisibility: updatedSite.helpCenterVisibility } : {}), noIndex: updatedSite.noIndex, name: updatedSite.name, }) ); await collection.utils.refetch({ throwOnError: true }); }, }) ); } export function workspacePlanCollection(scope: DashboardCollectionScope) { const id = organizationScopedCollectionId("workspacePlanCollection", scope); return collectionOptions(id, (client) => queryCollectionOptions({ id, queryClient: client.requireDependency("queryClient"), queryKey: () => organizationScopedQueryKey(scope, "workspace-plan"), queryFn: async (ctx) => { const organizationId = scope.organizationId; if (!organizationId) { return []; } const data = await fetchRpc( (rpc) => rpc.GetWorkspacePlan({ organizationId }), { signal: ctx.signal, } ); return [data]; }, getKey: (item) => item.organizationId, staleTime: Number.POSITIVE_INFINITY, }) ); } /** * The workspace's live over-plan findings, one row per workspace. * * The gate reads this on every dashboard route. The RPC counts first and * fetches resource previews only when a finding is already over, so a * compliant workspace costs a handful of indexed counts and nothing else. * `staleTime` is infinite on purpose: the plan changes through a webhook, and * the gate refetches this collection after every remediation action, so there * is nothing to poll. */ export function planComplianceCollection(scope: DashboardCollectionScope) { const id = organizationScopedCollectionId("planComplianceCollection", scope); return collectionOptions(id, (client) => queryCollectionOptions({ id, queryClient: client.requireDependency("queryClient"), queryKey: () => organizationScopedQueryKey(scope, "plan-compliance"), queryFn: async (ctx) => { const organizationId = scope.organizationId; if (!organizationId) { return []; } const data = await fetchRpc( (rpc) => rpc.GetWorkspacePlanCompliance({ organizationId }), { signal: ctx.signal, } ); return [data]; }, getKey: (item) => item.organizationId, staleTime: Number.POSITIVE_INFINITY, }) ); } /** * The plan-compliance collection for an explicit workspace. * * Route loaders run before the URL reflects the navigation, so they cannot use * `dashboardCollections`, whose scope comes from the live pathname. Naming the * workspace is what keeps a gate check on the destination from reading the * source organization's snapshot. */ export const planComplianceCollectionFor = (organizationId: string) => materialize( getBrowserDbClient(), planComplianceCollection({ organizationId, postSlug: undefined }) ); export function postSubscriptionCollection(scope: DashboardCollectionScope) { const id = slugScopedCollectionId("postSubscriptionCollection", scope); return collectionOptions(id, (client) => queryCollectionOptions({ id, queryClient: client.requireDependency("queryClient"), queryKey: (opts) => slugScopedQueryKey( scope, "post-subscription", parseLoadSubsetOptions(opts).filters ), syncMode: "on-demand", queryFn: async (ctx) => { const organizationId = scope.organizationId; const slug = scopePostSlug( scope, parseLoadSubsetOptions(ctx.meta?.loadSubsetOptions).filters ); if (!(organizationId && slug)) { return []; } const data = await fetchRpc( (rpc) => rpc.ListPostSubscriptions({ organizationId, slug }), { signal: ctx.signal, } ); // SAFETY: The endpoint/API contract guarantees this response shape. return [...data]; // SAFETY: The runtime invariant checked by the surrounding code guarantees this type. }, // SAFETY: The endpoint/API contract guarantees this response shape. // SAFETY: The endpoint/API contract guarantees this response shape. getKey: getPostSubscriptionCollectionKey as ( item: PostSubscriptionRow ) => string, onInsert: async ({ collection, transaction }) => { const mutation = transaction.mutations[0]; const { modified: newSubscription } = mutation; await fetchRpc((rpc) => rpc.CreatePostSubscription({ organizationId: newSubscription.organizationId, postId: newSubscription.postId, }) ); await collection.utils.refetch({ throwOnError: true }); }, onDelete: async ({ collection, transaction }) => { const mutation = transaction.mutations[0]; const { original: deletedSubscription } = mutation; await fetchRpc((rpc) => rpc.DeletePostSubscription({ organizationId: deletedSubscription.organizationId, postId: deletedSubscription.postId, }) ); await collection.utils.refetch({ throwOnError: true }); }, }) ); } export function jwtSecretCollection(scope: DashboardCollectionScope) { const id = organizationScopedCollectionId("jwtSecretCollection", scope); return collectionOptions(id, (client) => queryCollectionOptions({ id, queryClient: client.requireDependency("queryClient"), queryKey: () => organizationScopedQueryKey(scope, "jwt-secret"), queryFn: async (ctx) => { const organizationId = scope.organizationId; if (!organizationId) { return []; } const data = await fetchRpc( (rpc) => rpc.ListJwtSecrets({ organizationId }), { signal: ctx.signal } ); return [...data]; }, getKey: (item) => item.id, }) ); } export function contactCollection(scope: DashboardCollectionScope) { const id = organizationScopedCollectionId("contactCollection", scope); return collectionOptions(id, (client) => queryCollectionOptions({ id, queryClient: client.requireDependency("queryClient"), queryKey: () => organizationScopedQueryKey(scope, "contact"), queryFn: async (ctx) => { const organizationId = scope.organizationId; if (!organizationId) { return []; } const data = await fetchRpc( (rpc) => rpc.ListContacts({ organizationId }), { signal: ctx.signal } ); return [...data]; }, getKey: (item) => item.id, onUpdate: async ({ collection, transaction }) => { const mutation = transaction.mutations[0]; const { modified: updatedContact } = mutation; await fetchRpc((rpc) => rpc.UpdateContact({ id: updatedContact.id, organizationId: updatedContact.organizationId, externalId: updatedContact.externalId, email: updatedContact.email, name: updatedContact.name, phone: updatedContact.phone, avatar: updatedContact.avatar, companyId: updatedContact.companyId, }) ); await collection.utils.refetch({ throwOnError: true }); }, onInsert: async ({ collection, transaction }) => { const mutation = transaction.mutations[0]; const { modified: newContact } = mutation; await fetchRpc((rpc) => rpc.CreateContact({ id: newContact.id, organizationId: newContact.organizationId, externalId: newContact.externalId, email: newContact.email, name: newContact.name, phone: newContact.phone, avatar: newContact.avatar, companyId: newContact.companyId, }) ); await collection.utils.refetch({ throwOnError: true }); }, onDelete: async ({ collection, transaction }) => { const mutation = transaction.mutations[0]; const { original: deletedContact } = mutation; await fetchRpc((rpc) => rpc.DeleteContact({ id: deletedContact.id, organizationId: deletedContact.organizationId, }) ); await collection.utils.refetch({ throwOnError: true }); }, }) ); } export function companyCollection(scope: DashboardCollectionScope) { const id = organizationScopedCollectionId("companyCollection", scope); return collectionOptions(id, (client) => queryCollectionOptions({ id, queryClient: client.requireDependency("queryClient"), queryKey: () => organizationScopedQueryKey(scope, "company"), queryFn: async (ctx) => { const organizationId = scope.organizationId; if (!organizationId) { return []; } const data = await fetchRpc( (rpc) => rpc.ListCompanies({ organizationId }), { signal: ctx.signal } ); return [...data]; }, getKey: (item) => item.id, onUpdate: async ({ collection, transaction }) => { const mutation = transaction.mutations[0]; const { modified: updatedCompany } = mutation; await fetchRpc((rpc) => rpc.UpdateCompany({ id: updatedCompany.id, organizationId: updatedCompany.organizationId, externalId: updatedCompany.externalId, name: updatedCompany.name, avatar: updatedCompany.avatar, externalCreatedAt: updatedCompany.externalCreatedAt, }) ); await collection.utils.refetch({ throwOnError: true }); }, onInsert: async ({ collection, transaction }) => { const mutation = transaction.mutations[0]; const { modified: newCompany } = mutation; await fetchRpc((rpc) => rpc.CreateCompany({ id: newCompany.id, organizationId: newCompany.organizationId, externalId: newCompany.externalId, name: newCompany.name, avatar: newCompany.avatar, externalCreatedAt: newCompany.externalCreatedAt, }) ); await collection.utils.refetch({ throwOnError: true }); }, onDelete: async ({ collection, transaction }) => { const mutation = transaction.mutations[0]; const { original: deletedCompany } = mutation; await fetchRpc((rpc) => rpc.DeleteCompany({ id: deletedCompany.id, organizationId: deletedCompany.organizationId, }) ); await collection.utils.refetch({ throwOnError: true }); }, }) ); } //Todo scope export function contactAttributeDefinitionCollection( scope: DashboardCollectionScope ) { const id = organizationScopedCollectionId( "contactAttributeDefinitionCollection", scope ); return collectionOptions(id, (client) => queryCollectionOptions({ id, queryClient: client.requireDependency("queryClient"), queryKey: () => organizationScopedQueryKey(scope, "contact-attribute-definition"), queryFn: async (ctx) => { const organizationId = scope.organizationId; if (!organizationId) { return []; } const data = await fetchRpc( (rpc) => rpc.ListContactAttributeDefinitions({ organizationId }), { signal: ctx.signal } ); return [...data]; }, getKey: (item) => item.id, onUpdate: async ({ collection, transaction }) => { const mutation = transaction.mutations[0]; const { modified: definition } = mutation; await fetchRpc((rpc) => rpc.UpdateContactAttributeDefinition({ id: definition.id, name: definition.name, key: definition.key, description: definition.description, isRequired: definition.isRequired, organizationId: definition.organizationId, }) ); await collection.utils.refetch({ throwOnError: true }); }, onInsert: async ({ collection, transaction }) => { const mutation = transaction.mutations[0]; const { modified: definition } = mutation; await fetchRpc((rpc) => rpc.CreateContactAttributeDefinition({ id: definition.id, name: definition.name, key: definition.key, description: definition.description, type: definition.type, isRequired: definition.isRequired, organizationId: definition.organizationId, }) ); await collection.utils.refetch({ throwOnError: true }); }, onDelete: async ({ collection, transaction }) => { const mutation = transaction.mutations[0]; const { original: definition } = mutation; await fetchRpc((rpc) => rpc.DeleteContactAttributeDefinition({ id: definition.id, organizationId: definition.organizationId, }) ); await collection.utils.refetch({ throwOnError: true }); }, }) ); } //Todo scope export function companyAttributeDefinitionCollection( scope: DashboardCollectionScope ) { const id = organizationScopedCollectionId( "companyAttributeDefinitionCollection", scope ); return collectionOptions(id, (client) => queryCollectionOptions({ id, queryClient: client.requireDependency("queryClient"), queryKey: () => organizationScopedQueryKey(scope, "company-attribute-definition"), queryFn: async (ctx) => { const organizationId = scope.organizationId; if (!organizationId) { return []; } const data = await fetchRpc( (rpc) => rpc.ListCompanyAttributeDefinitions({ organizationId }), { signal: ctx.signal } ); return [...data]; }, getKey: (item) => item.id, onUpdate: async ({ collection, transaction }) => { const mutation = transaction.mutations[0]; const { modified: definition } = mutation; await fetchRpc((rpc) => rpc.UpdateCompanyAttributeDefinition({ id: definition.id, name: definition.name, key: definition.key, description: definition.description, isRequired: definition.isRequired, organizationId: definition.organizationId, }) ); await collection.utils.refetch({ throwOnError: true }); }, onInsert: async ({ collection, transaction }) => { const mutation = transaction.mutations[0]; const { modified: definition } = mutation; await fetchRpc((rpc) => rpc.CreateCompanyAttributeDefinition({ id: definition.id, name: definition.name, key: definition.key, description: definition.description, type: definition.type, isRequired: definition.isRequired, organizationId: definition.organizationId, }) ); await collection.utils.refetch({ throwOnError: true }); }, onDelete: async ({ collection, transaction }) => { const mutation = transaction.mutations[0]; const { original: definition } = mutation; await fetchRpc((rpc) => rpc.DeleteCompanyAttributeDefinition({ id: definition.id, organizationId: definition.organizationId, }) ); await collection.utils.refetch({ throwOnError: true }); }, }) ); } export function contactAttributeValueCollection( scope: DashboardCollectionScope ) { const id = organizationScopedCollectionId( "contactAttributeValueCollection", scope ); return collectionOptions(id, (client) => queryCollectionOptions({ id, queryClient: client.requireDependency("queryClient"), queryKey: () => organizationScopedQueryKey(scope, "contact-attribute-value"), queryFn: async (ctx) => { const organizationId = scope.organizationId; if (!organizationId) { return []; } const data = await fetchRpc( (rpc) => rpc.ListContactAttributeValues({ organizationId }), { signal: ctx.signal } ); return [...data]; }, getKey: (item) => item.id, }) ); } export function companyAttributeValueCollection( scope: DashboardCollectionScope ) { const id = organizationScopedCollectionId( "companyAttributeValueCollection", scope ); return collectionOptions(id, (client) => queryCollectionOptions({ id, queryClient: client.requireDependency("queryClient"), queryKey: () => organizationScopedQueryKey(scope, "company-attribute-value"), queryFn: async (ctx) => { const organizationId = scope.organizationId; if (!organizationId) { return []; } const data = await fetchRpc( (rpc) => rpc.ListCompanyAttributeValues({ organizationId }), { signal: ctx.signal } ); return [...data]; }, getKey: (item) => item.id, }) ); } export function roadmapCollection(scope: DashboardCollectionScope) { const id = organizationScopedCollectionId("roadmapCollection", scope); return collectionOptions(id, (client) => queryCollectionOptions({ id, queryClient: client.requireDependency("queryClient"), queryKey: () => organizationScopedQueryKey(scope, "roadmap"), queryFn: async (ctx) => { const organizationId = scope.organizationId; if (!organizationId) { return []; } const data = await fetchRpc( (rpc) => rpc.ListRoadmaps({ organizationId }), { signal: ctx.signal, } ); return [...data]; }, getKey: (item) => item.id, onInsert: async ({ collection, transaction }) => { const mutation = transaction.mutations[0]; const { modified: newRoadmap } = mutation; await fetchRpc((rpc) => rpc.CreateRoadmap({ id: newRoadmap.id, organizationId: newRoadmap.organizationId, name: newRoadmap.name, slug: newRoadmap.slug, description: newRoadmap.description, isPrimary: newRoadmap.isPrimary, mode: newRoadmap.mode, visibility: newRoadmap.visibility, filter: newRoadmap.filter, }) ); await collection.utils.refetch({ throwOnError: true }); }, onUpdate: async ({ collection, transaction }) => { const mutation = transaction.mutations[0]; const { modified: updatedRoadmap } = mutation; await fetchRpc((rpc) => rpc.UpdateRoadmap({ id: updatedRoadmap.id, organizationId: updatedRoadmap.organizationId, name: updatedRoadmap.name, slug: updatedRoadmap.slug, description: updatedRoadmap.description, isPrimary: updatedRoadmap.isPrimary, mode: updatedRoadmap.mode, visibility: updatedRoadmap.visibility, filter: updatedRoadmap.filter, }) ); await collection.utils.refetch({ throwOnError: true }); }, onDelete: async ({ transaction }) => { const mutation = transaction.mutations[0]; const { original: deletedRoadmap } = mutation; await fetchRpc((rpc) => rpc.DeleteRoadmap({ id: deletedRoadmap.id, organizationId: deletedRoadmap.organizationId, }) ); // Deleting the primary promotes a successor in the same server // transaction; read the rows back so the cached `isPrimary` flags match // the handoff instead of leaving the organization without a primary in // the client cache. await client .collection(roadmapCollection(scope)) .utils.refetch({ throwOnError: true }); }, }) ); } export function roadmapColumnCollection(scope: DashboardCollectionScope) { const id = organizationScopedCollectionId("roadmapColumnCollection", scope); return collectionOptions(id, (client) => queryCollectionOptions({ id, queryClient: client.requireDependency("queryClient"), queryKey: () => organizationScopedQueryKey(scope, "roadmap-column"), queryFn: async (ctx) => { const organizationId = scope.organizationId; if (!organizationId) { return []; } const data = await fetchRpc( (rpc) => rpc.ListRoadmapColumns({ organizationId }), { signal: ctx.signal } ); return [...data]; }, getKey: (item) => item.id, onInsert: async ({ collection, transaction }) => { const mutation = transaction.mutations[0]; const { modified: newColumn } = mutation; const organizationId = scope.organizationId; if (!organizationId) { throw new Error("Missing organization id"); } await fetchRpc((rpc) => rpc.CreateRoadmapColumn({ id: newColumn.id, roadmapId: newColumn.roadmapId, organizationId, name: newColumn.name, position: newColumn.position, config: { type: "status", statusId: newColumn.statusId }, }) ); await collection.utils.refetch({ throwOnError: true }); }, onUpdate: async ({ collection, transaction }) => { const mutation = transaction.mutations[0]; const { modified: updatedColumn } = mutation; const organizationId = scope.organizationId; if (!organizationId) { throw new Error("Missing organization id"); } await fetchRpc((rpc) => rpc.UpdateRoadmapColumn({ id: updatedColumn.id, roadmapId: updatedColumn.roadmapId, organizationId, name: updatedColumn.name, position: updatedColumn.position, config: { type: "status", statusId: updatedColumn.statusId }, }) ); await collection.utils.refetch({ throwOnError: true }); }, onDelete: async ({ collection, transaction }) => { const mutation = transaction.mutations[0]; const { original: deletedColumn } = mutation; const organizationId = scope.organizationId; if (!organizationId) { throw new Error("Missing organization id"); } await fetchRpc((rpc) => rpc.DeleteRoadmapColumn({ id: deletedColumn.id, roadmapId: deletedColumn.roadmapId, organizationId, }) ); await collection.utils.refetch({ throwOnError: true }); }, }) ); } /** * `createIndex` is a `Collection` method rather than a config field, so an index * cannot live in a descriptor config. Indexes are applied on first * materialization instead, keyed by collection id — which is what `DbClient` * memoizes on — so repeated reads do not stack duplicate indexes. */ const indexedCollectionIds = new Set(); /** * A member's saved board queries for one surface. * * `boardId` is part of the collection's identity because the board toolbar and * the organization-wide feedback list are separate surfaces: a view saved on * one board must not appear on another, and the two lists must not share a * cache entry. `null` is the feedback list, spelled out in the id so it cannot * collide with a board id. * * `memberId` is part of the identity for the same reason: visibility is read * for the signed-in member, and a collection keyed only by workspace and board * could serve one member's private views from a cache entry the previous * session filled. */ export function savedViewCollection( scope: DashboardCollectionScope, boardId: string | null, memberId: string | undefined ) { const id = `${organizationScopedCollectionId( "savedViewCollection", scope )}:${memberId ?? "anonymous"}:${boardId ?? "all-feedback"}`; return collectionOptions(id, (client) => queryCollectionOptions({ id, queryClient: client.requireDependency("queryClient"), queryKey: () => organizationScopedQueryKey( scope, "saved-view", memberId ?? "anonymous", boardId ?? "all-feedback" ), queryFn: async (ctx) => { const organizationId = scope.organizationId; if (!organizationId) { return []; } const data = await fetchRpc( (rpc) => rpc.ListSavedViews({ boardId, organizationId }), { signal: ctx.signal } ); return [...data]; }, getKey: (item) => item.id, onInsert: async ({ collection, transaction }) => { const mutation = transaction.mutations[0]; const { modified: view } = mutation; await fetchRpc((rpc) => rpc.CreateSavedView({ boardId: view.boardId, description: view.description, id: view.id, isPrivate: view.isPrivate, name: view.name, organizationId: view.organizationId, query: view.query, }) ); await collection.utils.refetch({ throwOnError: true }); }, onUpdate: async ({ collection, transaction }) => { const mutation = transaction.mutations[0]; const { modified: view, original } = mutation; // Unchanged fields are omitted so the handler keeps the stored value. // The sheet leaves `name`, `query`, and `isPrivate` untouched unless // the member changed them, but the row itself may be stale; letting // the server decide is what stops that stale copy from overwriting a // newer field. const queryChanged = JSON.stringify(original.query) !== JSON.stringify(view.query); const nameChanged = original.name !== view.name; const isPrivateChanged = original.isPrivate !== view.isPrivate; const update = { description: view.description, id: view.id, organizationId: view.organizationId, }; const withName = nameChanged ? { ...update, name: view.name } : update; const withVisibility = isPrivateChanged ? { ...withName, isPrivate: view.isPrivate } : withName; const payload = queryChanged ? { ...withVisibility, query: view.query } : withVisibility; await fetchRpc((rpc) => rpc.UpdateSavedView(payload)); await collection.utils.refetch({ throwOnError: true }); }, onDelete: async ({ collection, transaction }) => { const mutation = transaction.mutations[0]; const { original: view } = mutation; await fetchRpc((rpc) => rpc.DeleteSavedView({ id: view.id, organizationId: view.organizationId, }) ); await collection.utils.refetch({ throwOnError: true }); }, }) ); } /** * The saved views for one workspace surface, through the browser `DbClient`. * * Exported as a function rather than a getter on `dashboardCollections` * because the board toolbar and the feedback toolbar ask for different * surfaces at the same time — a single getter would have to pick one. */ export const savedViewCollectionFor = ( organizationId: string, boardId: string | null, memberId: string | undefined ) => materialize( getBrowserDbClient(), savedViewCollection( { organizationId, postSlug: undefined }, boardId, memberId ) ); /** * Materializes a descriptor with the row type its factory declares. * * `DbClient.collection` resolves its overload from the descriptor alone, and * under TypeScript 7.1 the schema-taking overload also matches a schema-less * descriptor: `T` is inferred as `never`, so a collection materialized through * it answers every live query with `never` rows. Naming the three type * arguments selects the schema-less overload, which keeps `T` — the row type * `queryCollectionOptions` inferred from the descriptor's `queryFn`. */ function materialize< T extends object, TKey extends string | number, TUtils extends UtilsRecord, >( client: DbClient, descriptor: CollectionOptions & NonSingleResult ) { return client.collection(descriptor); } function withIndexes( collection: TCollection, addIndexes: (collection: TCollection) => void ): TCollection { if (!indexedCollectionIds.has(collection.id)) { indexedCollectionIds.add(collection.id); addIndexes(collection); } return collection; } /** * Materializes every dashboard collection for the current scope through the * browser `DbClient`. * * Getter-based rather than a frozen map so a collection's identity follows the * current organization (and post) instead of being fixed at module load. The * `DbClient` memoizes by descriptor id, so repeated reads within one scope * return the same instance and React memo dependencies stay stable. */ const makeDashboardCollections = ( getScope: () => DashboardCollectionScope ) => ({ get boardCollection() { return withIndexes( materialize(getBrowserDbClient(), boardCollection(getScope())), (collection) => { collection.createIndex((row) => row.organizationId, { indexType: BasicIndex, }); // Post board queries join posts against boards by id. collection.createIndex((row) => row.id, { indexType: BasicIndex, }); } ); }, get helpCenterTopicCollection() { return materialize( getBrowserDbClient(), helpCenterTopicCollection(getScope()) ); }, get helpCenterArticleCollection() { return materialize( getBrowserDbClient(), helpCenterArticleCollection(getScope()) ); }, get changelogCategoryCollection() { return materialize( getBrowserDbClient(), changelogCategoryCollection(getScope()) ); }, get changelogCategoryLinkCollection() { return materialize( getBrowserDbClient(), changelogCategoryLinkCollection(getScope()) ); }, get changelogCollection() { return materialize(getBrowserDbClient(), changelogCollection(getScope())); }, get changelogPostCollection() { return withIndexes( materialize(getBrowserDbClient(), changelogPostCollection(getScope())), (collection) => { // Changelog completed-posts joins entries against posts by post id. collection.createIndex((row) => row.postId, { indexType: BasicIndex, }); } ); }, get commentCollection() { return materialize(getBrowserDbClient(), commentCollection(getScope())); }, get commentReactionCollection() { return materialize( getBrowserDbClient(), commentReactionCollection(getScope()) ); }, get companyCollection() { return materialize(getBrowserDbClient(), companyCollection(getScope())); }, get deleteEligibilityCollection() { return withIndexes( materialize( getBrowserDbClient(), deleteEligibilityCollection(getScope()) ), (collection) => { collection.createIndex((row) => row.postId, { indexType: BasicIndex, }); } ); }, get companyAttributeDefinitionCollection() { return materialize( getBrowserDbClient(), companyAttributeDefinitionCollection(getScope()) ); }, get companyAttributeValueCollection() { return materialize( getBrowserDbClient(), companyAttributeValueCollection(getScope()) ); }, get contactAttributeDefinitionCollection() { return materialize( getBrowserDbClient(), contactAttributeDefinitionCollection(getScope()) ); }, get contactAttributeValueCollection() { return materialize( getBrowserDbClient(), contactAttributeValueCollection(getScope()) ); }, get contactCollection() { return materialize(getBrowserDbClient(), contactCollection(getScope())); }, get invitationsCollection() { return materialize(getBrowserDbClient(), invitationsCollection(getScope())); }, get jwtSecretCollection() { return materialize(getBrowserDbClient(), jwtSecretCollection(getScope())); }, get membersCollection() { return materialize(getBrowserDbClient(), membersCollection(getScope())); }, get membershipCollection() { return withIndexes( materialize(getBrowserDbClient(), membershipCollection(getScope())), (collection) => { // Workspace details joins memberships against organizations by org id. collection.createIndex((row) => row.organizationId, { indexType: BasicIndex, }); } ); }, get organizationCollection() { return withIndexes( materialize(getBrowserDbClient(), organizationCollection(getScope())), (collection) => { // Workspace details joins memberships against organizations by org id. collection.createIndex((row) => row.id, { indexType: BasicIndex, }); } ); }, get postCollection() { return withIndexes( materialize(getBrowserDbClient(), postCollection(getScope())), (collection) => { collection.createIndex((row) => row.createdAt, { indexType: BasicIndex, }); collection.createIndex((row) => row.statusId, { indexType: BasicIndex, }); collection.createIndex((row) => row.organizationId, { indexType: BasicIndex, }); collection.createIndex((row) => row.boardId, { indexType: BasicIndex, }); } ); }, get postDetailCollection() { return materialize(getBrowserDbClient(), postDetailCollection(getScope())); }, get postActivityCollection() { return materialize( getBrowserDbClient(), postActivityCollection(getScope()) ); }, get postReactionCollection() { return materialize( getBrowserDbClient(), postReactionCollection(getScope()) ); }, get postStatusCollection() { return withIndexes( materialize(getBrowserDbClient(), postStatusCollection(getScope())), (collection) => { collection.createIndex((row) => row.organizationId, { indexType: BasicIndex, }); // Board, changelog, and merge queries join posts against status rows by id. collection.createIndex((row) => row.id, { indexType: BasicIndex, }); } ); }, get postSubscriptionCollection() { return materialize( getBrowserDbClient(), postSubscriptionCollection(getScope()) ); }, get roadmapCollection() { return materialize(getBrowserDbClient(), roadmapCollection(getScope())); }, get roadmapColumnCollection() { return withIndexes( materialize(getBrowserDbClient(), roadmapColumnCollection(getScope())), (collection) => { // Roadmap columns join statuses and roadmaps by their foreign keys. collection.createIndex((row) => row.statusId, { indexType: BasicIndex, }); collection.createIndex((row) => row.roadmapId, { indexType: BasicIndex, }); } ); }, get postTagCollection() { return withIndexes( materialize(getBrowserDbClient(), postTagCollection(getScope())), (collection) => { collection.createIndex((row) => row.organizationId, { indexType: BasicIndex, }); collection.createIndex((row) => row.postId, { indexType: BasicIndex, }); collection.createIndex((row) => row.tagId, { indexType: BasicIndex, }); } ); }, get siteCollection() { return materialize(getBrowserDbClient(), siteCollection(getScope())); }, get tagCollection() { return withIndexes( materialize(getBrowserDbClient(), tagCollection(getScope())), (collection) => { collection.createIndex((row) => row.organizationId, { indexType: BasicIndex, }); } ); }, get upvoteCollection() { return withIndexes( materialize(getBrowserDbClient(), upvoteCollection(getScope())), (collection) => { collection.createIndex((row) => row.organizationId, { indexType: BasicIndex, }); collection.createIndex((row) => row.postId, { indexType: BasicIndex, }); } ); }, get workspacePlanCollection() { return materialize( getBrowserDbClient(), workspacePlanCollection(getScope()) ); }, get planComplianceCollection() { return materialize( getBrowserDbClient(), planComplianceCollection(getScope()) ); }, }); export const dashboardCollections = makeDashboardCollections(currentScope); /** * The same collections, for a scope named by the caller. * * A route `beforeLoad` and the dashboard layout run before the browser history * has committed a client-side navigation, so `currentScope()` can still name * the route being left. Naming the destination scope is what keeps a preload * or a layout provider from materializing source-scoped collections and then * reading them with destination filters. */ export const dashboardCollectionsFor = (scope: DashboardCollectionScope) => makeDashboardCollections(() => scope); export type DashboardCollections = typeof dashboardCollections;