@aglyn/plugins-data 1.23.1 → 1.25.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +12 -11
- package/src/lib/components/dataset-icon-field-input.component.d.ts +30 -0
- package/src/lib/components/dataset-icon-field-input.component.js +142 -0
- package/src/lib/components/dataset-icon-field-input.component.js.map +1 -0
- package/src/lib/components/dataset-icon-picker.component.d.ts +33 -0
- package/src/lib/components/dataset-icon-picker.component.js +49 -0
- package/src/lib/components/dataset-icon-picker.component.js.map +1 -0
- package/src/lib/components/host-datasets-card.component.js +7 -2
- package/src/lib/components/host-datasets-card.component.js.map +1 -1
- package/src/lib/declarations.server.js +3 -0
- package/src/lib/declarations.server.js.map +1 -1
- package/src/lib/model/dataset-icon-field.d.ts +52 -0
- package/src/lib/model/dataset-icon-field.js +86 -0
- package/src/lib/model/dataset-icon-field.js.map +1 -0
- package/src/lib/plugin.js +6 -0
- package/src/lib/plugin.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/data/src/lib/components/host-datasets-card.component.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\nimport type { ScopePlaced } from '@aglyn/aglyn/app-utils/site-placement'\nimport { TransferResumeImport } from '@aglyn/aglyn/app-utils/transfer-resume-import'\nimport {\n type AglynOrgBilling,\n checkDatasetQuota,\n checkEntitlement,\n checkQuota,\n getCustomFieldType,\n PageHeaderActions,\n PageHeaderRecord,\n pluginDocsHelp,\n scopeTokensForHost,\n useTransferLauncher,\n visibleToHost,\n} from '@aglyn/aglyn'\nimport { nameSearchKey } from '@aglyn/aglyn/app-utils/name-search'\nimport { HubSections, type HubSection } from '@aglyn/shared-ui-next/components/hub-tabs'\nimport { AppLink, CardDisplay, MdiIcon, useConfirmationContext } from '@aglyn/shared-ui-jsx'\nimport { mdiArrowLeft } from '@aglyn/shared-data-mdi'\nimport ListFilterChips from '@aglyn/shared-ui-jsx/components/list-filter-chips.component'\nimport { ListPagination } from '@aglyn/shared-ui-jsx/components/list-pagination.component'\nimport ListQueryNotices, {\n listQueryRefusals,\n} from '@aglyn/shared-ui-jsx/components/list-query-notices.component'\nimport {\n ListTable,\n listActionsColumn,\n} from '@aglyn/shared-ui-jsx/components/list-table.component'\nimport QuotaReadoutComponent from '@aglyn/shared-ui-jsx/components/quota-readout.component'\nimport { listFilterGridColumns } from '@aglyn/shared-ui-jsx/const/list-grid-filter'\nimport { useListGridFilter } from '@aglyn/shared-ui-jsx/hooks/use-list-grid-filter'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport { Timestamp } from '@aglyn/shared-util-timestamp'\nimport {\n Alert,\n Box,\n Button,\n Chip,\n CircularProgress,\n Dialog,\n DialogActions,\n DialogContent,\n DialogTitle,\n MenuItem,\n Stack,\n TextField,\n Tooltip,\n Typography,\n} from '@mui/material'\nimport {\n collection,\n deleteDoc,\n deleteField,\n doc,\n endAt,\n getCountFromServer,\n getDoc,\n getDocs,\n limit,\n orderBy,\n query,\n startAt,\n where,\n setDoc,\n writeBatch,\n} from 'firebase/firestore'\nimport { useRouter } from 'next/navigation'\nimport { useCallback, useEffect, useMemo, useState } from 'react'\nimport { useListColumnSort } from '@aglyn/shared-ui-jsx/hooks/use-list-column-sort'\nimport {\n useFirestore,\n useFirestoreCollection,\n useFirestoreDoc,\n useHostActivityLogger,\n useOrgDataScope,\n usePagedCollection,\n useScopeTokens,\n useUser,\n} from '@aglyn/tenant-feature-instance'\nimport { listQueryConstraints } from '@aglyn/tenant-feature-instance/hooks/use-list-query'\nimport { authorizedFetch } from '@aglyn/shared-util-http/authorized-token'\nimport { DatasetSchemaDialog } from './dataset-schema-dialog.component'\nimport { DatasetRecordDialog, DatasetRecordFieldList } from './dataset-record-dialog.component'\nimport { DatasetRecordSiteContext } from './dataset-field-inputs.component'\nimport {\n datasetRecordFilter,\n planRecordQuery,\n recordColumn,\n} from './dataset-record-filter'\nimport { coerceDocumentValues, datasetIntegrityUpdate, datasetValueToInput, effectiveDatasetModel, formatDatasetValue, modelFromFieldEntries, validateDocument } from '../model/dataset-models'\nimport { fillRecordAddresses } from '../record-pages/record-pages'\nimport { planReferenceFixups, referencingFieldIds, restrictedDeleteMessage } from '../model/dataset-record-delete-plan'\nimport { BlockedControl } from '@aglyn/shared-ui-jsx/components/blocked-control.component'\nimport { datasetListScope } from '../model/dataset-record-list'\nimport {\n DATASETS_EXPORT_REFUSAL,\n DATASETS_VIEW_RECORDS_REFUSAL,\n DATASETS_WRITE_REFUSAL,\n useDatasetWritesBlocked,\n} from './use-dataset-writes-blocked'\nimport { DATASET_SAMPLE_RECORD_NOTE, datasetDisplayName, isSampleDatasetRecord, parseDatasetFieldEntries } from '../model/datasets'\nimport { datasetTransferResourceKey } from '../transfer/dataset-transfer-key'\nimport {\n DATASET_RAIL_GROUP_AT,\n type DatasetRailEntry,\n datasetCreatedLabel,\n datasetPickerLabelsOf,\n datasetRailName,\n datasetRecordTitle,\n datasetRailSecondary,\n datasetSharingLabel,\n datasetSourceLabel,\n groupDatasetsBySharing,\n sortDatasetsByName,\n} from '../model/dataset-rail'\nimport { useOrgSites } from './use-org-sites'\n\nexport interface HostDatasetsCardProps {\n /** Host context: resolves the owning org and logs host activity. */\n hostId?: string\n /**\n * Direct org scope (AGL-239): the org Data page renders the editor\n * without any host context. Wins over `hostId` resolution when set.\n */\n orgId?: string\n /**\n * The resolved entitlement source (org billing doc). Passed in by both\n * callers (the plugin Data page via the shell, the org Data page via its\n * own resolver) so this relocated card runs entitlement/quota checks\n * without console-app org/session hooks (AGL-395).\n */\n org?: Partial<AglynOrgBilling>\n /**\n * The Data page's own address (AGL-4047): each dataset is a tab of the\n * page's rail, at `<basePath>/<datasetId>`. Handed down by both callers —\n * the site's plugin route and the organization Data page.\n */\n basePath?: string\n /**\n * The path beneath {@link basePath}: `[datasetId]` on a dataset's tab,\n * `[datasetId, 'records', recordId]` on one of its records, and empty on the\n * bare page, which opens the first dataset.\n */\n segments?: readonly string[]\n}\n\n/**\n * The sentence that says who a NEW dataset is shared with, for the card and\n * for the site Data page's banner above it.\n *\n * `siteOnly` is true only on a site's Data page in an org whose Default\n * sharing is \"Only the site they were created in\". Everywhere else a new\n * dataset starts on All sites: the org Data page has no site to limit it to.\n */\n/** The records walk serves no header order: every header sorts the page. */\nconst NO_QUERY_SORTS: never[] = []\n\n/** The grid's own Export and Print, off for a member without \"Export data\" (AGL-4047). */\nconst EXPORT_OFF_TOOLBAR = {\n toolbar: { csvOptions: { disableToolbarButton: true }, printOptions: { disableToolbarButton: true } },\n}\n\n/** Stable, so an empty answer does not re-render the card. */\nconst NO_DATASETS: any[] = []\n\n/**\n * The datasets the rail loads at a time, and the most a delete's reference\n * check walks. \"Show more datasets\" loads the next window, so the rail\n * reaches every dataset however many there are (AGL-4047).\n */\nconst DATASET_LIST_WINDOW = 100\n\n/** A dataset read off its document, as the card's rows carry it. */\nconst datasetRow = (snapshot: { id: string; data(): unknown }) => ({\n $id: snapshot.id,\n ...(snapshot.data() as object),\n})\n\nexport function newDatasetSharingNote(siteOnly: boolean): string {\n return siteOnly\n ? 'Datasets belong to your organization. Your default sharing starts a ' +\n 'new one on this site only — use Schema to share it with more.'\n : 'Datasets belong to your organization. A new one is shared with ' +\n 'every site — use Schema to narrow that.'\n}\n\n/**\n * Datasets editor (AGL-102): org-shared document collections at\n * `orgs/{orgId}/datasets` (AGL-237/239) with a `records` subcollection,\n * consumed by repeatable components (AGL-103) via `{{item.field}}`.\n * Starter+ (`data-store` flag) with per-plan dataset and record caps —\n * dark-launch rule as everywhere (no plan, no gate). The host path is\n * the pre-migration fallback for hosts not yet org-wired.\n */\nexport function HostDatasetsCard(props: HostDatasetsCardProps) {\n const { hostId, basePath, segments } = props\n const router = useRouter()\n // `dataScope` is null until the async org lookup settles (AGL-1061), and\n // for a host with no owning org — there is no host fallback to act on\n // any more (AGL-1050), so every path built from it is guarded rather\n // than redirected.\n const { scope: dataScope, orgId } = useOrgDataScope({\n hostId,\n orgId: props.orgId,\n })\n // Scoped sharing (AGL-1044). Required, not cosmetic: under the AGL-1041\n // rules a scoped member's UNFILTERED list is rejected outright —\n // Firestore fails the whole query if any candidate would fail — so\n // without this the Data page errors rather than showing fewer rows.\n const {\n tokens: scopeTokens,\n orgWide: viewerOrgWide,\n loaded: scopeLoaded,\n } = useScopeTokens(orgId)\n /**\n * The site whose Data page this is, or undefined on the organization Data\n * page. The explicit `orgId` is that page's own scope and already wins over\n * `hostId` when the org is resolved, so it wins here too, even if a caller\n * hands the card both.\n */\n const pageHostId = props.orgId ? undefined : hostId || undefined\n // What the VIEWER reaches: their scope tokens, or no filter for an org-wide\n // member, who reads everything. Every dataset here is an org dataset, and\n // org datasets are all scoped (AGL-1041).\n const reachScope = viewerOrgWide ? null : scopeTokens\n /**\n * What this page lists (AGL-4047): a site's Data page shows that site's and\n * the workspace-wide datasets, whoever is looking, as every other site\n * surface does. It used to ask only the viewer's reach, so an owner, who\n * reaches everything, saw every site's datasets on every site. The\n * organization Data page lists the viewer's reach.\n */\n const listScope = useMemo(\n () => datasetListScope({ hostId: pageHostId, memberScope: reachScope }),\n [pageHostId, reachScope],\n )\n // Two answers must be in before listing: the org path (AGL-1061) and the\n // viewer's scope tokens (AGL-1047). `useScopeTokens` reports org-wide\n // while loading, so without `scopeLoaded` a scoped collaborator's first\n // render sends an UNFILTERED list that the AGL-1041 rules deny per\n // document. It recovers on the next render, which is exactly what makes\n // it easy to miss: the page looks right and logs a denial every mount.\n const scopeReady = Boolean(dataScope) && scopeLoaded\n const firestore = useFirestore()\n const { enqueueSnackbar } = useSnackbar()\n const { confirm } = useConfirmationContext()\n const { org } = props\n const logActivity = useHostActivityLogger(hostId)\n const { data: user } = useUser()\n /**\n * The site a dataset created here is created FROM, or undefined on the\n * organization Data page.\n *\n * `/api/orgs/datasets` stamps a new dataset with the org's Default sharing,\n * and that setting can only narrow to a site the request names — so a\n * create that names none lands on All sites whatever the org chose.\n */\n const createdFromHostId = pageHostId\n const createdFrom = useMemo(\n () => (createdFromHostId ? { hostId: createdFromHostId } : {}),\n [createdFromHostId],\n )\n /**\n * The site the record editor's Page field lists pages from (AGL-3763): the\n * site whose Data page this is, and none on the organization Data page,\n * where a dataset is no one site's.\n */\n const recordSite = useMemo(\n () => ({ hostId: createdFromHostId }),\n [createdFromHostId],\n )\n /**\n * Whether a dataset created here starts on this site alone: the org chose\n * \"Only the site they were created in\" and there is a site to limit it to.\n * The caption reads it so it never promises All sites to a create that\n * will not get it.\n */\n const createsSiteOnly =\n Boolean(createdFromHostId) &&\n (org as { defaultResourceScope?: 'org' | 'host' } | undefined)\n ?.defaultResourceScope === 'host'\n\n // Creates go through the console API (AGL-473): rules deny client-side\n // `create` on org datasets/records so quotas are server-enforced.\n // Updates/deletes stay client-direct (they don't consume quota). The\n // legacy host scope (no org resolved) keeps the old client writes.\n const callDatasetApi = useCallback(\n async (payload: Record<string, unknown>) => {\n const response = await authorizedFetch(user, '/api/orgs/datasets', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ orgId, ...payload }),\n })\n const result = await response.json().catch(() => ({}))\n if (!response.ok) {\n throw new Error(result?.error ?? 'Dataset operation failed')\n }\n return result\n },\n [user, orgId],\n )\n\n /**\n * Refresh the live pages showing a dataset after a write the BROWSER made\n * (AGL-3113).\n *\n * Record edits and deletes are client-direct — they consume no quota, so\n * AGL-473 left them out of the server leg — which also left them with\n * nothing to announce from. They make a page listing the rows exactly as\n * stale as a create does, so they take the same trip the create already\n * takes, through the route that already holds the org membership check.\n *\n * BEST EFFORT. The record is stored by the time this runs, and the pages\n * catch up on their own window regardless; a refused cache must never be\n * shown to somebody as a refused save.\n */\n const announceRecords = useCallback(\n async (datasetId: string) => {\n try {\n await callDatasetApi({ action: 'announce-records', datasetId })\n } catch (error) {\n console.error(error)\n }\n },\n [callDatasetApi],\n )\n\n /**\n * The rail's search and its Shared with filter (AGL-4047).\n *\n * The filter is a query clause: one site the reader reaches, asked by that\n * site's scope tokens in place of the page's own, which they sit inside —\n * a site the reader is a member of is one their own tokens already reach,\n * so the narrower query is still one the rules can prove. Offered on the\n * organization Data page only: a site's page already lists that site's.\n */\n const [nameSearch, setNameSearch] = useState('')\n const [sharedWith, setSharedWith] = useState('')\n const [railWindow, setRailWindow] = useState(DATASET_LIST_WINDOW)\n const railScope = useMemo(\n () => (sharedWith && !pageHostId ? scopeTokensForHost(sharedWith) : listScope),\n [sharedWith, pageHostId, listScope],\n )\n /** The search as the stored `nameLower` is normalized, asked of the server as a prefix. */\n const serverNameKey = nameSearchKey(nameSearch)\n const { hostNames, sites: orgSites } = useOrgSites(orgId)\n\n const {\n data: datasetDocs,\n status: datasetsStatus,\n /**\n * The dataset rows are unconfirmed by the server (AGL-1358). The schema\n * dialog is seeded from one of them and writes the whole `model` plus\n * `visibleTo` back, so the freshness verdict belongs to THIS listener —\n * the dialog has none of its own, which is why it is handed down rather\n * than recomputed there.\n */\n fromCache: datasetsFromCache,\n listen: datasetsListen,\n } = useFirestoreCollection<any>(\n () =>\n // `scopeReady` already implies a non-null `dataScope`; testing it\n // directly is what lets the compiler see that too.\n dataScope && scopeReady\n ? query(\n collection(firestore, dataScope[0], dataScope[1], 'datasets'),\n ...(railScope\n ? [where('visibleTo', 'array-contains-any', [...railScope])]\n : []),\n /*\n * The rail in name order, and the search as a `nameLower` prefix\n * asked of the server, so it finds a dataset past the loaded\n * window (AGL-4047). Served by the `datasets (visibleTo CONTAINS,\n * nameLower ASC)` index beside the scope clause. Ordering on a\n * field leaves out a document that lacks it, so every writer\n * stamps `nameLower` through `datasetNameLower`, and\n * `tools/scripts/backfill-dataset-name-lower.mjs` stamped the\n * datasets saved before. One row past the window says whether\n * there are more.\n */\n orderBy('nameLower'),\n ...(serverNameKey ? [startAt(serverNameKey), endAt(`${serverNameKey}\\uf8ff`)] : []),\n limit(railWindow + 1),\n )\n : null,\n [firestore, dataScope, railScope, scopeReady, railWindow, serverNameKey],\n { idField: '$id' },\n )\n /** The loaded window in name order: what the join dialog and the reference checks read. */\n const datasets = useMemo(\n () => sortDatasetsByName<any>([...(datasetDocs ?? [])].slice(0, railWindow)),\n [datasetDocs, railWindow],\n )\n const moreDatasets = (datasetDocs?.length ?? 0) > railWindow\n /**\n * Whether the loaded window is short of everything this page lists: a\n * filter or the name search narrowed it, or there are more. A check that\n * must see every dataset — what references a record about to be deleted —\n * reads for itself then.\n */\n const railNarrowed =\n Boolean(pageHostId) || Boolean(sharedWith) || Boolean(serverNameKey) || moreDatasets\n\n /**\n * The open dataset (AGL-4047): the one the address names, or, on the bare\n * page, none until the page moves to the first. The card is also mounted\n * without an address by callers outside the console's routes, which pick\n * one by state.\n */\n const routeDatasetId = basePath ? segments?.[0] : undefined\n /** The record the address opens on its own page (AGL-4047), beneath its dataset's tab. */\n const routeRecordId = basePath && segments?.[1] === 'records' ? segments?.[2] : undefined\n const [selectedId, setSelectedId] = useState<string | null>(null)\n const wantedId = routeDatasetId ?? selectedId ?? undefined\n const listed = wantedId ? datasets.find((item) => item.$id === wantedId) : undefined\n /**\n * The list has emitted, from the cache or the server: enough to look for\n * the open dataset on its own when the window does not hold it.\n */\n const listAnswered = datasetsStatus !== 'loading'\n /**\n * The SERVER has answered the list (AGL-4047). Only this may say there are\n * no datasets. `useFirestoreCollection` hands back `[]` from its first\n * render, before any snapshot, and a cold cache answers `[]` too, unconfirmed:\n * reading either as \"none\" showed a site with five datasets the \"Create a\n * dataset\" empty state for the 16 s its list took to reach the server.\n */\n const listConfirmed = scopeReady && datasetsStatus === 'success' && !datasetsFromCache\n /** The list failed for good, so neither \"none\" nor \"loading\" is true. */\n const listUnreadable = datasetsStatus === 'error'\n /*\n * A dataset the address names that the loaded window does not hold — past\n * the window, outside the filter, or only just created — is read on its\n * own, live, so its tab still opens and a save still seeds from a listener.\n */\n const linkedRead = useFirestoreDoc<any>(\n () =>\n dataScope && scopeReady && wantedId && listAnswered && !listed\n ? doc(firestore, dataScope[0], dataScope[1], 'datasets', wantedId)\n : null,\n [firestore, dataScope, scopeReady, wantedId, listAnswered, Boolean(listed)],\n )\n // Keyed by the id it was read under, as the list's rows are.\n const linked = useMemo(\n () => (!listed && wantedId && linkedRead.data ? { ...linkedRead.data, $id: wantedId } : undefined),\n [listed, wantedId, linkedRead.data],\n )\n /** A site's page refuses a dataset that is not shared with the site (#2341). */\n const notSharedHere = Boolean(\n pageHostId && linked && !visibleToHost((linked as { visibleTo?: string[] }).visibleTo, pageHostId),\n )\n const notFound = Boolean(\n wantedId &&\n listAnswered &&\n !listed &&\n !linked &&\n (linkedRead.status === 'error' || (linkedRead.status !== 'loading' && !linkedRead.fromCache)),\n )\n const selected =\n listed ??\n (linked && !notSharedHere ? linked : undefined) ??\n (wantedId ? undefined : datasets[0])\n /** Which listener the open dataset came from, for the schema dialog's freshness guard. */\n const seed = listed || !linked\n ? { fromCache: datasetsFromCache, unreadable: datasetsStatus === 'error', listen: datasetsListen }\n : { fromCache: linkedRead.fromCache, unreadable: linkedRead.status === 'error', listen: linkedRead.listen }\n /** Opens a dataset: its own address on a routed page, the card's state elsewhere. */\n const openDataset = useCallback(\n (id: string | null) => {\n if (basePath) router.push(id ? `${basePath}/${id}` : basePath)\n else setSelectedId(id)\n },\n [basePath, router],\n )\n // The bare page opens the first dataset, as a hub opens its first section,\n // so the rail always has a tab lit and the address names what is open.\n const landing = basePath && !routeDatasetId && datasets[0] ? `${basePath}/${datasets[0].$id}` : null\n useEffect(() => {\n if (landing) router.replace(landing)\n }, [landing, router])\n const [schemaOpen, setSchemaOpen] = useState(false)\n // What this member may do with THIS dataset (AGL-4047): one placed on one site\n // answers to that site.\n const blocked = useDatasetWritesBlocked(orgId, selected as ScopePlaced | undefined)\n // Typed model (AGL-179): drives headers, cell rendering, and the\n // document form; v1 datasets get a derived all-text model.\n const model = useMemo(\n () => effectiveDatasetModel(selected ?? {}),\n [selected],\n )\n const fields: string[] = useMemo(() => model.order, [model])\n // The records grid's Filters panel, from the dataset's own schema.\n const recordFilter = useMemo(() => datasetRecordFilter(model), [model])\n\n // Guarded on BOTH the scope and a real selection (AGL-1440): with no\n // datasets, `selected` never resolves, and `datasets/-none-/records` is not\n // an empty read for everyone — the AGL-1044 scoped-sharing rules deny it\n // outright for a scoped collaborator, and a permanently denied listen is\n // reopened forever by the refusal loop.\n /**\n * The records table PAGES (AGL-2501). It used to be `limit(500)` with no\n * `orderBy`, every row rendered at once and no control anywhere.\n *\n * That was wrong twice. Five hundred documents were read and billed on\n * every mount of a card nobody had scrolled — and past five hundred the\n * remaining rows were not merely unrendered, they were UNREACHABLE, because\n * nothing showed them and nothing asked for more. Firestore answers an\n * unordered limit in document-id order over auto-ids, so which five hundred\n * a reader got was arbitrary and could differ between two loads of the same\n * dataset; `sortDatasetRecords` then sorted that sample by `order`, which\n * made the table look ordered while being a sample. The export leg\n * (AGL-2335) fixed exactly this shape for the file and left the table.\n *\n * ## Why the walk orders on the document id, and not on a field\n *\n * The usual fix is `orderBy` on the field the rows are sorted by. It cannot\n * be used here: `orderBy` matches only documents that HAVE the field, so\n * ordering on one that any writer omits does not mis-order the list, it\n * hides rows from it — a worse failure than the one being fixed, and a\n * silent one. Every candidate on this collection is omitted by some writer:\n *\n * * `order` — set by `/api/orgs/datasets` and by `POST /v1/datasets/{id}\n * /records`, and NOT by the tenant form-submit leg or by the workflow\n * `appendDataset`/`updateDataset` actions, which write `values` and\n * `createdAt` only. Ordering on it would drop every row a public form or\n * an automation ever produced — the rows a lead dataset is mostly made\n * of.\n * * `createdAt` — written by all four of those, and NOT by a site import:\n * `IMPORTABLE_FIELDS.records` is `['values', 'order']`, so a restored\n * record carries no `createdAt` at all.\n * * `updatedAt` — the mirror image: the import stamps it, the form and\n * automation legs do not.\n *\n * A document's NAME is not a field and cannot be absent, so ordering on it\n * drops nothing and the walk is total: every record is reachable by paging,\n * which is the property the old query lacked. It is not insertion order —\n * ids are random — so the rows are not claimed to be in one. What they are\n * is stable, complete, and the same on every load.\n *\n * `sortDatasetRecords` is deliberately NOT applied to the page. Re-sorting a\n * window of an id-ordered walk by `order` is the same lie the old code told:\n * rows would run in one order within a page and another across pages.\n * For the same reason a header sorts THIS PAGE only, and says so\n * (AGL-3680, `recordColumnSort` below): no stored field could serve it.\n *\n * ## Filtering: every clause and the search word are on the query\n *\n * The grid's Filters panel and quick search are predicates on this same\n * walk (AGL-3321), planned by `planRecordQuery` (`./dataset-record-filter`,\n * over the shared `planListQuery`): equalities ask the record's\n * `filterValues`, and one word-level clause — a text `contains`, a list\n * member, or the search word — asks its `filterKeys`. Firestore's\n * automatic single-field indexes merge them under the same document-name\n * order, so every filter pages through every matching record exactly as\n * the plain walk pages through all of them, with no composite index and\n * no index deploy.\n *\n * Nothing is matched over the rows already loaded. What one query cannot\n * hold is not offered (ranges, negations, empty checks) or is refused by\n * name above the table (a second `contains`, a `contains` beside the\n * search), and a many-word `contains` or search says it asked the first\n * word.\n */\n const gridFilter = useListGridFilter({ selectFields: recordFilter.selectFields })\n // A clause on a field this dataset does not have (the reader switched\n // datasets) narrows nothing and is not shown.\n const recordClauses = useMemo(\n () =>\n gridFilter.clauses.filter((clause) =>\n recordFilter.fields.some((field) => field.column === clause.field),\n ),\n [gridFilter.clauses, recordFilter.fields],\n )\n const recordPlan = useMemo(\n () => planRecordQuery(model, recordFilter, recordClauses, gridFilter.searchWords),\n [model, recordFilter, recordClauses, gridFilter.searchWords],\n )\n // The query's identity: a new plan is a new walk, from page one.\n const recordPlanKey = JSON.stringify({\n filters: recordPlan.plan.filters,\n orderBy: recordPlan.plan.orderBy,\n })\n const {\n rows: records,\n hasMore: hasMoreRecords,\n page: recordPage,\n setPage: setRecordPage,\n pageSize: recordPageSize,\n setPageSize: setRecordPageSize,\n } = usePagedCollection<any>(\n (pageLimit) =>\n // A record's own page shows no table, so it reads none (AGL-4047).\n dataScope && selected?.$id && !blocked.records && !routeRecordId\n ? query(\n collection(\n firestore,\n dataScope[0],\n dataScope[1],\n 'datasets',\n selected.$id,\n 'records',\n ),\n ...listQueryConstraints(recordPlan.plan),\n limit(pageLimit),\n )\n : null,\n [firestore, dataScope, selected?.$id, recordPlanKey, blocked.records, routeRecordId],\n { idField: '$id' },\n )\n /**\n * The record a record's own page opens (AGL-4047), read on its own and live,\n * so a deep link to a record on no loaded page still opens and an edit shows\n * as soon as it lands. Asked only of a member who may view the records.\n */\n const routeRecordRead = useFirestoreDoc<any>(\n () =>\n dataScope && selected?.$id && routeRecordId && !blocked.records\n ? doc(firestore, dataScope[0], dataScope[1], 'datasets', selected.$id, 'records', routeRecordId)\n : null,\n [firestore, dataScope, selected?.$id, routeRecordId, blocked.records],\n )\n // Keyed by the id it was read under, as the table's rows are.\n const routeRecord = useMemo(\n () => (routeRecordId && routeRecordRead.data ? { ...routeRecordRead.data, $id: routeRecordId } : null),\n [routeRecordId, routeRecordRead.data],\n )\n const routeRecordMissing = Boolean(\n routeRecordId &&\n !routeRecord &&\n (routeRecordRead.status === 'error' || (routeRecordRead.status !== 'loading' && !routeRecordRead.fromCache)),\n )\n const recordRefusals = useMemo(\n () =>\n listQueryRefusals(recordPlan.refused, {\n fields: recordFilter.fields,\n headers: recordFilter.headers,\n options: recordFilter.options,\n }),\n [recordPlan.refused, recordFilter],\n )\n const filteringRecords =\n recordClauses.length > 0 || gridFilter.searchWords.some((word) => word.trim())\n /**\n * The two HEAD-COUNTS on this card are server aggregates, not the lengths\n * of the two capped listeners above (AGL-1716, the AGL-1706 shape).\n *\n * Both listeners are capped correctly — 100 datasets in a picker, 500 rows\n * in a table, nobody needs more streamed in. What neither may do is answer\n * \"how many does this org have\", and both did:\n *\n * * `records.length` saturated at 500 and was handed to\n * `checkQuota(org, 'recordsPerDataset', …)`. The bands are 1,000 /\n * 10,000 / 100,000 / 500,000 / 1,000,000, so on EVERY paid plan the\n * check read 500-against-thousands and could never refuse. Worse, the\n * importer computed its room as `limit − records.length`, so an\n * understated count *inflated* the slots it offered.\n * * `datasets.length` saturated at 100 and fed `checkDatasetQuota`, whose\n * bands run to 250 / 500 / 2,000 above that window.\n *\n * `api/orgs/datasets` — the route that actually enforces both — counts with\n * `collection('datasets').count()` and `collection('records').count()` on\n * these exact paths, so this card was offering headroom the API would then\n * refuse. It now asks the same question the same way, and the console\n * billing page and the staff org page already read the dataset count with\n * this identical unscoped aggregate.\n *\n * THE LISTS KEEP THEIR CAPS. The list and the count are different\n * questions; only the count moved. A one-shot goes stale where a listener\n * refreshed for free, so both are re-read after any mutation that can move\n * them — the epochs below.\n *\n * No counting RULE moves: `checkQuota` and `checkDatasetQuota` are\n * untouched entitlement inputs, and nothing here is metered by\n * `report-usage` (it samples record counts server-side for storage, on its\n * own read). Only this card's inputs stopped being saturated.\n */\n const [datasetCountEpoch, setDatasetCountEpoch] = useState(0)\n const [recordCountEpoch, setRecordCountEpoch] = useState(0)\n const [serverDatasetCount, setServerDatasetCount] = useState<number | null>(\n null,\n )\n // TAGGED with the dataset it describes. A bare number would have to be\n // cleared when the selection changes, and clearing state from inside the\n // effect that fills it is a render loop waiting for one unstable dep;\n // tagging answers \"whose count is this?\" without writing state on render.\n const [serverRecordCount, setServerRecordCount] = useState<{\n datasetId: string\n count: number\n } | null>(null)\n useEffect(() => {\n if (!dataScope) return\n let active = true\n // Unscoped, exactly like `api/orgs/datasets` and the billing page: the\n // quota is about the ORG's datasets, not the subset this collaborator\n // can see. A scoped collaborator whom AGL-1044 denies the read falls\n // through to the catch and keeps the visible-rows lower bound.\n void getCountFromServer(\n collection(firestore, dataScope[0], dataScope[1], 'datasets'),\n )\n .then((snapshot) => {\n if (active) setServerDatasetCount(snapshot.data().count)\n })\n .catch(() => {\n // Falls back to the listener length below — a LOWER bound, and this\n // card's prior behaviour. Deliberately not 0: `checkDatasetQuota`\n // answers from whatever it is handed, and 0 used is a confident\n // wrong number in the flattering direction.\n })\n return () => {\n active = false\n }\n }, [firestore, dataScope, datasetCountEpoch])\n // The dataset the counts below belong to. Distinct from `selectedId`\n // above, which is the PICKER value and is null until the user chooses.\n const countedDatasetId: string | undefined = selected?.$id\n useEffect(() => {\n if (!dataScope || !countedDatasetId || blocked.records) return\n let active = true\n void getCountFromServer(\n collection(\n firestore,\n dataScope[0],\n dataScope[1],\n 'datasets',\n countedDatasetId,\n 'records',\n ),\n )\n .then((snapshot) => {\n if (active) {\n setServerRecordCount({\n datasetId: countedDatasetId,\n count: snapshot.data().count,\n })\n }\n })\n .catch(() => {\n // Same fallback, same reason as above.\n })\n return () => {\n active = false\n }\n }, [firestore, dataScope, countedDatasetId, recordCountEpoch, blocked.records])\n // Pending, denied, or answered about the PREVIOUS selection, the loaded\n // rows stand in. They can only UNDERSTATE (same collections, capped),\n // never overstate, so nothing these figures gate fires on a count larger\n // than the truth. Since AGL-2501 the record fallback is one PAGE, so it\n // understates by more — which moves it further in the safe direction and\n // changes nothing about which way it can be wrong.\n const datasetCount = serverDatasetCount ?? datasets.length\n const recordCount =\n serverRecordCount && serverRecordCount.datasetId === countedDatasetId\n ? serverRecordCount.count\n : records.length\n\n // --- Create dataset -----------------------------------------------------\n const [creator, setCreator] = useState<{\n name: string\n fields: string\n } | null>(null)\n const handleOpenCreator = useCallback(() => {\n if (!checkEntitlement(org, 'dataStore')) {\n return enqueueSnackbar(\n 'Datasets require a Starter plan or higher — see Billing',\n { variant: 'warning', persist: false },\n )\n }\n // Addon-aware quota (AGL-132): purchased extra datasets raise the\n // limit up to the plan's hard max; beyond that only an upgrade helps.\n // The ORG's datasets, not the picker's window (AGL-1716).\n const quota = checkDatasetQuota(org as any, datasetCount)\n if (!quota.allowed) {\n return enqueueSnackbar(\n quota.upgradeRequired\n ? `Dataset limit reached (${quota.limit}) — upgrade in Billing`\n : `Dataset limit reached (${quota.limit}) — add extra datasets ` +\n `for $${quota.addonPriceUsd}/mo each or upgrade in Billing`,\n { variant: 'warning', persist: false },\n )\n }\n setCreator({ name: '', fields: '' })\n }, [org, datasetCount, enqueueSnackbar])\n // Entries are human names — \"Roast preference\" → stable id\n // `roast_preference` with the pretty name kept for headers (AGL-558).\n const creatorEntries = parseDatasetFieldEntries(creator?.fields ?? '')\n const creatorFields = creatorEntries.map((entry) => entry.id)\n const handleCreate = useCallback(async () => {\n // No org, no create. The `else` that used to sit below this was the\n // legacy host-scope client write (AGL-1050) — the one path by which a\n // dataset could be created with NO quota check, since /api/orgs/datasets\n // is where AGL-473 enforces it. The rules now deny that path outright;\n // this is the client side of the same closure. The Add button is\n // disabled without a scope, so reaching the guard means a stale closure.\n if (!creator?.name.trim() || creatorFields.length === 0 || !orgId) return\n let id: string\n try {\n const result = await callDatasetApi({\n action: 'create-dataset',\n displayName: creator.name.trim(),\n fields: creatorFields,\n // Typed model from day one (AGL-178); refine in the Schema dialog.\n model: modelFromFieldEntries(creatorEntries),\n ...createdFrom,\n })\n id = String(result.id)\n } catch (error: any) {\n return void enqueueSnackbar(error?.message ?? 'Dataset create failed', {\n variant: 'warning',\n persist: false,\n })\n }\n setCreator(null)\n openDataset(id)\n setDatasetCountEpoch((epoch) => epoch + 1)\n enqueueSnackbar(`Dataset \"${creator.name.trim()}\" created`, {\n variant: 'success',\n persist: false,\n })\n logActivity('Created dataset', {\n type: 'content',\n id,\n name: creator.name.trim(),\n })\n }, [creator, creatorEntries, creatorFields, orgId, createdFrom, callDatasetApi, enqueueSnackbar, logActivity, openDataset])\n\n // Join collection template (AGL-180): extrinsic many-to-many as a\n // visible, editable collection of FKey pairs — no magic.\n const [joiner, setJoiner] = useState<{ a: string; b: string } | null>(null)\n const handleCreateJoin = useCallback(async () => {\n if (!joiner?.a || !joiner?.b || joiner.a === joiner.b) return\n const a = datasets.find((item) => item.$id === joiner.a)\n const b = datasets.find((item) => item.$id === joiner.b)\n // A join collection is a dataset and consumes the same quota, so it\n // takes the same API-only route (AGL-1050) — the host-scope client\n // write that used to stand in for it is gone.\n if (!a || !b || !orgId) return\n const fieldFor = (target: any, fieldId: string) => ({\n name: datasetDisplayName(target) || fieldId,\n type: 'reference' as const,\n required: true,\n reference: {\n datasetId: target.$id as string,\n displayFieldId: effectiveDatasetModel(target).order[0],\n onDelete: 'setNull' as const,\n },\n })\n const payload = {\n displayName: `${datasetDisplayName(a)} ↔ ${datasetDisplayName(b)}`,\n fields: ['aRef', 'bRef'],\n model: {\n order: ['aRef', 'bRef'],\n fields: { aRef: fieldFor(a, 'aRef'), bRef: fieldFor(b, 'bRef') },\n },\n }\n let id: string\n try {\n const result = await callDatasetApi({\n action: 'create-dataset',\n ...payload,\n // A join collection is a dataset, so the same Default sharing applies.\n ...createdFrom,\n })\n id = String(result.id)\n } catch (error: any) {\n return void enqueueSnackbar(error?.message ?? 'Join create failed', {\n variant: 'warning',\n persist: false,\n })\n }\n setJoiner(null)\n openDataset(id)\n // A join collection IS a dataset and consumes the same quota.\n setDatasetCountEpoch((epoch) => epoch + 1)\n enqueueSnackbar('Join collection created', {\n variant: 'success',\n persist: false,\n })\n }, [joiner, datasets, orgId, createdFrom, callDatasetApi, enqueueSnackbar, openDataset])\n\n const handleDeleteDataset = useCallback(async () => {\n if (!selected) return\n const confirmed = await confirm({\n title: 'Delete this dataset?',\n description:\n `\"${datasetDisplayName(selected)}\"` +\n // What is actually being destroyed, not what is loaded (AGL-1716):\n // a 40,000-row dataset used to warn about \"its 500 documents\".\n (recordCount\n ? ` and its ${recordCount.toLocaleString()} record${recordCount === 1 ? '' : 's'}`\n : '') +\n ' will be deleted. Repeatable components and bindings that use it ' +\n 'stop showing its data.',\n confirmationText: 'Delete',\n confirmationButtonProps: { color: 'error' },\n })\n .then(() => true)\n .catch(() => false)\n if (!confirmed || !dataScope) return\n // Deleting the dataset doc client-side would strand its `records`\n // subcollection — Firestore doesn't cascade and only the Admin SDK has\n // `recursiveDelete`, so the delete goes through the erase route\n // (AGL-945). Single-record deletes below stay client-direct.\n try {\n const response = await authorizedFetch(user, '/api/resources/erase', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n scope: dataScope[0],\n scopeId: dataScope[1],\n kind: 'datasets',\n id: selected.$id,\n // Names the site this delete was issued from, so the route can\n // refuse to destroy a dataset shared beyond it (AGL-1046). The\n // org Data page passes no host and keeps the org-wide delete.\n hostId,\n }),\n })\n const result = await response.json().catch(() => ({}))\n if (!response.ok) throw new Error(result?.error ?? 'Dataset delete failed')\n } catch (error: any) {\n return void enqueueSnackbar(error?.message ?? 'Dataset delete failed', {\n variant: 'warning',\n persist: false,\n })\n }\n openDataset(null)\n setDatasetCountEpoch((epoch) => epoch + 1)\n enqueueSnackbar('Dataset deleted', { variant: 'success', persist: false })\n logActivity('Deleted dataset', {\n type: 'content',\n id: selected.$id,\n name: datasetDisplayName(selected),\n })\n }, [\n selected,\n recordCount,\n confirm,\n dataScope,\n hostId,\n user,\n enqueueSnackbar,\n logActivity,\n openDataset,\n ])\n\n /**\n * What the selected dataset's references point at beyond this site's list\n * (AGL-4047). A dataset this site sees can name a target another site holds;\n * the schema dialog warns about exactly that, and a cell still labels the\n * row it points at, so the target has to be known even though the site's\n * list does not show it. Read one by one, and only when there is one; a\n * target the viewer may not read stays unknown.\n */\n const [outsideTargets, setOutsideTargets] = useState<any[]>(NO_DATASETS)\n useEffect(() => {\n let active = true\n const missing = railNarrowed\n ? [\n ...new Set(\n model.order\n .map((fieldId) => model.fields[fieldId]?.reference?.datasetId)\n .filter((id): id is string => Boolean(id)),\n ),\n ].filter((id) => !datasets.some((item) => item.$id === id))\n : []\n if (!missing.length || !dataScope) {\n setOutsideTargets(NO_DATASETS)\n return\n }\n void Promise.all(\n missing.map((id) =>\n getDoc(doc(firestore, dataScope[0], dataScope[1], 'datasets', id)).then(\n (snapshot) => (snapshot.exists() ? datasetRow(snapshot) : null),\n () => null,\n ),\n ),\n ).then((rows) => {\n if (active) setOutsideTargets(rows.filter(Boolean))\n })\n return () => {\n active = false\n }\n }, [railNarrowed, model, datasets, firestore, dataScope])\n const knownDatasets = useMemo(\n () => (outsideTargets.length ? [...datasets, ...outsideTargets] : datasets),\n [datasets, outsideTargets],\n )\n\n // Reference pickers (AGL-180): load target-collection rows for every\n // reference field in the model (id -> display label).\n const [refOptions, setRefOptions] = useState<\n Record<string, Array<{ id: string; label: string }>>\n >({})\n useEffect(() => {\n let active = true\n const referenceFields = model.order.filter(\n (fieldId) =>\n model.fields[fieldId]?.type === 'reference' &&\n model.fields[fieldId]?.reference?.datasetId,\n )\n if (!referenceFields.length || !dataScope) {\n setRefOptions({})\n return\n }\n void Promise.all(\n referenceFields.map(async (fieldId) => {\n const reference = model.fields[fieldId].reference as {\n datasetId: string\n displayFieldId?: string\n }\n const target = knownDatasets.find(\n (item) => item.$id === reference.datasetId,\n )\n const displayFieldId =\n reference.displayFieldId ??\n effectiveDatasetModel(target ?? {}).order[0]\n const snapshot = await getDocs(\n query(\n collection(\n firestore,\n dataScope[0],\n dataScope[1],\n 'datasets',\n reference.datasetId,\n 'records',\n ),\n limit(200),\n ),\n ).catch(() => null)\n const options = (snapshot?.docs ?? []).map((docSnapshot) => ({\n id: docSnapshot.id,\n label: String(\n docSnapshot.get('values')?.[displayFieldId ?? ''] ??\n docSnapshot.id,\n ),\n }))\n return [fieldId, options] as const\n }),\n ).then((entries) => {\n if (active) setRefOptions(Object.fromEntries(entries))\n })\n return () => {\n active = false\n }\n }, [model, knownDatasets, firestore, dataScope])\n /**\n * One reference target's label, or `null` when this ID resolves to nothing.\n *\n * The distinction the grid cannot draw. `referenceLabel` below falls back to\n * the raw ID, which is the only thing a cell has room for and is\n * indistinguishable from a resolved label that happens to look like an ID.\n * The record view has room to say which, so it asks the question that has a\n * `null` answer.\n *\n * Unresolvable covers more than a deleted target: `refOptions` loads at most\n * 200 rows per referenced collection, so a live target outside that window\n * reports the same way. Either way the ID is shown and neither is claimed to\n * be a working link.\n */\n const resolveReferenceLabel = useCallback(\n (fieldId: string, id: string): string | null =>\n refOptions[fieldId]?.find((option) => option.id === id)?.label ?? null,\n [refOptions],\n )\n const referenceLabel = useCallback(\n (fieldId: string, value: unknown): string => {\n const ids = Array.isArray(value) ? value : value != null ? [value] : []\n return ids\n .map((id) => resolveReferenceLabel(fieldId, String(id)) ?? String(id))\n .join(', ')\n },\n [resolveReferenceLabel],\n )\n /**\n * The record the viewer is showing, held as an ID and resolved against the\n * page the table already has.\n *\n * Holding the ID rather than the row is what keeps the view live without\n * costing a read: the same listener that draws the table re-resolves it, so\n * an edit landing underneath updates the open dialog. When the row leaves\n * the page — deleted, or paged past — this answers `null` and the dialog\n * closes, which is the honest response to a record no longer in front of\n * this reader. Nothing here queries: `records` is the page (or filter window)\n * query's answer.\n */\n const [viewerId, setViewerId] = useState<string | null>(null)\n /**\n * Opens a record (AGL-4047): on its own page beneath the dataset's tab\n * where the Data page is routed, in the View record dialog elsewhere.\n */\n const datasetHref = basePath && selected?.$id ? `${basePath}/${selected.$id}` : null\n const openRecord = useCallback(\n (id: string) => {\n if (datasetHref) router.push(`${datasetHref}/records/${encodeURIComponent(id)}`)\n else setViewerId(id)\n },\n [datasetHref, router],\n )\n const viewerRecord = useMemo(\n () =>\n viewerId\n ? (records.find((record: any) => record.$id === viewerId) ?? null)\n : null,\n [viewerId, records],\n )\n\n // --- Document editor (null id = new; AGL-179 typed inputs) --------------\n const [editor, setEditor] = useState<{\n id: string | null\n values: Record<string, string>\n errors: Record<string, string>\n /** A sample a site start seeded (AGL-4065): saving it makes it the owner's. */\n sample?: boolean\n } | null>(null)\n const handleOpenRecord = useCallback(\n (record?: any) => () => {\n if (!record) {\n // The dataset's documents, not the loaded window (AGL-1716).\n const quota = checkQuota(org, 'recordsPerDataset', recordCount)\n if (!quota.allowed) {\n return enqueueSnackbar(\n `Record limit reached (${quota.limit}) — see Billing to upgrade`,\n { variant: 'warning', persist: false },\n )\n }\n }\n const values: Record<string, string> = {}\n for (const fieldId of model.order) {\n const field = model.fields[fieldId]\n if (!field) continue\n if (record) {\n values[fieldId] = datasetValueToInput(\n field,\n record.values?.[fieldId],\n )\n } else if (field.default != null) {\n values[fieldId] = String(field.default)\n }\n }\n // Flag non-conforming stored values (AGL-178 policy: type changes\n // never rewrite documents; the editor surfaces the mismatch).\n const errors = record\n ? validateDocument(model, record.values ?? {})\n : {}\n setEditor({ id: record?.$id ?? null, values, errors, ...(isSampleDatasetRecord(record) ? { sample: true } : {}) })\n },\n [org, recordCount, model, enqueueSnackbar],\n )\n const handleSaveRecord = useCallback(async () => {\n if (!editor || !selected || !dataScope) return\n // The editor holds the record's WHOLE values, so an address it already\n // has stays and an empty one fills in from its source (AGL-3475).\n const coerced = fillRecordAddresses(\n model,\n coerceDocumentValues(model, editor.values),\n )\n const errors = validateDocument(model, coerced)\n if (Object.keys(errors).length) {\n return void setEditor((prev) => (prev ? { ...prev, errors } : prev))\n }\n // `values` is replaced wholesale (not merged) so orphaned values from\n // removed fields strip here, lazily, per the documented AGL-178 policy.\n try {\n if (editor.id) {\n // Updates stay client-direct (no quota consumed).\n const recordRef = doc(\n firestore,\n dataScope[0],\n dataScope[1],\n 'datasets',\n selected.$id,\n 'records',\n editor.id,\n )\n await setDoc(\n recordRef,\n {\n values: coerced,\n // The integrity index moves with the values it describes\n // (`datasetIntegrityUpdate`); the merging form, because clearing\n // the last reference has to REMOVE the field rather than omit it.\n ...datasetIntegrityUpdate(model, coerced, deleteField()),\n // A sample saved is the owner's row now (AGL-4065).\n ...(editor.sample ? { sample: deleteField() } : {}),\n updatedAt: Timestamp.now(),\n },\n {\n mergeFields: [\n 'values',\n 'referencedIds',\n 'filterKeys',\n 'filterValues',\n 'updatedAt',\n ...(editor.sample ? ['sample'] : []),\n ],\n },\n )\n await announceRecords(selected.$id)\n } else {\n // Creates go through the quota-enforcing API (AGL-473). The legacy\n // host-scope client write that used to follow this branch is gone\n // (AGL-1050): a non-null `dataScope` is an org scope, so `orgId` is\n // set and there is no third case to fall into.\n await callDatasetApi({\n action: 'create-record',\n datasetId: selected.$id,\n values: coerced,\n })\n }\n } catch (error: any) {\n return void enqueueSnackbar(error?.message ?? 'Record save failed', {\n variant: 'warning',\n persist: false,\n })\n }\n setEditor(null)\n // A create moves the count; an update cannot. Same reason as the\n // importer: the one-shot aggregate does not refresh itself.\n if (!editor.id) setRecordCountEpoch((epoch) => epoch + 1)\n enqueueSnackbar(editor.id ? 'Record saved' : 'Record added', {\n variant: 'success',\n persist: false,\n })\n logActivity(editor.id ? 'Updated record' : 'Added record', {\n type: 'content',\n id: selected.$id,\n name: datasetDisplayName(selected),\n })\n }, [\n editor,\n selected,\n firestore,\n dataScope,\n model,\n callDatasetApi,\n announceRecords,\n enqueueSnackbar,\n logActivity,\n ])\n const handleDeleteRecord = useCallback(\n (record: any, afterDelete?: () => void) => async () => {\n // Datasets whose records this delete rewrites through a reference\n // fixup, beside the one the record belongs to. Each has pages of its\n // own to refresh (AGL-3113).\n const alsoChanged = new Set<string>()\n if (!selected || !dataScope) return\n /**\n * Delete integrity (AGL-180): every collection whose model references\n * this one is asked whether it still points at this record. `restrict`\n * blocks the delete; `setNull` strips the FKey from the holders.\n *\n * The question is a QUERY over the denormalized `referencedIds` index,\n * not a page of records filtered in the browser. A page answers for the\n * rows it happened to fetch — an unordered `limit` is answered in\n * document-id order over auto-ids, so it is an arbitrary sample — and a\n * reference held by a row outside it reads as no reference at all: the\n * delete goes through and `restrict` silently fails to restrict, leaving\n * a document pointing at something that no longer exists. `values`\n * itself cannot be queried (it carries a deliberate index exemption —\n * see `datasetIntegrityFields`), which is why the index exists.\n *\n * The query narrows to the candidates; the per-field test below keeps it\n * EXACT, since `referencedIds` is the union across every reference field\n * and one of them may point at a different collection entirely.\n *\n * ⚠️ FAILS CLOSED. A query that rejects — a missing index, a rules\n * refusal on a collection this member cannot read — refuses the delete\n * rather than treating silence as \"nothing references it\". A check that\n * fails open is worse than no check, because the UI then tells the user\n * the record is safe to remove.\n *\n * ⚠️ Reaches the collections in this viewer's scoped, capped window. A\n * referencing collection shared with no site this member can see is one\n * the client may not read at all, so it is not consulted; only a server\n * route could close that.\n *\n * On a site's Data page that window is NOT the list (AGL-4047). The list\n * is the site's, and a dataset another site holds can reference a row of\n * one shared with both: narrowing what the page shows must not narrow\n * what a delete protects. So the page reads the viewer's reach here, once,\n * at the moment of the delete, and refuses if it cannot.\n */\n let referencing: any[] = datasets\n if (railNarrowed) {\n try {\n const reach = await getDocs(\n query(\n collection(firestore, dataScope[0], dataScope[1], 'datasets'),\n ...(reachScope\n ? [where('visibleTo', 'array-contains-any', [...reachScope])]\n : []),\n limit(DATASET_LIST_WINDOW),\n ),\n )\n referencing = reach.docs.map(datasetRow)\n } catch {\n return void enqueueSnackbar(\n 'Cannot delete: the datasets that may reference this record could ' +\n 'not be checked, so removing it could break them. Nothing was ' +\n 'deleted.',\n { variant: 'error' },\n )\n }\n }\n for (const other of referencing) {\n const otherModel = effectiveDatasetModel(other)\n if (!referencingFieldIds(otherModel, selected.$id).length) continue\n let snapshot\n try {\n snapshot = await getDocs(\n query(\n collection(\n firestore,\n dataScope[0],\n dataScope[1],\n 'datasets',\n other.$id,\n 'records',\n ),\n where('referencedIds', 'array-contains', record.$id),\n ),\n )\n } catch {\n return void enqueueSnackbar(\n `Cannot delete: \"${datasetDisplayName(other)}\" could not be checked for ` +\n 'references, so removing this record could break it. Nothing ' +\n 'was deleted.',\n { variant: 'error' },\n )\n }\n // The verdict is shared with `/api/orgs/datasets` `delete-record`\n // (`planReferenceFixups`): the per-field test keeps the query EXACT,\n // since `referencedIds` is the union across every reference field.\n const plan = planReferenceFixups(\n otherModel,\n selected.$id,\n record.$id,\n snapshot.docs.map((docSnapshot) => ({ id: docSnapshot.id, values: docSnapshot.get('values') })),\n )\n if (plan.kind === 'none') continue\n if (plan.kind === 'restricted') {\n return void enqueueSnackbar(\n restrictedDeleteMessage(plan.holders, datasetDisplayName(other)),\n { variant: 'warning', persist: false },\n )\n }\n // Chunked under Firestore's 500-writes-per-batch cap. The query is no\n // longer bounded by a page size, so the number of holders is whatever\n // the collection really holds.\n for (let start = 0; start < plan.updates.length; start += 400) {\n const batch = writeBatch(firestore)\n for (const update of plan.updates.slice(start, start + 400)) {\n const holder = snapshot.docs.find((docSnapshot) => docSnapshot.id === update.id)\n if (!holder) continue\n batch.update(holder.ref, {\n values: update.values,\n ...datasetIntegrityUpdate(otherModel, update.values, deleteField()),\n })\n }\n await batch.commit()\n }\n // The fixups rewrote rows in ANOTHER dataset, whose own pages are now\n // showing a reference that no longer resolves.\n alsoChanged.add(other.$id)\n }\n await deleteDoc(\n doc(\n firestore,\n dataScope[0],\n dataScope[1],\n 'datasets',\n selected.$id,\n 'records',\n record.$id,\n ),\n )\n setRecordCountEpoch((epoch) => epoch + 1)\n for (const datasetId of [selected.$id, ...alsoChanged]) {\n await announceRecords(datasetId)\n }\n enqueueSnackbar('Record deleted', { variant: 'success', persist: false })\n afterDelete?.()\n },\n [\n selected,\n datasets,\n railNarrowed,\n reachScope,\n firestore,\n dataScope,\n announceRecords,\n enqueueSnackbar,\n ],\n )\n\n /**\n * Import and export (AGL-3530) open the console's import wizard and export\n * dialog on this dataset (`data.dataset:<datasetId>`): the file is read,\n * matched and written on the server, through the same record writes as\n * every other create and update, and the export streams the fields the\n * person picks. Outside the console shell there is no launcher, and no\n * Import or Export to offer. Inside it, Import is on for a member who may\n * write this dataset and switched off with the permission named for one who\n * may not, and Export likewise for \"Export data\", for a member who can see it\n * (AGL-3546, AGL-4047) — the transfer routes' own rule.\n */\n const transfer = useTransferLauncher()\n const transferTarget = selected?.$id\n ? {\n resource: datasetTransferResourceKey(selected.$id),\n scope: 'org' as const,\n // This dataset's own answer once it is known; the workspace's until then.\n ...(blocked.known ? { importAllowed: !blocked.writes } : {}),\n }\n : null\n const canImport = Boolean(transfer && transferTarget && transfer.can('import', transferTarget))\n const canExport = Boolean(transfer && transferTarget && transfer.can('export', transferTarget))\n const handleImport = useCallback(() => {\n if (!transfer || !selected?.$id) return\n const dataset = { id: selected.$id, name: datasetDisplayName(selected) }\n transfer.openImport({\n resource: datasetTransferResourceKey(dataset.id),\n scope: 'org',\n title: dataset.name ? `Import into ${dataset.name}` : 'Import records',\n onFinished: () => {\n // An import moves the record count, and the aggregate is a one-shot.\n setRecordCountEpoch((epoch) => epoch + 1)\n logActivity('Imported records', { type: 'content', id: dataset.id, name: dataset.name })\n },\n })\n }, [transfer, selected, logActivity])\n const handleExport = useCallback(() => {\n if (!transfer || !selected?.$id) return\n const name = datasetDisplayName(selected)\n transfer.openExport({\n resource: datasetTransferResourceKey(selected.$id),\n scope: 'org',\n title: name ? `Export ${name}` : 'Export records',\n // The table's own query, re-planned on the server the way the table\n // plans it, so \"the current filter\" exports what the table shows.\n ...(filteringRecords\n ? {\n filter: {\n label: 'The records the table’s filters and search show',\n value: { clauses: recordClauses, search: gridFilter.searchWords },\n },\n }\n : {}),\n })\n }, [transfer, selected, filteringRecords, recordClauses, gridFilter.searchWords])\n\n /*\n * One column per schema field, filterable as far as `datasetRecordFilter`\n * declares it. The row OPENS the record, read-only (`onOpen`); the actions\n * column holds the keyboard's way in (`View`, a real button) beside Edit\n * and Delete, and a press anywhere in it never opens the row.\n */\n const recordGridColumns = useMemo(\n () =>\n listFilterGridColumns(\n [\n ...fields.map((fieldId, column) => {\n const field = model.fields[fieldId]\n const shown = (row: any) =>\n field?.type === 'reference'\n ? referenceLabel(fieldId, row.values?.[fieldId]) || '--'\n : field\n ? formatDatasetValue(field, row.values?.[fieldId]) || '--'\n : '--'\n return {\n field: recordColumn(fieldId),\n headerName: field?.name ?? fieldId,\n // Field descriptions (AGL-560) surface as header hints.\n description: field?.description,\n flex: 1,\n minWidth: 140,\n renderCell: ({ row }: { row: any }) =>\n // A sample a site start seeded says so beside its first value (AGL-4065).\n column === 0 && isSampleDatasetRecord(row) ? (\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center', height: '100%', minWidth: 0 }}>\n <Typography variant=\"body2\" noWrap>\n {shown(row)}\n </Typography>\n <Tooltip title={DATASET_SAMPLE_RECORD_NOTE}>\n <Chip label=\"Sample\" size=\"small\" variant=\"outlined\" color=\"info\" />\n </Tooltip>\n </Stack>\n ) : (\n shown(row)\n ),\n }\n }),\n listActionsColumn(\n (record: any) => (\n <Stack\n direction=\"row\"\n sx={{ height: '100%', alignItems: 'center', justifyContent: 'flex-end' }}\n >\n <Button size=\"small\" onClick={() => openRecord(record.$id)}>\n {'View'}\n </Button>\n <BlockedControl blocked={blocked.writes} reason={blocked.writesReason}>\n <Button size=\"small\" onClick={handleOpenRecord(record)}>\n {'Edit'}\n </Button>\n </BlockedControl>\n <BlockedControl blocked={blocked.writes} reason={blocked.writesReason}>\n <Button\n size=\"small\"\n color=\"error\"\n onClick={handleDeleteRecord(record)}\n >\n {'Delete'}\n </Button>\n </BlockedControl>\n </Stack>\n ),\n { width: 220 },\n ),\n ] as Parameters<typeof listFilterGridColumns>[0],\n recordFilter.fields,\n recordFilter.options,\n recordFilter.headers,\n ),\n [\n fields,\n model,\n referenceLabel,\n handleOpenRecord,\n handleDeleteRecord,\n openRecord,\n recordFilter,\n blocked.writes,\n blocked.writesReason,\n ],\n )\n\n /*\n * EVERY HEADER SORTS — THE PAGE ON SCREEN (AGL-3680). A record's values are\n * per-schema and no field is on every record (see the walk above), so no\n * query can order by one; each value column sorts the loaded page by what\n * it shows (a reference by its label, a number or switch by its value) and\n * the notice says it is this page only.\n */\n const recordPageSorts = useMemo(\n () =>\n Object.fromEntries(\n fields.map((fieldId) => {\n const field = model.fields[fieldId]\n return [\n recordColumn(fieldId),\n (row: any) => {\n const value = row.values?.[fieldId]\n if (field?.type === 'reference') return referenceLabel(fieldId, value) || null\n if (typeof value === 'number' || typeof value === 'boolean') return value\n return field ? formatDatasetValue(field, value) || null : null\n },\n ]\n }),\n ),\n [fields, model, referenceLabel],\n )\n const recordSortHeaders = useMemo(\n () =>\n Object.fromEntries(\n fields.map((fieldId) => [recordColumn(fieldId), model.fields[fieldId]?.name ?? fieldId]),\n ),\n [fields, model],\n )\n const recordColumnSort = useListColumnSort<any>({\n sorts: NO_QUERY_SORTS,\n rows: records,\n pageSorts: recordPageSorts,\n headers: recordSortHeaders,\n })\n\n /**\n * The rail (AGL-4047): one tab per dataset, at the dataset's own address,\n * with a second line that tells two of one name apart. Past\n * {@link DATASET_RAIL_GROUP_AT} the tabs are grouped by who they are shared\n * with, and the organization page offers the Shared with filter.\n */\n const grouped = datasets.length > DATASET_RAIL_GROUP_AT\n const railSections = useMemo<HubSection[]>(() => {\n if (!basePath) return []\n const tab = (item: DatasetRailEntry, group?: string): HubSection => ({\n href: `${basePath}/${item.$id}`,\n label: datasetRailName(item),\n secondary: datasetRailSecondary(item, { hostNames, grouped }),\n ...(group ? { group } : {}),\n })\n if (!grouped) return datasets.map((item: DatasetRailEntry) => tab(item))\n return groupDatasetsBySharing(datasets, hostNames).flatMap((group) =>\n group.datasets.map((item) => tab(item, group.label)),\n )\n }, [basePath, datasets, hostNames, grouped])\n /** The join dialog's names, told apart where two match (AGL-4047). */\n const joinLabels = useMemo(() => datasetPickerLabelsOf(datasets, hostNames), [datasets, hostNames])\n const offerSharedWith =\n !pageHostId && orgSites.length > 1 && (datasets.length > DATASET_RAIL_GROUP_AT || Boolean(sharedWith))\n const sitesByName = useMemo(\n () => [...orgSites].sort((a, b) => (hostNames[a.$id] ?? '').localeCompare(hostNames[b.$id] ?? '')),\n [orgSites, hostNames],\n )\n const railHeader =\n datasets.length || nameSearch || sharedWith ? (\n <Stack spacing={1.5} sx={{ mb: 1 }}>\n <TextField\n size=\"small\"\n fullWidth\n placeholder=\"Search datasets by name\"\n value={nameSearch}\n onChange={(event) => setNameSearch(event.target.value)}\n slotProps={{ htmlInput: { 'aria-label': 'Search datasets by name' } }}\n />\n {offerSharedWith ? (\n <TextField\n select\n size=\"small\"\n fullWidth\n label=\"Shared with\"\n value={sharedWith}\n onChange={(event) => {\n setSharedWith(event.target.value)\n setRailWindow(DATASET_LIST_WINDOW)\n }}\n >\n <MenuItem value=\"\">{'Any site'}</MenuItem>\n {sitesByName.map((site) => (\n <MenuItem key={site.$id} value={site.$id}>\n {hostNames[site.$id]}\n </MenuItem>\n ))}\n </TextField>\n ) : null}\n </Stack>\n ) : null\n const railFooter = (\n <>\n {/*\n The Datasets card's own loading state (AGL-4047), the same rule as the\n panel beside it: while the list has nothing to show and the server has\n not answered, the card says it is loading instead of sitting blank.\n Rows the cache already holds show at once, and an answer that is\n empty, or refused, leaves the panel to say so.\n */}\n {!listConfirmed && !listUnreadable && datasets.length === 0 ? (\n <Box sx={{ px: 2, py: 1 }}>\n <CircularProgress size={24} aria-label=\"Loading the dataset list\" />\n </Box>\n ) : null}\n {listConfirmed && serverNameKey && datasets.length === 0 ? (\n <Typography variant=\"body2\" color=\"text.secondary\" sx={{ px: 2, py: 1 }}>\n {'No datasets match.'}\n </Typography>\n ) : null}\n {moreDatasets ? (\n <Button size=\"small\" sx={{ mt: 1 }} onClick={() => setRailWindow((window) => window + DATASET_LIST_WINDOW)}>\n {'Show more datasets'}\n </Button>\n ) : null}\n </>\n )\n\n /** The open dataset's facts, under its name. */\n const facts: Array<[string, string]> = selected\n ? [\n ['Shared with', datasetSharingLabel(selected, hostNames)],\n ['Fields', String(fields.length)],\n ['Records', blocked.records ? '--' : recordCount.toLocaleString()],\n ['Source', datasetSourceLabel(selected)],\n ['Created', datasetCreatedLabel(selected)],\n ]\n : []\n\n /** Label-over-value facts, under a heading. */\n const factsRow = (pairs: Array<[string, string]>) => (\n <Stack direction=\"row\" spacing={3} useFlexGap sx={{ flexWrap: 'wrap', mt: 1 }}>\n {pairs.map(([label, value]) => (\n <Box key={label}>\n <Typography variant=\"caption\" color=\"text.secondary\" component=\"div\">\n {label}\n </Typography>\n <Typography variant=\"body2\" color=\"text.primary\" component=\"div\" sx={{ overflowWrap: 'anywhere' }}>\n {value}\n </Typography>\n </Box>\n ))}\n </Stack>\n )\n\n /**\n * A record's own page (AGL-4047): back to its dataset, its fields, and\n * today's record actions with today's gates. It takes the place of the View\n * record dialog where the Data page is routed.\n */\n const recordTitle = routeRecord ? datasetRecordTitle(model, routeRecord.values) : undefined\n const recordPanel =\n selected && routeRecordId ? (\n <CardDisplay\n help={pluginDocsHelp('datasets', { anchor: '#organization-data-page' })}\n header={\n <Stack spacing={1} sx={{ alignItems: 'flex-start' }}>\n {datasetHref ? (\n <Button\n size=\"small\"\n component={AppLink}\n href={datasetHref}\n startIcon={<MdiIcon path={mdiArrowLeft.path} size={0.8} />}\n >\n {datasetRailName(selected)}\n </Button>\n ) : null}\n {recordTitle ? <span>{recordTitle}</span> : null}\n </Stack>\n }\n contentGutterX\n contentGutterY\n contentBordered=\"top\"\n HeaderProps={{\n action: routeRecord ? (\n <Stack direction=\"row\" spacing={1} useFlexGap sx={{ alignItems: 'center', flexWrap: 'wrap', justifyContent: 'flex-end' }}>\n <BlockedControl blocked={blocked.writes} reason={blocked.writesReason}>\n <Button size=\"small\" onClick={handleOpenRecord(routeRecord)}>\n {'Edit record'}\n </Button>\n </BlockedControl>\n <BlockedControl blocked={blocked.writes} reason={blocked.writesReason}>\n <Button\n size=\"small\"\n color=\"error\"\n onClick={handleDeleteRecord(routeRecord, () => {\n if (datasetHref) router.push(datasetHref)\n })}\n >\n {'Delete'}\n </Button>\n </BlockedControl>\n </Stack>\n ) : undefined,\n subheader: factsRow([\n ['Record ID', routeRecordId],\n ['Dataset', `${datasetRailName(selected)} · ${datasetSharingLabel(selected, hostNames)}`],\n ]),\n }}\n >\n <Stack spacing={1.5}>\n {blocked.records ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {DATASETS_VIEW_RECORDS_REFUSAL}\n </Typography>\n ) : routeRecordMissing ? (\n <Alert severity=\"info\">{'This record doesn’t exist, or you can’t open it.'}</Alert>\n ) : routeRecord ? (\n <DatasetRecordFieldList\n record={routeRecord}\n model={model}\n resolveReference={resolveReferenceLabel}\n divided\n />\n ) : null}\n </Stack>\n </CardDisplay>\n ) : null\n\n const panel = notSharedHere ? (\n <Alert severity=\"info\">{'This dataset isn’t shared with this site.'}</Alert>\n ) : notFound ? (\n <Alert severity=\"info\">{'This dataset doesn’t exist, or you can’t open it.'}</Alert>\n ) : recordPanel ? (\n recordPanel\n ) : !selected ? (\n listUnreadable && !wantedId ? (\n <Alert severity=\"error\">\n {'We couldn’t load your datasets. This does not mean there are none.'}\n </Alert>\n ) : !listConfirmed || wantedId ? (\n // Until the server answers, and while the dataset the address names is\n // read on its own: never the empty state, which is a verdict.\n <CardDisplay contentGutterX contentGutterY>\n <CircularProgress size={24} aria-label=\"Loading datasets\" />\n </CardDisplay>\n ) : datasets.length === 0 && !sharedWith && !serverNameKey ? (\n <CardDisplay contentGutterX contentGutterY>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Create a dataset, like Products, then add a repeating section ' +\n 'to any page to show one item per record.'}\n </Typography>\n </CardDisplay>\n ) : null\n ) : (\n <CardDisplay\n header={datasetRailName(selected)}\n help={pluginDocsHelp('datasets', { anchor: '#filter-records' })}\n contentGutterX\n contentGutterY\n contentBordered=\"top\"\n HeaderProps={{\n action: (\n <Stack\n direction=\"row\"\n spacing={1}\n useFlexGap\n sx={{ alignItems: 'center', flexWrap: 'wrap', justifyContent: 'flex-end' }}\n >\n <BlockedControl blocked={blocked.writes} reason={blocked.writesReason}>\n <Button\n size=\"small\"\n color=\"primary\"\n onClick={handleOpenRecord()}\n >\n {'Add record'}\n </Button>\n </BlockedControl>\n <BlockedControl blocked={blocked.writes && !blocked.sharingOnly} reason={blocked.writesReason}>\n <Button size=\"small\" onClick={() => setSchemaOpen(true)}>\n {'Schema'}\n </Button>\n </BlockedControl>\n {/* An import left unfinished, reopened where it stopped (AGL-3549). */}\n {transferTarget ? (\n <TransferResumeImport\n target={transferTarget}\n {...(selected ? { title: `Import into ${datasetDisplayName(selected)}` } : {})}\n onFinished={() => setRecordCountEpoch((epoch) => epoch + 1)}\n />\n ) : null}\n {/* Off with the permission named for a member known not to hold it,\n not hidden. Still absent while the answer is out, and where the\n launcher refuses for another reason than the key. */}\n {canImport || (transfer && transferTarget && blocked.writes) ? (\n <BlockedControl blocked={!canImport} reason={blocked.writesReason}>\n <Button size=\"small\" onClick={handleImport}>\n {'Import'}\n </Button>\n </BlockedControl>\n ) : null}\n {/* The real dataset size, not the loaded window (AGL-2335) —\n the export is a server stream, so a dataset whose first page\n has not landed yet is still exportable. */}\n {(canExport && (recordCount || records.length)) || (transfer && blocked.exports) ? (\n <BlockedControl blocked={blocked.exports} reason={DATASETS_EXPORT_REFUSAL}>\n <Button size=\"small\" onClick={handleExport}>\n {'Export'}\n </Button>\n </BlockedControl>\n ) : null}\n <BlockedControl blocked={blocked.deletes} reason={blocked.deletesReason}>\n <Button size=\"small\" color=\"error\" onClick={handleDeleteDataset}>\n {'Delete'}\n </Button>\n </BlockedControl>\n </Stack>\n ),\n subheader: factsRow(facts),\n }}\n >\n <Stack spacing={1.5}>\n {/* The per-dataset record cap, standing rather than only on refusal\n (AGL-2113). `recordCount` is the dataset's real size — the same\n number `handleOpenRecord` and the importer hand to `checkQuota`,\n not the loaded window (AGL-1716). */}\n {selected ? (\n <QuotaReadoutComponent\n ready={org != null}\n used={recordCount}\n limit={checkQuota(org, 'recordsPerDataset', recordCount).limit}\n noun=\"record\"\n />\n ) : null}\n {selected && blocked.records ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {DATASETS_VIEW_RECORDS_REFUSAL}\n </Typography>\n ) : selected && (records.length > 0 || recordPage > 0 || filteringRecords) ? (\n <>\n <ListFilterChips\n fields={recordFilter.fields}\n headers={recordFilter.headers}\n clauses={recordClauses}\n onChange={gridFilter.setClauses}\n options={recordFilter.options}\n />\n <ListQueryNotices\n refused={recordRefusals}\n notices={[...recordPlan.notices, ...recordColumnSort.notices]}\n />\n <ListTable\n aria-label=\"Records\"\n // Edit and Delete stay in reach when the columns scroll sideways\n // in the panel beside the rail (AGL-4047).\n pinActions\n rows={recordColumnSort.rows}\n columnSort={recordColumnSort}\n columns={recordGridColumns}\n onOpen={(id) => openRecord(id)}\n // One page of the walk, turned by the footer below: the grid\n // neither slices nor filters it.\n hideFooter\n filterMode=\"server\"\n filterModel={gridFilter.filterModel}\n onFilterModelChange={gridFilter.onFilterModelChange}\n quickFilter\n {...(blocked.exports ? { slotProps: EXPORT_OFF_TOOLBAR } : {})}\n noRowsLabel={\n filteringRecords ? 'No records match these filters' : 'No records yet.'\n }\n />\n {/* The count line is the PAGE's, deliberately. `recordCount` is the\n dataset's real size and it already has its own readout above —\n handing it to the footer as `count` would tell MUI the walk is\n that long and leave Next live past the end of it whenever a rule,\n a scope or a filter has narrowed what this reader may list.\n `hasMore` is a fact from the probe row, so the footer answers\n for what it is actually paging. */}\n <ListPagination\n page={recordPage}\n pageSize={recordPageSize}\n rowCount={records.length}\n hasMore={hasMoreRecords}\n onPageChange={setRecordPage}\n onPageSizeChange={setRecordPageSize}\n />\n </>\n ) : selected ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'No records yet.'}\n </Typography>\n ) : null}\n </Stack>\n </CardDisplay>\n )\n\n return (\n <>\n {/* The page's own actions, in the page header beside its title. */}\n <PageHeaderActions>\n <Stack direction=\"row\" spacing={1} useFlexGap sx={{ flexWrap: 'wrap' }}>\n <BlockedControl blocked={blocked.creates} reason={DATASETS_WRITE_REFUSAL}>\n <Button variant=\"outlined\" color=\"primary\" onClick={handleOpenCreator}>\n {'Add dataset'}\n </Button>\n </BlockedControl>\n {datasets.length >= 2 ? (\n <BlockedControl blocked={blocked.creates} reason={DATASETS_WRITE_REFUSAL}>\n <Button onClick={() => setJoiner({ a: '', b: '' })}>{'Add join collection'}</Button>\n </BlockedControl>\n ) : null}\n </Stack>\n </PageHeaderActions>\n {/* The open dataset ends the trail; the heading stays the page's. */}\n {/* On a record's page the trail runs dataset, linked, then record. */}\n {routeRecordId && selected && datasetHref ? (\n <PageHeaderRecord\n title={recordTitle}\n keepHeading\n parentTitle={datasetRailName(selected)}\n parentHref={datasetHref}\n />\n ) : (\n <PageHeaderRecord title={selected && routeDatasetId ? datasetRailName(selected) : undefined} keepHeading />\n )}\n <HubSections\n sections={railSections}\n navHeader=\"Datasets\"\n railHeader={railHeader}\n railFooter={railFooter}\n scrollRail\n >\n {panel}\n </HubSections>\n <Dialog\n open={Boolean(creator)}\n onClose={() => setCreator(null)}\n maxWidth=\"xs\"\n fullWidth\n >\n <DialogTitle>{'New dataset'}</DialogTitle>\n <DialogContent\n sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}\n >\n {orgId ? (\n <Typography variant=\"body2\" color=\"text.secondary\" sx={{ mt: 1 }}>\n {/* Ownership and visibility are separate facts (AGL-1044), and\n what a new dataset starts on depends on where it is made. */}\n {newDatasetSharingNote(createsSiteOnly)}\n </Typography>\n ) : null}\n <TextField\n label=\"Name\"\n value={creator?.name ?? ''}\n onChange={(event) =>\n setCreator((prev) =>\n prev ? { ...prev, name: event.target.value } : prev,\n )\n }\n size=\"small\"\n autoFocus\n sx={{ mt: 1 }}\n helperText=\"e.g. Products, Team, FAQ\"\n />\n <TextField\n label=\"Fields\"\n value={creator?.fields ?? ''}\n onChange={(event) =>\n setCreator((prev) =>\n prev ? { ...prev, fields: event.target.value } : prev,\n )\n }\n size=\"small\"\n helperText={\n creatorEntries.length\n ? `Columns: ${creatorEntries\n .map((entry) => entry.name)\n .join(', ')}`\n : 'Comma-separated column names, e.g. Title, Unit price'\n }\n />\n </DialogContent>\n <DialogActions>\n <Button onClick={() => setCreator(null)}>{'Cancel'}</Button>\n <Button\n variant=\"contained\"\n color=\"primary\"\n disabled={\n !scopeReady ||\n !creator?.name.trim() ||\n creatorFields.length === 0\n }\n onClick={handleCreate}\n >\n {'Create'}\n </Button>\n </DialogActions>\n </Dialog>\n {/*\n ONE viewer for the table, not one per row. Its record is a prop out of\n the page already in hand, so opening it reads nothing — and mounting\n the table does not open a dialog per row to discover that.\n */}\n <DatasetRecordDialog\n record={viewerRecord}\n model={model}\n resolveReference={resolveReferenceLabel}\n onClose={() => setViewerId(null)}\n // Explicitly separate, and a hand-off rather than a second editor:\n // the viewer closes and the record opens in the dialog that has\n // always owned writing.\n onEdit={() => {\n const record = viewerRecord\n setViewerId(null)\n if (record) handleOpenRecord(record)()\n }}\n />\n <Dialog\n open={Boolean(editor)}\n onClose={() => setEditor(null)}\n maxWidth=\"xs\"\n fullWidth\n >\n <DialogTitle>{editor?.id ? 'Edit record' : 'New record'}</DialogTitle>\n <DialogContent\n sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}\n >\n {editor?.sample ? <Alert severity=\"info\">{DATASET_SAMPLE_RECORD_NOTE}</Alert> : null}\n <DatasetRecordSiteContext.Provider value={recordSite}>\n {fields.map((fieldId, index) => {\n const field = model.fields[fieldId]\n if (!field) return null\n const value = editor?.values[fieldId] ?? ''\n const error = editor?.errors[fieldId]\n const label = field.required ? `${field.name} *` : field.name\n const setValue = (nextValue: string) =>\n setEditor((prev) =>\n prev\n ? {\n ...prev,\n values: { ...prev.values, [fieldId]: nextValue },\n errors: { ...prev.errors, [fieldId]: '' },\n }\n : prev,\n )\n const common = {\n label,\n value,\n size: 'small' as const,\n autoFocus: index === 0,\n error: Boolean(error),\n helperText: error || field.description,\n sx: index === 0 ? { mt: 1 } : undefined,\n onChange: (event: { target: { value: string } }) =>\n setValue(event.target.value),\n }\n // Custom field types (AGL-434): the declaring plugin's Input\n // takes over; values stay in input form (strings) so the\n // existing coerce/validate pipeline is unchanged.\n const customFieldType = getCustomFieldType(field.customType)\n if (customFieldType?.Input) {\n const CustomInput = customFieldType.Input\n return (\n <Stack key={fieldId} sx={index === 0 ? { mt: 1 } : undefined}>\n <CustomInput\n value={value}\n label={common.label}\n onChange={(next) => setValue(String(next ?? ''))}\n />\n {(error || field.description) ? (\n <Typography\n variant=\"caption\"\n color={error ? 'error' : 'text.secondary'}\n >\n {error || field.description}\n </Typography>\n ) : null}\n </Stack>\n )\n }\n // Typed inputs per FT.Tag (AGL-179).\n if (field.type === 'bool') {\n return (\n <TextField key={fieldId} {...common} select>\n <MenuItem value=\"\">{'—'}</MenuItem>\n <MenuItem value=\"true\">{'Yes'}</MenuItem>\n <MenuItem value=\"false\">{'No'}</MenuItem>\n </TextField>\n )\n }\n if (field.type === 'text' && field.validation?.options?.length) {\n return (\n <TextField key={fieldId} {...common} select>\n <MenuItem value=\"\">{'—'}</MenuItem>\n {field.validation.options.map((option) => (\n <MenuItem key={option} value={option}>\n {option}\n </MenuItem>\n ))}\n </TextField>\n )\n }\n if (field.type === 'reference') {\n const options = refOptions[fieldId] ?? []\n const multiple = Boolean(field.reference?.multiple)\n const selectedIds = value\n .split(',')\n .map((part) => part.trim())\n .filter(Boolean)\n return (\n <TextField\n key={fieldId}\n {...common}\n select\n value={multiple ? selectedIds : value}\n slotProps={{\n select: multiple\n ? {\n multiple: true,\n onChange: (event: any) =>\n setValue(\n (event.target.value as string[]).join(', '),\n ),\n }\n : undefined,\n }}\n >\n {multiple ? null : <MenuItem value=\"\">{'—'}</MenuItem>}\n {options.map((option) => (\n <MenuItem key={option.id} value={option.id}>\n {option.label}\n </MenuItem>\n ))}\n </TextField>\n )\n }\n if (\n field.type === 'int32' ||\n field.type === 'int64' ||\n field.type === 'float'\n ) {\n return <TextField key={fieldId} {...common} type=\"number\" />\n }\n if (field.type === 'timestamp') {\n return (\n <TextField\n key={fieldId}\n {...common}\n type=\"datetime-local\"\n slotProps={{ inputLabel: { shrink: true } }}\n />\n )\n }\n if (field.type === 'coordinates') {\n return (\n <TextField\n key={fieldId}\n {...common}\n helperText={error || field.description || 'lat, lon'}\n />\n )\n }\n if (field.type === 'sorted') {\n return (\n <TextField\n key={fieldId}\n {...common}\n helperText={\n error || field.description || 'Comma-separated list'\n }\n />\n )\n }\n return <TextField key={fieldId} {...common} />\n })}\n </DatasetRecordSiteContext.Provider>\n </DialogContent>\n <DialogActions>\n <Button onClick={() => setEditor(null)}>{'Cancel'}</Button>\n <Button\n variant=\"contained\"\n color=\"primary\"\n onClick={handleSaveRecord}\n >\n {editor?.id ? 'Save' : 'Add'}\n </Button>\n </DialogActions>\n </Dialog>\n <Dialog\n open={Boolean(joiner)}\n onClose={() => setJoiner(null)}\n maxWidth=\"xs\"\n fullWidth\n >\n <DialogTitle>{'New join collection'}</DialogTitle>\n <DialogContent\n sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}\n >\n <Typography variant=\"body2\" color=\"text.secondary\" sx={{ mt: 1 }}>\n {'Links two collections many-to-many; each row pairs one ' +\n 'document from each side.'}\n </Typography>\n {(['a', 'b'] as const).map((side) => (\n <TextField\n key={side}\n select\n size=\"small\"\n label={side === 'a' ? 'First collection' : 'Second collection'}\n value={joiner?.[side] ?? ''}\n onChange={(event) =>\n setJoiner((prev) =>\n prev ? { ...prev, [side]: event.target.value } : prev,\n )\n }\n >\n {datasets.map((item) => (\n <MenuItem key={item.$id} value={item.$id}>\n {/* Who it is shared with only where two share a name (AGL-4047). */}\n {joinLabels[item.$id]}\n </MenuItem>\n ))}\n </TextField>\n ))}\n </DialogContent>\n <DialogActions>\n <Button onClick={() => setJoiner(null)}>{'Cancel'}</Button>\n <Button\n variant=\"contained\"\n color=\"primary\"\n disabled={\n !scopeReady || !joiner?.a || !joiner?.b || joiner.a === joiner.b\n }\n onClick={handleCreateJoin}\n >\n {'Create'}\n </Button>\n </DialogActions>\n </Dialog>\n <DatasetSchemaDialog\n hostId={hostId}\n orgId={orgId ?? undefined}\n dataset={schemaOpen && selected ? selected : null}\n datasets={knownDatasets}\n // The dataset's documents, not the loaded window (AGL-1716) — the\n // dialog warns \"N documents exist\" before a narrowing type change,\n // and 500 was the cap talking, not the collection.\n recordCount={recordCount}\n seedFromCache={seed.fromCache}\n seedUnreadable={seed.unreadable}\n seedListen={seed.listen}\n canChangeSharing={!blocked.creates}\n {...(blocked.sharingOnly ? { sharingOnlyReason: blocked.writesReason } : {})}\n onClose={() => setSchemaOpen(false)}\n />\n </>\n )\n}\nHostDatasetsCard.displayName = 'HostDatasetsCard'\n\nexport default HostDatasetsCard\n"],"names":["TransferResumeImport","checkDatasetQuota","checkEntitlement","checkQuota","getCustomFieldType","PageHeaderActions","PageHeaderRecord","pluginDocsHelp","scopeTokensForHost","useTransferLauncher","visibleToHost","nameSearchKey","HubSections","AppLink","CardDisplay","MdiIcon","useConfirmationContext","mdiArrowLeft","ListFilterChips","ListPagination","ListQueryNotices","listQueryRefusals","ListTable","listActionsColumn","QuotaReadoutComponent","listFilterGridColumns","useListGridFilter","useSnackbar","Timestamp","Alert","Box","Button","Chip","CircularProgress","Dialog","DialogActions","DialogContent","DialogTitle","MenuItem","Stack","TextField","Tooltip","Typography","collection","deleteDoc","deleteField","doc","endAt","getCountFromServer","getDoc","getDocs","limit","orderBy","query","startAt","where","setDoc","writeBatch","useRouter","useCallback","useEffect","useMemo","useState","useListColumnSort","useFirestore","useFirestoreCollection","useFirestoreDoc","useHostActivityLogger","useOrgDataScope","usePagedCollection","useScopeTokens","useUser","listQueryConstraints","authorizedFetch","DatasetSchemaDialog","DatasetRecordDialog","DatasetRecordFieldList","DatasetRecordSiteContext","datasetRecordFilter","planRecordQuery","recordColumn","coerceDocumentValues","datasetIntegrityUpdate","datasetValueToInput","effectiveDatasetModel","formatDatasetValue","modelFromFieldEntries","validateDocument","fillRecordAddresses","planReferenceFixups","referencingFieldIds","restrictedDeleteMessage","BlockedControl","datasetListScope","DATASETS_EXPORT_REFUSAL","DATASETS_VIEW_RECORDS_REFUSAL","DATASETS_WRITE_REFUSAL","useDatasetWritesBlocked","DATASET_SAMPLE_RECORD_NOTE","datasetDisplayName","isSampleDatasetRecord","parseDatasetFieldEntries","datasetTransferResourceKey","DATASET_RAIL_GROUP_AT","datasetCreatedLabel","datasetPickerLabelsOf","datasetRailName","datasetRecordTitle","datasetRailSecondary","datasetSharingLabel","datasetSourceLabel","groupDatasetsBySharing","sortDatasetsByName","useOrgSites","NO_QUERY_SORTS","EXPORT_OFF_TOOLBAR","toolbar","csvOptions","disableToolbarButton","printOptions","NO_DATASETS","DATASET_LIST_WINDOW","datasetRow","snapshot","$id","id","data","newDatasetSharingNote","siteOnly","HostDatasetsCard","props","routeDatasetId","listed","hostId","basePath","segments","router","scope","dataScope","orgId","tokens","scopeTokens","orgWide","viewerOrgWide","loaded","scopeLoaded","pageHostId","undefined","reachScope","listScope","memberScope","scopeReady","Boolean","firestore","enqueueSnackbar","confirm","org","logActivity","user","createdFromHostId","createdFrom","recordSite","createsSiteOnly","defaultResourceScope","callDatasetApi","payload","response","method","headers","body","JSON","stringify","result","json","catch","ok","Error","error","announceRecords","datasetId","action","console","nameSearch","setNameSearch","sharedWith","setSharedWith","railWindow","setRailWindow","railScope","serverNameKey","hostNames","sites","orgSites","datasetDocs","status","datasetsStatus","fromCache","datasetsFromCache","listen","datasetsListen","idField","datasets","slice","moreDatasets","length","railNarrowed","routeRecordId","selectedId","setSelectedId","wantedId","find","item","listAnswered","listConfirmed","listUnreadable","linkedRead","linked","notSharedHere","visibleTo","notFound","selected","seed","unreadable","openDataset","push","landing","replace","schemaOpen","setSchemaOpen","blocked","model","fields","order","recordFilter","gridFilter","selectFields","recordClauses","clauses","filter","clause","some","field","column","recordPlan","searchWords","recordPlanKey","filters","plan","rows","records","hasMore","hasMoreRecords","page","recordPage","setPage","setRecordPage","pageSize","recordPageSize","setPageSize","setRecordPageSize","pageLimit","routeRecordRead","routeRecord","routeRecordMissing","recordRefusals","refused","options","filteringRecords","word","trim","datasetCountEpoch","setDatasetCountEpoch","recordCountEpoch","setRecordCountEpoch","serverDatasetCount","setServerDatasetCount","serverRecordCount","setServerRecordCount","active","then","count","countedDatasetId","datasetCount","recordCount","creator","setCreator","handleOpenCreator","variant","persist","quota","allowed","upgradeRequired","addonPriceUsd","name","creatorEntries","creatorFields","map","entry","handleCreate","displayName","String","message","epoch","type","joiner","setJoiner","handleCreateJoin","a","b","fieldFor","target","fieldId","required","reference","displayFieldId","onDelete","aRef","bRef","handleDeleteDataset","confirmed","title","description","toLocaleString","confirmationText","confirmationButtonProps","color","scopeId","kind","outsideTargets","setOutsideTargets","missing","Set","Promise","all","exists","knownDatasets","refOptions","setRefOptions","referenceFields","docs","docSnapshot","label","get","entries","Object","fromEntries","resolveReferenceLabel","option","referenceLabel","value","ids","Array","isArray","join","viewerId","setViewerId","datasetHref","openRecord","encodeURIComponent","viewerRecord","record","editor","setEditor","handleOpenRecord","values","default","errors","sample","handleSaveRecord","coerced","keys","prev","recordRef","updatedAt","now","mergeFields","handleDeleteRecord","afterDelete","alsoChanged","referencing","reach","other","otherModel","holders","start","updates","batch","update","holder","ref","commit","add","transfer","transferTarget","resource","known","importAllowed","writes","canImport","can","canExport","handleImport","dataset","openImport","onFinished","handleExport","openExport","search","recordGridColumns","shown","row","headerName","flex","minWidth","renderCell","direction","spacing","sx","alignItems","height","noWrap","size","justifyContent","onClick","reason","writesReason","width","recordPageSorts","recordSortHeaders","recordColumnSort","sorts","pageSorts","grouped","railSections","tab","group","href","secondary","flatMap","joinLabels","offerSharedWith","sitesByName","sort","localeCompare","railHeader","mb","fullWidth","placeholder","onChange","event","slotProps","htmlInput","select","site","railFooter","px","py","aria-label","mt","window","facts","factsRow","pairs","useFlexGap","flexWrap","component","overflowWrap","recordTitle","recordPanel","help","anchor","header","startIcon","path","span","contentGutterX","contentGutterY","contentBordered","HeaderProps","subheader","severity","resolveReference","divided","panel","sharingOnly","exports","deletes","deletesReason","ready","used","noun","setClauses","notices","pinActions","columnSort","columns","onOpen","hideFooter","filterMode","filterModel","onFilterModelChange","quickFilter","noRowsLabel","rowCount","onPageChange","onPageSizeChange","creates","keepHeading","parentTitle","parentHref","sections","navHeader","scrollRail","open","onClose","maxWidth","display","flexDirection","gap","autoFocus","helperText","disabled","onEdit","Provider","index","setValue","nextValue","common","customFieldType","customType","Input","CustomInput","next","validation","multiple","selectedIds","split","part","inputLabel","shrink","side","seedFromCache","seedUnreadable","seedListen","canChangeSharing","sharingOnlyReason"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;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AK,EAAEA,gBAAAA,QAASQ;gBAChB+P,SAAS/K,cAAcP,WAAWA,WAAW;gBAC7CnB,UAAUsI;gBACV,kEAAkE;gBAClE,mEAAmE;gBACnE,mDAAmD;gBACnDpD,aAAaA;gBACbkQ,eAAehU,KAAKzB,SAAS;gBAC7B0V,gBAAgBjU,KAAKC,UAAU;gBAC/BiU,YAAYlU,KAAKvB,MAAM;gBACvB0V,kBAAkB,CAAC3T,QAAQqR,OAAO;eAC7BrR,QAAQ+P,WAAW,GAAG;gBAAE6D,mBAAmB5T,QAAQoM,YAAY;YAAC,IAAI,CAAC;gBAC1EyF,SAAS,IAAM9R,cAAc;;;;AAIrC;AACAnG,iBAAiB0K,WAAW,GAAG;AAE/B,eAAe1K,iBAAgB"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/data/src/lib/components/host-datasets-card.component.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\nimport type { ScopePlaced } from '@aglyn/aglyn/app-utils/site-placement'\nimport { TransferResumeImport } from '@aglyn/aglyn/app-utils/transfer-resume-import'\nimport {\n type AglynOrgBilling,\n checkDatasetQuota,\n checkEntitlement,\n checkQuota,\n getCustomFieldType,\n PageHeaderActions,\n PageHeaderRecord,\n pluginDocsHelp,\n scopeTokensForHost,\n useTransferLauncher,\n visibleToHost,\n} from '@aglyn/aglyn'\nimport { nameSearchKey } from '@aglyn/aglyn/app-utils/name-search'\nimport { HubSections, type HubSection } from '@aglyn/shared-ui-next/components/hub-tabs'\nimport { AppLink, CardDisplay, MdiIcon, useConfirmationContext } from '@aglyn/shared-ui-jsx'\nimport { mdiArrowLeft } from '@aglyn/shared-data-mdi'\nimport ListFilterChips from '@aglyn/shared-ui-jsx/components/list-filter-chips.component'\nimport { ListPagination } from '@aglyn/shared-ui-jsx/components/list-pagination.component'\nimport ListQueryNotices, {\n listQueryRefusals,\n} from '@aglyn/shared-ui-jsx/components/list-query-notices.component'\nimport {\n ListTable,\n listActionsColumn,\n} from '@aglyn/shared-ui-jsx/components/list-table.component'\nimport QuotaReadoutComponent from '@aglyn/shared-ui-jsx/components/quota-readout.component'\nimport { listFilterGridColumns } from '@aglyn/shared-ui-jsx/const/list-grid-filter'\nimport { useListGridFilter } from '@aglyn/shared-ui-jsx/hooks/use-list-grid-filter'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport { Timestamp } from '@aglyn/shared-util-timestamp'\nimport {\n Alert,\n Box,\n Button,\n Chip,\n CircularProgress,\n Dialog,\n DialogActions,\n DialogContent,\n DialogTitle,\n MenuItem,\n Stack,\n TextField,\n Tooltip,\n Typography,\n} from '@mui/material'\nimport {\n collection,\n deleteDoc,\n deleteField,\n doc,\n endAt,\n getCountFromServer,\n getDoc,\n getDocs,\n limit,\n orderBy,\n query,\n startAt,\n where,\n setDoc,\n writeBatch,\n} from 'firebase/firestore'\nimport { useRouter } from 'next/navigation'\nimport { useCallback, useEffect, useMemo, useState } from 'react'\nimport { useListColumnSort } from '@aglyn/shared-ui-jsx/hooks/use-list-column-sort'\nimport {\n useFirestore,\n useFirestoreCollection,\n useFirestoreDoc,\n useHostActivityLogger,\n useOrgDataScope,\n usePagedCollection,\n useScopeTokens,\n useUser,\n} from '@aglyn/tenant-feature-instance'\nimport { listQueryConstraints } from '@aglyn/tenant-feature-instance/hooks/use-list-query'\nimport { authorizedFetch } from '@aglyn/shared-util-http/authorized-token'\nimport { DatasetSchemaDialog } from './dataset-schema-dialog.component'\nimport { DatasetRecordDialog, DatasetRecordFieldList } from './dataset-record-dialog.component'\nimport { DatasetRecordSiteContext } from './dataset-field-inputs.component'\nimport { DatasetIconPreview } from './dataset-icon-field-input.component'\nimport { DATASET_ICON_FIELD_TYPE, readDatasetIconValue } from '../model/dataset-icon-field'\nimport {\n datasetRecordFilter,\n planRecordQuery,\n recordColumn,\n} from './dataset-record-filter'\nimport { coerceDocumentValues, datasetIntegrityUpdate, datasetValueToInput, effectiveDatasetModel, formatDatasetValue, modelFromFieldEntries, validateDocument } from '../model/dataset-models'\nimport { fillRecordAddresses } from '../record-pages/record-pages'\nimport { planReferenceFixups, referencingFieldIds, restrictedDeleteMessage } from '../model/dataset-record-delete-plan'\nimport { BlockedControl } from '@aglyn/shared-ui-jsx/components/blocked-control.component'\nimport { datasetListScope } from '../model/dataset-record-list'\nimport {\n DATASETS_EXPORT_REFUSAL,\n DATASETS_VIEW_RECORDS_REFUSAL,\n DATASETS_WRITE_REFUSAL,\n useDatasetWritesBlocked,\n} from './use-dataset-writes-blocked'\nimport { DATASET_SAMPLE_RECORD_NOTE, datasetDisplayName, isSampleDatasetRecord, parseDatasetFieldEntries } from '../model/datasets'\nimport { datasetTransferResourceKey } from '../transfer/dataset-transfer-key'\nimport {\n DATASET_RAIL_GROUP_AT,\n type DatasetRailEntry,\n datasetCreatedLabel,\n datasetPickerLabelsOf,\n datasetRailName,\n datasetRecordTitle,\n datasetRailSecondary,\n datasetSharingLabel,\n datasetSourceLabel,\n groupDatasetsBySharing,\n sortDatasetsByName,\n} from '../model/dataset-rail'\nimport { useOrgSites } from './use-org-sites'\n\nexport interface HostDatasetsCardProps {\n /** Host context: resolves the owning org and logs host activity. */\n hostId?: string\n /**\n * Direct org scope (AGL-239): the org Data page renders the editor\n * without any host context. Wins over `hostId` resolution when set.\n */\n orgId?: string\n /**\n * The resolved entitlement source (org billing doc). Passed in by both\n * callers (the plugin Data page via the shell, the org Data page via its\n * own resolver) so this relocated card runs entitlement/quota checks\n * without console-app org/session hooks (AGL-395).\n */\n org?: Partial<AglynOrgBilling>\n /**\n * The Data page's own address (AGL-4047): each dataset is a tab of the\n * page's rail, at `<basePath>/<datasetId>`. Handed down by both callers —\n * the site's plugin route and the organization Data page.\n */\n basePath?: string\n /**\n * The path beneath {@link basePath}: `[datasetId]` on a dataset's tab,\n * `[datasetId, 'records', recordId]` on one of its records, and empty on the\n * bare page, which opens the first dataset.\n */\n segments?: readonly string[]\n}\n\n/**\n * The sentence that says who a NEW dataset is shared with, for the card and\n * for the site Data page's banner above it.\n *\n * `siteOnly` is true only on a site's Data page in an org whose Default\n * sharing is \"Only the site they were created in\". Everywhere else a new\n * dataset starts on All sites: the org Data page has no site to limit it to.\n */\n/** The records walk serves no header order: every header sorts the page. */\nconst NO_QUERY_SORTS: never[] = []\n\n/** The grid's own Export and Print, off for a member without \"Export data\" (AGL-4047). */\nconst EXPORT_OFF_TOOLBAR = {\n toolbar: { csvOptions: { disableToolbarButton: true }, printOptions: { disableToolbarButton: true } },\n}\n\n/** Stable, so an empty answer does not re-render the card. */\nconst NO_DATASETS: any[] = []\n\n/**\n * The datasets the rail loads at a time, and the most a delete's reference\n * check walks. \"Show more datasets\" loads the next window, so the rail\n * reaches every dataset however many there are (AGL-4047).\n */\nconst DATASET_LIST_WINDOW = 100\n\n/** A dataset read off its document, as the card's rows carry it. */\nconst datasetRow = (snapshot: { id: string; data(): unknown }) => ({\n $id: snapshot.id,\n ...(snapshot.data() as object),\n})\n\nexport function newDatasetSharingNote(siteOnly: boolean): string {\n return siteOnly\n ? 'Datasets belong to your organization. Your default sharing starts a ' +\n 'new one on this site only — use Schema to share it with more.'\n : 'Datasets belong to your organization. A new one is shared with ' +\n 'every site — use Schema to narrow that.'\n}\n\n/**\n * Datasets editor (AGL-102): org-shared document collections at\n * `orgs/{orgId}/datasets` (AGL-237/239) with a `records` subcollection,\n * consumed by repeatable components (AGL-103) via `{{item.field}}`.\n * Starter+ (`data-store` flag) with per-plan dataset and record caps —\n * dark-launch rule as everywhere (no plan, no gate). The host path is\n * the pre-migration fallback for hosts not yet org-wired.\n */\nexport function HostDatasetsCard(props: HostDatasetsCardProps) {\n const { hostId, basePath, segments } = props\n const router = useRouter()\n // `dataScope` is null until the async org lookup settles (AGL-1061), and\n // for a host with no owning org — there is no host fallback to act on\n // any more (AGL-1050), so every path built from it is guarded rather\n // than redirected.\n const { scope: dataScope, orgId } = useOrgDataScope({\n hostId,\n orgId: props.orgId,\n })\n // Scoped sharing (AGL-1044). Required, not cosmetic: under the AGL-1041\n // rules a scoped member's UNFILTERED list is rejected outright —\n // Firestore fails the whole query if any candidate would fail — so\n // without this the Data page errors rather than showing fewer rows.\n const {\n tokens: scopeTokens,\n orgWide: viewerOrgWide,\n loaded: scopeLoaded,\n } = useScopeTokens(orgId)\n /**\n * The site whose Data page this is, or undefined on the organization Data\n * page. The explicit `orgId` is that page's own scope and already wins over\n * `hostId` when the org is resolved, so it wins here too, even if a caller\n * hands the card both.\n */\n const pageHostId = props.orgId ? undefined : hostId || undefined\n // What the VIEWER reaches: their scope tokens, or no filter for an org-wide\n // member, who reads everything. Every dataset here is an org dataset, and\n // org datasets are all scoped (AGL-1041).\n const reachScope = viewerOrgWide ? null : scopeTokens\n /**\n * What this page lists (AGL-4047): a site's Data page shows that site's and\n * the workspace-wide datasets, whoever is looking, as every other site\n * surface does. It used to ask only the viewer's reach, so an owner, who\n * reaches everything, saw every site's datasets on every site. The\n * organization Data page lists the viewer's reach.\n */\n const listScope = useMemo(\n () => datasetListScope({ hostId: pageHostId, memberScope: reachScope }),\n [pageHostId, reachScope],\n )\n // Two answers must be in before listing: the org path (AGL-1061) and the\n // viewer's scope tokens (AGL-1047). `useScopeTokens` reports org-wide\n // while loading, so without `scopeLoaded` a scoped collaborator's first\n // render sends an UNFILTERED list that the AGL-1041 rules deny per\n // document. It recovers on the next render, which is exactly what makes\n // it easy to miss: the page looks right and logs a denial every mount.\n const scopeReady = Boolean(dataScope) && scopeLoaded\n const firestore = useFirestore()\n const { enqueueSnackbar } = useSnackbar()\n const { confirm } = useConfirmationContext()\n const { org } = props\n const logActivity = useHostActivityLogger(hostId)\n const { data: user } = useUser()\n /**\n * The site a dataset created here is created FROM, or undefined on the\n * organization Data page.\n *\n * `/api/orgs/datasets` stamps a new dataset with the org's Default sharing,\n * and that setting can only narrow to a site the request names — so a\n * create that names none lands on All sites whatever the org chose.\n */\n const createdFromHostId = pageHostId\n const createdFrom = useMemo(\n () => (createdFromHostId ? { hostId: createdFromHostId } : {}),\n [createdFromHostId],\n )\n /**\n * The site the record editor's Page field lists pages from (AGL-3763): the\n * site whose Data page this is, and none on the organization Data page,\n * where a dataset is no one site's.\n */\n const recordSite = useMemo(\n () => ({ hostId: createdFromHostId }),\n [createdFromHostId],\n )\n /**\n * Whether a dataset created here starts on this site alone: the org chose\n * \"Only the site they were created in\" and there is a site to limit it to.\n * The caption reads it so it never promises All sites to a create that\n * will not get it.\n */\n const createsSiteOnly =\n Boolean(createdFromHostId) &&\n (org as { defaultResourceScope?: 'org' | 'host' } | undefined)\n ?.defaultResourceScope === 'host'\n\n // Creates go through the console API (AGL-473): rules deny client-side\n // `create` on org datasets/records so quotas are server-enforced.\n // Updates/deletes stay client-direct (they don't consume quota). The\n // legacy host scope (no org resolved) keeps the old client writes.\n const callDatasetApi = useCallback(\n async (payload: Record<string, unknown>) => {\n const response = await authorizedFetch(user, '/api/orgs/datasets', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ orgId, ...payload }),\n })\n const result = await response.json().catch(() => ({}))\n if (!response.ok) {\n throw new Error(result?.error ?? 'Dataset operation failed')\n }\n return result\n },\n [user, orgId],\n )\n\n /**\n * Refresh the live pages showing a dataset after a write the BROWSER made\n * (AGL-3113).\n *\n * Record edits and deletes are client-direct — they consume no quota, so\n * AGL-473 left them out of the server leg — which also left them with\n * nothing to announce from. They make a page listing the rows exactly as\n * stale as a create does, so they take the same trip the create already\n * takes, through the route that already holds the org membership check.\n *\n * BEST EFFORT. The record is stored by the time this runs, and the pages\n * catch up on their own window regardless; a refused cache must never be\n * shown to somebody as a refused save.\n */\n const announceRecords = useCallback(\n async (datasetId: string) => {\n try {\n await callDatasetApi({ action: 'announce-records', datasetId })\n } catch (error) {\n console.error(error)\n }\n },\n [callDatasetApi],\n )\n\n /**\n * The rail's search and its Shared with filter (AGL-4047).\n *\n * The filter is a query clause: one site the reader reaches, asked by that\n * site's scope tokens in place of the page's own, which they sit inside —\n * a site the reader is a member of is one their own tokens already reach,\n * so the narrower query is still one the rules can prove. Offered on the\n * organization Data page only: a site's page already lists that site's.\n */\n const [nameSearch, setNameSearch] = useState('')\n const [sharedWith, setSharedWith] = useState('')\n const [railWindow, setRailWindow] = useState(DATASET_LIST_WINDOW)\n const railScope = useMemo(\n () => (sharedWith && !pageHostId ? scopeTokensForHost(sharedWith) : listScope),\n [sharedWith, pageHostId, listScope],\n )\n /** The search as the stored `nameLower` is normalized, asked of the server as a prefix. */\n const serverNameKey = nameSearchKey(nameSearch)\n const { hostNames, sites: orgSites } = useOrgSites(orgId)\n\n const {\n data: datasetDocs,\n status: datasetsStatus,\n /**\n * The dataset rows are unconfirmed by the server (AGL-1358). The schema\n * dialog is seeded from one of them and writes the whole `model` plus\n * `visibleTo` back, so the freshness verdict belongs to THIS listener —\n * the dialog has none of its own, which is why it is handed down rather\n * than recomputed there.\n */\n fromCache: datasetsFromCache,\n listen: datasetsListen,\n } = useFirestoreCollection<any>(\n () =>\n // `scopeReady` already implies a non-null `dataScope`; testing it\n // directly is what lets the compiler see that too.\n dataScope && scopeReady\n ? query(\n collection(firestore, dataScope[0], dataScope[1], 'datasets'),\n ...(railScope\n ? [where('visibleTo', 'array-contains-any', [...railScope])]\n : []),\n /*\n * The rail in name order, and the search as a `nameLower` prefix\n * asked of the server, so it finds a dataset past the loaded\n * window (AGL-4047). Served by the `datasets (visibleTo CONTAINS,\n * nameLower ASC)` index beside the scope clause. Ordering on a\n * field leaves out a document that lacks it, so every writer\n * stamps `nameLower` through `datasetNameLower`, and\n * `tools/scripts/backfill-dataset-name-lower.mjs` stamped the\n * datasets saved before. One row past the window says whether\n * there are more.\n */\n orderBy('nameLower'),\n ...(serverNameKey ? [startAt(serverNameKey), endAt(`${serverNameKey}\\uf8ff`)] : []),\n limit(railWindow + 1),\n )\n : null,\n [firestore, dataScope, railScope, scopeReady, railWindow, serverNameKey],\n { idField: '$id' },\n )\n /** The loaded window in name order: what the join dialog and the reference checks read. */\n const datasets = useMemo(\n () => sortDatasetsByName<any>([...(datasetDocs ?? [])].slice(0, railWindow)),\n [datasetDocs, railWindow],\n )\n const moreDatasets = (datasetDocs?.length ?? 0) > railWindow\n /**\n * Whether the loaded window is short of everything this page lists: a\n * filter or the name search narrowed it, or there are more. A check that\n * must see every dataset — what references a record about to be deleted —\n * reads for itself then.\n */\n const railNarrowed =\n Boolean(pageHostId) || Boolean(sharedWith) || Boolean(serverNameKey) || moreDatasets\n\n /**\n * The open dataset (AGL-4047): the one the address names, or, on the bare\n * page, none until the page moves to the first. The card is also mounted\n * without an address by callers outside the console's routes, which pick\n * one by state.\n */\n const routeDatasetId = basePath ? segments?.[0] : undefined\n /** The record the address opens on its own page (AGL-4047), beneath its dataset's tab. */\n const routeRecordId = basePath && segments?.[1] === 'records' ? segments?.[2] : undefined\n const [selectedId, setSelectedId] = useState<string | null>(null)\n const wantedId = routeDatasetId ?? selectedId ?? undefined\n const listed = wantedId ? datasets.find((item) => item.$id === wantedId) : undefined\n /**\n * The list has emitted, from the cache or the server: enough to look for\n * the open dataset on its own when the window does not hold it.\n */\n const listAnswered = datasetsStatus !== 'loading'\n /**\n * The SERVER has answered the list (AGL-4047). Only this may say there are\n * no datasets. `useFirestoreCollection` hands back `[]` from its first\n * render, before any snapshot, and a cold cache answers `[]` too, unconfirmed:\n * reading either as \"none\" showed a site with five datasets the \"Create a\n * dataset\" empty state for the 16 s its list took to reach the server.\n */\n const listConfirmed = scopeReady && datasetsStatus === 'success' && !datasetsFromCache\n /** The list failed for good, so neither \"none\" nor \"loading\" is true. */\n const listUnreadable = datasetsStatus === 'error'\n /*\n * A dataset the address names that the loaded window does not hold — past\n * the window, outside the filter, or only just created — is read on its\n * own, live, so its tab still opens and a save still seeds from a listener.\n */\n const linkedRead = useFirestoreDoc<any>(\n () =>\n dataScope && scopeReady && wantedId && listAnswered && !listed\n ? doc(firestore, dataScope[0], dataScope[1], 'datasets', wantedId)\n : null,\n [firestore, dataScope, scopeReady, wantedId, listAnswered, Boolean(listed)],\n )\n // Keyed by the id it was read under, as the list's rows are.\n const linked = useMemo(\n () => (!listed && wantedId && linkedRead.data ? { ...linkedRead.data, $id: wantedId } : undefined),\n [listed, wantedId, linkedRead.data],\n )\n /** A site's page refuses a dataset that is not shared with the site (#2341). */\n const notSharedHere = Boolean(\n pageHostId && linked && !visibleToHost((linked as { visibleTo?: string[] }).visibleTo, pageHostId),\n )\n const notFound = Boolean(\n wantedId &&\n listAnswered &&\n !listed &&\n !linked &&\n (linkedRead.status === 'error' || (linkedRead.status !== 'loading' && !linkedRead.fromCache)),\n )\n const selected =\n listed ??\n (linked && !notSharedHere ? linked : undefined) ??\n (wantedId ? undefined : datasets[0])\n /** Which listener the open dataset came from, for the schema dialog's freshness guard. */\n const seed = listed || !linked\n ? { fromCache: datasetsFromCache, unreadable: datasetsStatus === 'error', listen: datasetsListen }\n : { fromCache: linkedRead.fromCache, unreadable: linkedRead.status === 'error', listen: linkedRead.listen }\n /** Opens a dataset: its own address on a routed page, the card's state elsewhere. */\n const openDataset = useCallback(\n (id: string | null) => {\n if (basePath) router.push(id ? `${basePath}/${id}` : basePath)\n else setSelectedId(id)\n },\n [basePath, router],\n )\n // The bare page opens the first dataset, as a hub opens its first section,\n // so the rail always has a tab lit and the address names what is open.\n const landing = basePath && !routeDatasetId && datasets[0] ? `${basePath}/${datasets[0].$id}` : null\n useEffect(() => {\n if (landing) router.replace(landing)\n }, [landing, router])\n const [schemaOpen, setSchemaOpen] = useState(false)\n // What this member may do with THIS dataset (AGL-4047): one placed on one site\n // answers to that site.\n const blocked = useDatasetWritesBlocked(orgId, selected as ScopePlaced | undefined)\n // Typed model (AGL-179): drives headers, cell rendering, and the\n // document form; v1 datasets get a derived all-text model.\n const model = useMemo(\n () => effectiveDatasetModel(selected ?? {}),\n [selected],\n )\n const fields: string[] = useMemo(() => model.order, [model])\n // The records grid's Filters panel, from the dataset's own schema.\n const recordFilter = useMemo(() => datasetRecordFilter(model), [model])\n\n // Guarded on BOTH the scope and a real selection (AGL-1440): with no\n // datasets, `selected` never resolves, and `datasets/-none-/records` is not\n // an empty read for everyone — the AGL-1044 scoped-sharing rules deny it\n // outright for a scoped collaborator, and a permanently denied listen is\n // reopened forever by the refusal loop.\n /**\n * The records table PAGES (AGL-2501). It used to be `limit(500)` with no\n * `orderBy`, every row rendered at once and no control anywhere.\n *\n * That was wrong twice. Five hundred documents were read and billed on\n * every mount of a card nobody had scrolled — and past five hundred the\n * remaining rows were not merely unrendered, they were UNREACHABLE, because\n * nothing showed them and nothing asked for more. Firestore answers an\n * unordered limit in document-id order over auto-ids, so which five hundred\n * a reader got was arbitrary and could differ between two loads of the same\n * dataset; `sortDatasetRecords` then sorted that sample by `order`, which\n * made the table look ordered while being a sample. The export leg\n * (AGL-2335) fixed exactly this shape for the file and left the table.\n *\n * ## Why the walk orders on the document id, and not on a field\n *\n * The usual fix is `orderBy` on the field the rows are sorted by. It cannot\n * be used here: `orderBy` matches only documents that HAVE the field, so\n * ordering on one that any writer omits does not mis-order the list, it\n * hides rows from it — a worse failure than the one being fixed, and a\n * silent one. Every candidate on this collection is omitted by some writer:\n *\n * * `order` — set by `/api/orgs/datasets` and by `POST /v1/datasets/{id}\n * /records`, and NOT by the tenant form-submit leg or by the workflow\n * `appendDataset`/`updateDataset` actions, which write `values` and\n * `createdAt` only. Ordering on it would drop every row a public form or\n * an automation ever produced — the rows a lead dataset is mostly made\n * of.\n * * `createdAt` — written by all four of those, and NOT by a site import:\n * `IMPORTABLE_FIELDS.records` is `['values', 'order']`, so a restored\n * record carries no `createdAt` at all.\n * * `updatedAt` — the mirror image: the import stamps it, the form and\n * automation legs do not.\n *\n * A document's NAME is not a field and cannot be absent, so ordering on it\n * drops nothing and the walk is total: every record is reachable by paging,\n * which is the property the old query lacked. It is not insertion order —\n * ids are random — so the rows are not claimed to be in one. What they are\n * is stable, complete, and the same on every load.\n *\n * `sortDatasetRecords` is deliberately NOT applied to the page. Re-sorting a\n * window of an id-ordered walk by `order` is the same lie the old code told:\n * rows would run in one order within a page and another across pages.\n * For the same reason a header sorts THIS PAGE only, and says so\n * (AGL-3680, `recordColumnSort` below): no stored field could serve it.\n *\n * ## Filtering: every clause and the search word are on the query\n *\n * The grid's Filters panel and quick search are predicates on this same\n * walk (AGL-3321), planned by `planRecordQuery` (`./dataset-record-filter`,\n * over the shared `planListQuery`): equalities ask the record's\n * `filterValues`, and one word-level clause — a text `contains`, a list\n * member, or the search word — asks its `filterKeys`. Firestore's\n * automatic single-field indexes merge them under the same document-name\n * order, so every filter pages through every matching record exactly as\n * the plain walk pages through all of them, with no composite index and\n * no index deploy.\n *\n * Nothing is matched over the rows already loaded. What one query cannot\n * hold is not offered (ranges, negations, empty checks) or is refused by\n * name above the table (a second `contains`, a `contains` beside the\n * search), and a many-word `contains` or search says it asked the first\n * word.\n */\n const gridFilter = useListGridFilter({ selectFields: recordFilter.selectFields })\n // A clause on a field this dataset does not have (the reader switched\n // datasets) narrows nothing and is not shown.\n const recordClauses = useMemo(\n () =>\n gridFilter.clauses.filter((clause) =>\n recordFilter.fields.some((field) => field.column === clause.field),\n ),\n [gridFilter.clauses, recordFilter.fields],\n )\n const recordPlan = useMemo(\n () => planRecordQuery(model, recordFilter, recordClauses, gridFilter.searchWords),\n [model, recordFilter, recordClauses, gridFilter.searchWords],\n )\n // The query's identity: a new plan is a new walk, from page one.\n const recordPlanKey = JSON.stringify({\n filters: recordPlan.plan.filters,\n orderBy: recordPlan.plan.orderBy,\n })\n const {\n rows: records,\n hasMore: hasMoreRecords,\n page: recordPage,\n setPage: setRecordPage,\n pageSize: recordPageSize,\n setPageSize: setRecordPageSize,\n } = usePagedCollection<any>(\n (pageLimit) =>\n // A record's own page shows no table, so it reads none (AGL-4047).\n dataScope && selected?.$id && !blocked.records && !routeRecordId\n ? query(\n collection(\n firestore,\n dataScope[0],\n dataScope[1],\n 'datasets',\n selected.$id,\n 'records',\n ),\n ...listQueryConstraints(recordPlan.plan),\n limit(pageLimit),\n )\n : null,\n [firestore, dataScope, selected?.$id, recordPlanKey, blocked.records, routeRecordId],\n { idField: '$id' },\n )\n /**\n * The record a record's own page opens (AGL-4047), read on its own and live,\n * so a deep link to a record on no loaded page still opens and an edit shows\n * as soon as it lands. Asked only of a member who may view the records.\n */\n const routeRecordRead = useFirestoreDoc<any>(\n () =>\n dataScope && selected?.$id && routeRecordId && !blocked.records\n ? doc(firestore, dataScope[0], dataScope[1], 'datasets', selected.$id, 'records', routeRecordId)\n : null,\n [firestore, dataScope, selected?.$id, routeRecordId, blocked.records],\n )\n // Keyed by the id it was read under, as the table's rows are.\n const routeRecord = useMemo(\n () => (routeRecordId && routeRecordRead.data ? { ...routeRecordRead.data, $id: routeRecordId } : null),\n [routeRecordId, routeRecordRead.data],\n )\n const routeRecordMissing = Boolean(\n routeRecordId &&\n !routeRecord &&\n (routeRecordRead.status === 'error' || (routeRecordRead.status !== 'loading' && !routeRecordRead.fromCache)),\n )\n const recordRefusals = useMemo(\n () =>\n listQueryRefusals(recordPlan.refused, {\n fields: recordFilter.fields,\n headers: recordFilter.headers,\n options: recordFilter.options,\n }),\n [recordPlan.refused, recordFilter],\n )\n const filteringRecords =\n recordClauses.length > 0 || gridFilter.searchWords.some((word) => word.trim())\n /**\n * The two HEAD-COUNTS on this card are server aggregates, not the lengths\n * of the two capped listeners above (AGL-1716, the AGL-1706 shape).\n *\n * Both listeners are capped correctly — 100 datasets in a picker, 500 rows\n * in a table, nobody needs more streamed in. What neither may do is answer\n * \"how many does this org have\", and both did:\n *\n * * `records.length` saturated at 500 and was handed to\n * `checkQuota(org, 'recordsPerDataset', …)`. The bands are 1,000 /\n * 10,000 / 100,000 / 500,000 / 1,000,000, so on EVERY paid plan the\n * check read 500-against-thousands and could never refuse. Worse, the\n * importer computed its room as `limit − records.length`, so an\n * understated count *inflated* the slots it offered.\n * * `datasets.length` saturated at 100 and fed `checkDatasetQuota`, whose\n * bands run to 250 / 500 / 2,000 above that window.\n *\n * `api/orgs/datasets` — the route that actually enforces both — counts with\n * `collection('datasets').count()` and `collection('records').count()` on\n * these exact paths, so this card was offering headroom the API would then\n * refuse. It now asks the same question the same way, and the console\n * billing page and the staff org page already read the dataset count with\n * this identical unscoped aggregate.\n *\n * THE LISTS KEEP THEIR CAPS. The list and the count are different\n * questions; only the count moved. A one-shot goes stale where a listener\n * refreshed for free, so both are re-read after any mutation that can move\n * them — the epochs below.\n *\n * No counting RULE moves: `checkQuota` and `checkDatasetQuota` are\n * untouched entitlement inputs, and nothing here is metered by\n * `report-usage` (it samples record counts server-side for storage, on its\n * own read). Only this card's inputs stopped being saturated.\n */\n const [datasetCountEpoch, setDatasetCountEpoch] = useState(0)\n const [recordCountEpoch, setRecordCountEpoch] = useState(0)\n const [serverDatasetCount, setServerDatasetCount] = useState<number | null>(\n null,\n )\n // TAGGED with the dataset it describes. A bare number would have to be\n // cleared when the selection changes, and clearing state from inside the\n // effect that fills it is a render loop waiting for one unstable dep;\n // tagging answers \"whose count is this?\" without writing state on render.\n const [serverRecordCount, setServerRecordCount] = useState<{\n datasetId: string\n count: number\n } | null>(null)\n useEffect(() => {\n if (!dataScope) return\n let active = true\n // Unscoped, exactly like `api/orgs/datasets` and the billing page: the\n // quota is about the ORG's datasets, not the subset this collaborator\n // can see. A scoped collaborator whom AGL-1044 denies the read falls\n // through to the catch and keeps the visible-rows lower bound.\n void getCountFromServer(\n collection(firestore, dataScope[0], dataScope[1], 'datasets'),\n )\n .then((snapshot) => {\n if (active) setServerDatasetCount(snapshot.data().count)\n })\n .catch(() => {\n // Falls back to the listener length below — a LOWER bound, and this\n // card's prior behaviour. Deliberately not 0: `checkDatasetQuota`\n // answers from whatever it is handed, and 0 used is a confident\n // wrong number in the flattering direction.\n })\n return () => {\n active = false\n }\n }, [firestore, dataScope, datasetCountEpoch])\n // The dataset the counts below belong to. Distinct from `selectedId`\n // above, which is the PICKER value and is null until the user chooses.\n const countedDatasetId: string | undefined = selected?.$id\n useEffect(() => {\n if (!dataScope || !countedDatasetId || blocked.records) return\n let active = true\n void getCountFromServer(\n collection(\n firestore,\n dataScope[0],\n dataScope[1],\n 'datasets',\n countedDatasetId,\n 'records',\n ),\n )\n .then((snapshot) => {\n if (active) {\n setServerRecordCount({\n datasetId: countedDatasetId,\n count: snapshot.data().count,\n })\n }\n })\n .catch(() => {\n // Same fallback, same reason as above.\n })\n return () => {\n active = false\n }\n }, [firestore, dataScope, countedDatasetId, recordCountEpoch, blocked.records])\n // Pending, denied, or answered about the PREVIOUS selection, the loaded\n // rows stand in. They can only UNDERSTATE (same collections, capped),\n // never overstate, so nothing these figures gate fires on a count larger\n // than the truth. Since AGL-2501 the record fallback is one PAGE, so it\n // understates by more — which moves it further in the safe direction and\n // changes nothing about which way it can be wrong.\n const datasetCount = serverDatasetCount ?? datasets.length\n const recordCount =\n serverRecordCount && serverRecordCount.datasetId === countedDatasetId\n ? serverRecordCount.count\n : records.length\n\n // --- Create dataset -----------------------------------------------------\n const [creator, setCreator] = useState<{\n name: string\n fields: string\n } | null>(null)\n const handleOpenCreator = useCallback(() => {\n if (!checkEntitlement(org, 'dataStore')) {\n return enqueueSnackbar(\n 'Datasets require a Starter plan or higher — see Billing',\n { variant: 'warning', persist: false },\n )\n }\n // Addon-aware quota (AGL-132): purchased extra datasets raise the\n // limit up to the plan's hard max; beyond that only an upgrade helps.\n // The ORG's datasets, not the picker's window (AGL-1716).\n const quota = checkDatasetQuota(org as any, datasetCount)\n if (!quota.allowed) {\n return enqueueSnackbar(\n quota.upgradeRequired\n ? `Dataset limit reached (${quota.limit}) — upgrade in Billing`\n : `Dataset limit reached (${quota.limit}) — add extra datasets ` +\n `for $${quota.addonPriceUsd}/mo each or upgrade in Billing`,\n { variant: 'warning', persist: false },\n )\n }\n setCreator({ name: '', fields: '' })\n }, [org, datasetCount, enqueueSnackbar])\n // Entries are human names — \"Roast preference\" → stable id\n // `roast_preference` with the pretty name kept for headers (AGL-558).\n const creatorEntries = parseDatasetFieldEntries(creator?.fields ?? '')\n const creatorFields = creatorEntries.map((entry) => entry.id)\n const handleCreate = useCallback(async () => {\n // No org, no create. The `else` that used to sit below this was the\n // legacy host-scope client write (AGL-1050) — the one path by which a\n // dataset could be created with NO quota check, since /api/orgs/datasets\n // is where AGL-473 enforces it. The rules now deny that path outright;\n // this is the client side of the same closure. The Add button is\n // disabled without a scope, so reaching the guard means a stale closure.\n if (!creator?.name.trim() || creatorFields.length === 0 || !orgId) return\n let id: string\n try {\n const result = await callDatasetApi({\n action: 'create-dataset',\n displayName: creator.name.trim(),\n fields: creatorFields,\n // Typed model from day one (AGL-178); refine in the Schema dialog.\n model: modelFromFieldEntries(creatorEntries),\n ...createdFrom,\n })\n id = String(result.id)\n } catch (error: any) {\n return void enqueueSnackbar(error?.message ?? 'Dataset create failed', {\n variant: 'warning',\n persist: false,\n })\n }\n setCreator(null)\n openDataset(id)\n setDatasetCountEpoch((epoch) => epoch + 1)\n enqueueSnackbar(`Dataset \"${creator.name.trim()}\" created`, {\n variant: 'success',\n persist: false,\n })\n logActivity('Created dataset', {\n type: 'content',\n id,\n name: creator.name.trim(),\n })\n }, [creator, creatorEntries, creatorFields, orgId, createdFrom, callDatasetApi, enqueueSnackbar, logActivity, openDataset])\n\n // Join collection template (AGL-180): extrinsic many-to-many as a\n // visible, editable collection of FKey pairs — no magic.\n const [joiner, setJoiner] = useState<{ a: string; b: string } | null>(null)\n const handleCreateJoin = useCallback(async () => {\n if (!joiner?.a || !joiner?.b || joiner.a === joiner.b) return\n const a = datasets.find((item) => item.$id === joiner.a)\n const b = datasets.find((item) => item.$id === joiner.b)\n // A join collection is a dataset and consumes the same quota, so it\n // takes the same API-only route (AGL-1050) — the host-scope client\n // write that used to stand in for it is gone.\n if (!a || !b || !orgId) return\n const fieldFor = (target: any, fieldId: string) => ({\n name: datasetDisplayName(target) || fieldId,\n type: 'reference' as const,\n required: true,\n reference: {\n datasetId: target.$id as string,\n displayFieldId: effectiveDatasetModel(target).order[0],\n onDelete: 'setNull' as const,\n },\n })\n const payload = {\n displayName: `${datasetDisplayName(a)} ↔ ${datasetDisplayName(b)}`,\n fields: ['aRef', 'bRef'],\n model: {\n order: ['aRef', 'bRef'],\n fields: { aRef: fieldFor(a, 'aRef'), bRef: fieldFor(b, 'bRef') },\n },\n }\n let id: string\n try {\n const result = await callDatasetApi({\n action: 'create-dataset',\n ...payload,\n // A join collection is a dataset, so the same Default sharing applies.\n ...createdFrom,\n })\n id = String(result.id)\n } catch (error: any) {\n return void enqueueSnackbar(error?.message ?? 'Join create failed', {\n variant: 'warning',\n persist: false,\n })\n }\n setJoiner(null)\n openDataset(id)\n // A join collection IS a dataset and consumes the same quota.\n setDatasetCountEpoch((epoch) => epoch + 1)\n enqueueSnackbar('Join collection created', {\n variant: 'success',\n persist: false,\n })\n }, [joiner, datasets, orgId, createdFrom, callDatasetApi, enqueueSnackbar, openDataset])\n\n const handleDeleteDataset = useCallback(async () => {\n if (!selected) return\n const confirmed = await confirm({\n title: 'Delete this dataset?',\n description:\n `\"${datasetDisplayName(selected)}\"` +\n // What is actually being destroyed, not what is loaded (AGL-1716):\n // a 40,000-row dataset used to warn about \"its 500 documents\".\n (recordCount\n ? ` and its ${recordCount.toLocaleString()} record${recordCount === 1 ? '' : 's'}`\n : '') +\n ' will be deleted. Repeatable components and bindings that use it ' +\n 'stop showing its data.',\n confirmationText: 'Delete',\n confirmationButtonProps: { color: 'error' },\n })\n .then(() => true)\n .catch(() => false)\n if (!confirmed || !dataScope) return\n // Deleting the dataset doc client-side would strand its `records`\n // subcollection — Firestore doesn't cascade and only the Admin SDK has\n // `recursiveDelete`, so the delete goes through the erase route\n // (AGL-945). Single-record deletes below stay client-direct.\n try {\n const response = await authorizedFetch(user, '/api/resources/erase', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n scope: dataScope[0],\n scopeId: dataScope[1],\n kind: 'datasets',\n id: selected.$id,\n // Names the site this delete was issued from, so the route can\n // refuse to destroy a dataset shared beyond it (AGL-1046). The\n // org Data page passes no host and keeps the org-wide delete.\n hostId,\n }),\n })\n const result = await response.json().catch(() => ({}))\n if (!response.ok) throw new Error(result?.error ?? 'Dataset delete failed')\n } catch (error: any) {\n return void enqueueSnackbar(error?.message ?? 'Dataset delete failed', {\n variant: 'warning',\n persist: false,\n })\n }\n openDataset(null)\n setDatasetCountEpoch((epoch) => epoch + 1)\n enqueueSnackbar('Dataset deleted', { variant: 'success', persist: false })\n logActivity('Deleted dataset', {\n type: 'content',\n id: selected.$id,\n name: datasetDisplayName(selected),\n })\n }, [\n selected,\n recordCount,\n confirm,\n dataScope,\n hostId,\n user,\n enqueueSnackbar,\n logActivity,\n openDataset,\n ])\n\n /**\n * What the selected dataset's references point at beyond this site's list\n * (AGL-4047). A dataset this site sees can name a target another site holds;\n * the schema dialog warns about exactly that, and a cell still labels the\n * row it points at, so the target has to be known even though the site's\n * list does not show it. Read one by one, and only when there is one; a\n * target the viewer may not read stays unknown.\n */\n const [outsideTargets, setOutsideTargets] = useState<any[]>(NO_DATASETS)\n useEffect(() => {\n let active = true\n const missing = railNarrowed\n ? [\n ...new Set(\n model.order\n .map((fieldId) => model.fields[fieldId]?.reference?.datasetId)\n .filter((id): id is string => Boolean(id)),\n ),\n ].filter((id) => !datasets.some((item) => item.$id === id))\n : []\n if (!missing.length || !dataScope) {\n setOutsideTargets(NO_DATASETS)\n return\n }\n void Promise.all(\n missing.map((id) =>\n getDoc(doc(firestore, dataScope[0], dataScope[1], 'datasets', id)).then(\n (snapshot) => (snapshot.exists() ? datasetRow(snapshot) : null),\n () => null,\n ),\n ),\n ).then((rows) => {\n if (active) setOutsideTargets(rows.filter(Boolean))\n })\n return () => {\n active = false\n }\n }, [railNarrowed, model, datasets, firestore, dataScope])\n const knownDatasets = useMemo(\n () => (outsideTargets.length ? [...datasets, ...outsideTargets] : datasets),\n [datasets, outsideTargets],\n )\n\n // Reference pickers (AGL-180): load target-collection rows for every\n // reference field in the model (id -> display label).\n const [refOptions, setRefOptions] = useState<\n Record<string, Array<{ id: string; label: string }>>\n >({})\n useEffect(() => {\n let active = true\n const referenceFields = model.order.filter(\n (fieldId) =>\n model.fields[fieldId]?.type === 'reference' &&\n model.fields[fieldId]?.reference?.datasetId,\n )\n if (!referenceFields.length || !dataScope) {\n setRefOptions({})\n return\n }\n void Promise.all(\n referenceFields.map(async (fieldId) => {\n const reference = model.fields[fieldId].reference as {\n datasetId: string\n displayFieldId?: string\n }\n const target = knownDatasets.find(\n (item) => item.$id === reference.datasetId,\n )\n const displayFieldId =\n reference.displayFieldId ??\n effectiveDatasetModel(target ?? {}).order[0]\n const snapshot = await getDocs(\n query(\n collection(\n firestore,\n dataScope[0],\n dataScope[1],\n 'datasets',\n reference.datasetId,\n 'records',\n ),\n limit(200),\n ),\n ).catch(() => null)\n const options = (snapshot?.docs ?? []).map((docSnapshot) => ({\n id: docSnapshot.id,\n label: String(\n docSnapshot.get('values')?.[displayFieldId ?? ''] ??\n docSnapshot.id,\n ),\n }))\n return [fieldId, options] as const\n }),\n ).then((entries) => {\n if (active) setRefOptions(Object.fromEntries(entries))\n })\n return () => {\n active = false\n }\n }, [model, knownDatasets, firestore, dataScope])\n /**\n * One reference target's label, or `null` when this ID resolves to nothing.\n *\n * The distinction the grid cannot draw. `referenceLabel` below falls back to\n * the raw ID, which is the only thing a cell has room for and is\n * indistinguishable from a resolved label that happens to look like an ID.\n * The record view has room to say which, so it asks the question that has a\n * `null` answer.\n *\n * Unresolvable covers more than a deleted target: `refOptions` loads at most\n * 200 rows per referenced collection, so a live target outside that window\n * reports the same way. Either way the ID is shown and neither is claimed to\n * be a working link.\n */\n const resolveReferenceLabel = useCallback(\n (fieldId: string, id: string): string | null =>\n refOptions[fieldId]?.find((option) => option.id === id)?.label ?? null,\n [refOptions],\n )\n const referenceLabel = useCallback(\n (fieldId: string, value: unknown): string => {\n const ids = Array.isArray(value) ? value : value != null ? [value] : []\n return ids\n .map((id) => resolveReferenceLabel(fieldId, String(id)) ?? String(id))\n .join(', ')\n },\n [resolveReferenceLabel],\n )\n /**\n * The record the viewer is showing, held as an ID and resolved against the\n * page the table already has.\n *\n * Holding the ID rather than the row is what keeps the view live without\n * costing a read: the same listener that draws the table re-resolves it, so\n * an edit landing underneath updates the open dialog. When the row leaves\n * the page — deleted, or paged past — this answers `null` and the dialog\n * closes, which is the honest response to a record no longer in front of\n * this reader. Nothing here queries: `records` is the page (or filter window)\n * query's answer.\n */\n const [viewerId, setViewerId] = useState<string | null>(null)\n /**\n * Opens a record (AGL-4047): on its own page beneath the dataset's tab\n * where the Data page is routed, in the View record dialog elsewhere.\n */\n const datasetHref = basePath && selected?.$id ? `${basePath}/${selected.$id}` : null\n const openRecord = useCallback(\n (id: string) => {\n if (datasetHref) router.push(`${datasetHref}/records/${encodeURIComponent(id)}`)\n else setViewerId(id)\n },\n [datasetHref, router],\n )\n const viewerRecord = useMemo(\n () =>\n viewerId\n ? (records.find((record: any) => record.$id === viewerId) ?? null)\n : null,\n [viewerId, records],\n )\n\n // --- Document editor (null id = new; AGL-179 typed inputs) --------------\n const [editor, setEditor] = useState<{\n id: string | null\n values: Record<string, string>\n errors: Record<string, string>\n /** A sample a site start seeded (AGL-4065): saving it makes it the owner's. */\n sample?: boolean\n } | null>(null)\n const handleOpenRecord = useCallback(\n (record?: any) => () => {\n if (!record) {\n // The dataset's documents, not the loaded window (AGL-1716).\n const quota = checkQuota(org, 'recordsPerDataset', recordCount)\n if (!quota.allowed) {\n return enqueueSnackbar(\n `Record limit reached (${quota.limit}) — see Billing to upgrade`,\n { variant: 'warning', persist: false },\n )\n }\n }\n const values: Record<string, string> = {}\n for (const fieldId of model.order) {\n const field = model.fields[fieldId]\n if (!field) continue\n if (record) {\n values[fieldId] = datasetValueToInput(\n field,\n record.values?.[fieldId],\n )\n } else if (field.default != null) {\n values[fieldId] = String(field.default)\n }\n }\n // Flag non-conforming stored values (AGL-178 policy: type changes\n // never rewrite documents; the editor surfaces the mismatch).\n const errors = record\n ? validateDocument(model, record.values ?? {})\n : {}\n setEditor({ id: record?.$id ?? null, values, errors, ...(isSampleDatasetRecord(record) ? { sample: true } : {}) })\n },\n [org, recordCount, model, enqueueSnackbar],\n )\n const handleSaveRecord = useCallback(async () => {\n if (!editor || !selected || !dataScope) return\n // The editor holds the record's WHOLE values, so an address it already\n // has stays and an empty one fills in from its source (AGL-3475).\n const coerced = fillRecordAddresses(\n model,\n coerceDocumentValues(model, editor.values),\n )\n const errors = validateDocument(model, coerced)\n if (Object.keys(errors).length) {\n return void setEditor((prev) => (prev ? { ...prev, errors } : prev))\n }\n // `values` is replaced wholesale (not merged) so orphaned values from\n // removed fields strip here, lazily, per the documented AGL-178 policy.\n try {\n if (editor.id) {\n // Updates stay client-direct (no quota consumed).\n const recordRef = doc(\n firestore,\n dataScope[0],\n dataScope[1],\n 'datasets',\n selected.$id,\n 'records',\n editor.id,\n )\n await setDoc(\n recordRef,\n {\n values: coerced,\n // The integrity index moves with the values it describes\n // (`datasetIntegrityUpdate`); the merging form, because clearing\n // the last reference has to REMOVE the field rather than omit it.\n ...datasetIntegrityUpdate(model, coerced, deleteField()),\n // A sample saved is the owner's row now (AGL-4065).\n ...(editor.sample ? { sample: deleteField() } : {}),\n updatedAt: Timestamp.now(),\n },\n {\n mergeFields: [\n 'values',\n 'referencedIds',\n 'filterKeys',\n 'filterValues',\n 'updatedAt',\n ...(editor.sample ? ['sample'] : []),\n ],\n },\n )\n await announceRecords(selected.$id)\n } else {\n // Creates go through the quota-enforcing API (AGL-473). The legacy\n // host-scope client write that used to follow this branch is gone\n // (AGL-1050): a non-null `dataScope` is an org scope, so `orgId` is\n // set and there is no third case to fall into.\n await callDatasetApi({\n action: 'create-record',\n datasetId: selected.$id,\n values: coerced,\n })\n }\n } catch (error: any) {\n return void enqueueSnackbar(error?.message ?? 'Record save failed', {\n variant: 'warning',\n persist: false,\n })\n }\n setEditor(null)\n // A create moves the count; an update cannot. Same reason as the\n // importer: the one-shot aggregate does not refresh itself.\n if (!editor.id) setRecordCountEpoch((epoch) => epoch + 1)\n enqueueSnackbar(editor.id ? 'Record saved' : 'Record added', {\n variant: 'success',\n persist: false,\n })\n logActivity(editor.id ? 'Updated record' : 'Added record', {\n type: 'content',\n id: selected.$id,\n name: datasetDisplayName(selected),\n })\n }, [\n editor,\n selected,\n firestore,\n dataScope,\n model,\n callDatasetApi,\n announceRecords,\n enqueueSnackbar,\n logActivity,\n ])\n const handleDeleteRecord = useCallback(\n (record: any, afterDelete?: () => void) => async () => {\n // Datasets whose records this delete rewrites through a reference\n // fixup, beside the one the record belongs to. Each has pages of its\n // own to refresh (AGL-3113).\n const alsoChanged = new Set<string>()\n if (!selected || !dataScope) return\n /**\n * Delete integrity (AGL-180): every collection whose model references\n * this one is asked whether it still points at this record. `restrict`\n * blocks the delete; `setNull` strips the FKey from the holders.\n *\n * The question is a QUERY over the denormalized `referencedIds` index,\n * not a page of records filtered in the browser. A page answers for the\n * rows it happened to fetch — an unordered `limit` is answered in\n * document-id order over auto-ids, so it is an arbitrary sample — and a\n * reference held by a row outside it reads as no reference at all: the\n * delete goes through and `restrict` silently fails to restrict, leaving\n * a document pointing at something that no longer exists. `values`\n * itself cannot be queried (it carries a deliberate index exemption —\n * see `datasetIntegrityFields`), which is why the index exists.\n *\n * The query narrows to the candidates; the per-field test below keeps it\n * EXACT, since `referencedIds` is the union across every reference field\n * and one of them may point at a different collection entirely.\n *\n * ⚠️ FAILS CLOSED. A query that rejects — a missing index, a rules\n * refusal on a collection this member cannot read — refuses the delete\n * rather than treating silence as \"nothing references it\". A check that\n * fails open is worse than no check, because the UI then tells the user\n * the record is safe to remove.\n *\n * ⚠️ Reaches the collections in this viewer's scoped, capped window. A\n * referencing collection shared with no site this member can see is one\n * the client may not read at all, so it is not consulted; only a server\n * route could close that.\n *\n * On a site's Data page that window is NOT the list (AGL-4047). The list\n * is the site's, and a dataset another site holds can reference a row of\n * one shared with both: narrowing what the page shows must not narrow\n * what a delete protects. So the page reads the viewer's reach here, once,\n * at the moment of the delete, and refuses if it cannot.\n */\n let referencing: any[] = datasets\n if (railNarrowed) {\n try {\n const reach = await getDocs(\n query(\n collection(firestore, dataScope[0], dataScope[1], 'datasets'),\n ...(reachScope\n ? [where('visibleTo', 'array-contains-any', [...reachScope])]\n : []),\n limit(DATASET_LIST_WINDOW),\n ),\n )\n referencing = reach.docs.map(datasetRow)\n } catch {\n return void enqueueSnackbar(\n 'Cannot delete: the datasets that may reference this record could ' +\n 'not be checked, so removing it could break them. Nothing was ' +\n 'deleted.',\n { variant: 'error' },\n )\n }\n }\n for (const other of referencing) {\n const otherModel = effectiveDatasetModel(other)\n if (!referencingFieldIds(otherModel, selected.$id).length) continue\n let snapshot\n try {\n snapshot = await getDocs(\n query(\n collection(\n firestore,\n dataScope[0],\n dataScope[1],\n 'datasets',\n other.$id,\n 'records',\n ),\n where('referencedIds', 'array-contains', record.$id),\n ),\n )\n } catch {\n return void enqueueSnackbar(\n `Cannot delete: \"${datasetDisplayName(other)}\" could not be checked for ` +\n 'references, so removing this record could break it. Nothing ' +\n 'was deleted.',\n { variant: 'error' },\n )\n }\n // The verdict is shared with `/api/orgs/datasets` `delete-record`\n // (`planReferenceFixups`): the per-field test keeps the query EXACT,\n // since `referencedIds` is the union across every reference field.\n const plan = planReferenceFixups(\n otherModel,\n selected.$id,\n record.$id,\n snapshot.docs.map((docSnapshot) => ({ id: docSnapshot.id, values: docSnapshot.get('values') })),\n )\n if (plan.kind === 'none') continue\n if (plan.kind === 'restricted') {\n return void enqueueSnackbar(\n restrictedDeleteMessage(plan.holders, datasetDisplayName(other)),\n { variant: 'warning', persist: false },\n )\n }\n // Chunked under Firestore's 500-writes-per-batch cap. The query is no\n // longer bounded by a page size, so the number of holders is whatever\n // the collection really holds.\n for (let start = 0; start < plan.updates.length; start += 400) {\n const batch = writeBatch(firestore)\n for (const update of plan.updates.slice(start, start + 400)) {\n const holder = snapshot.docs.find((docSnapshot) => docSnapshot.id === update.id)\n if (!holder) continue\n batch.update(holder.ref, {\n values: update.values,\n ...datasetIntegrityUpdate(otherModel, update.values, deleteField()),\n })\n }\n await batch.commit()\n }\n // The fixups rewrote rows in ANOTHER dataset, whose own pages are now\n // showing a reference that no longer resolves.\n alsoChanged.add(other.$id)\n }\n await deleteDoc(\n doc(\n firestore,\n dataScope[0],\n dataScope[1],\n 'datasets',\n selected.$id,\n 'records',\n record.$id,\n ),\n )\n setRecordCountEpoch((epoch) => epoch + 1)\n for (const datasetId of [selected.$id, ...alsoChanged]) {\n await announceRecords(datasetId)\n }\n enqueueSnackbar('Record deleted', { variant: 'success', persist: false })\n afterDelete?.()\n },\n [\n selected,\n datasets,\n railNarrowed,\n reachScope,\n firestore,\n dataScope,\n announceRecords,\n enqueueSnackbar,\n ],\n )\n\n /**\n * Import and export (AGL-3530) open the console's import wizard and export\n * dialog on this dataset (`data.dataset:<datasetId>`): the file is read,\n * matched and written on the server, through the same record writes as\n * every other create and update, and the export streams the fields the\n * person picks. Outside the console shell there is no launcher, and no\n * Import or Export to offer. Inside it, Import is on for a member who may\n * write this dataset and switched off with the permission named for one who\n * may not, and Export likewise for \"Export data\", for a member who can see it\n * (AGL-3546, AGL-4047) — the transfer routes' own rule.\n */\n const transfer = useTransferLauncher()\n const transferTarget = selected?.$id\n ? {\n resource: datasetTransferResourceKey(selected.$id),\n scope: 'org' as const,\n // This dataset's own answer once it is known; the workspace's until then.\n ...(blocked.known ? { importAllowed: !blocked.writes } : {}),\n }\n : null\n const canImport = Boolean(transfer && transferTarget && transfer.can('import', transferTarget))\n const canExport = Boolean(transfer && transferTarget && transfer.can('export', transferTarget))\n const handleImport = useCallback(() => {\n if (!transfer || !selected?.$id) return\n const dataset = { id: selected.$id, name: datasetDisplayName(selected) }\n transfer.openImport({\n resource: datasetTransferResourceKey(dataset.id),\n scope: 'org',\n title: dataset.name ? `Import into ${dataset.name}` : 'Import records',\n onFinished: () => {\n // An import moves the record count, and the aggregate is a one-shot.\n setRecordCountEpoch((epoch) => epoch + 1)\n logActivity('Imported records', { type: 'content', id: dataset.id, name: dataset.name })\n },\n })\n }, [transfer, selected, logActivity])\n const handleExport = useCallback(() => {\n if (!transfer || !selected?.$id) return\n const name = datasetDisplayName(selected)\n transfer.openExport({\n resource: datasetTransferResourceKey(selected.$id),\n scope: 'org',\n title: name ? `Export ${name}` : 'Export records',\n // The table's own query, re-planned on the server the way the table\n // plans it, so \"the current filter\" exports what the table shows.\n ...(filteringRecords\n ? {\n filter: {\n label: 'The records the table’s filters and search show',\n value: { clauses: recordClauses, search: gridFilter.searchWords },\n },\n }\n : {}),\n })\n }, [transfer, selected, filteringRecords, recordClauses, gridFilter.searchWords])\n\n /*\n * One column per schema field, filterable as far as `datasetRecordFilter`\n * declares it. The row OPENS the record, read-only (`onOpen`); the actions\n * column holds the keyboard's way in (`View`, a real button) beside Edit\n * and Delete, and a press anywhere in it never opens the row.\n */\n const recordGridColumns = useMemo(\n () =>\n listFilterGridColumns(\n [\n ...fields.map((fieldId, column) => {\n const field = model.fields[fieldId]\n const isIcon = field?.customType === DATASET_ICON_FIELD_TYPE\n const shown = (row: any) =>\n field?.type === 'reference'\n ? referenceLabel(fieldId, row.values?.[fieldId]) || '--'\n : isIcon\n ? // A record's icon (AGL-4190) is drawn, with its name, never its stored map.\n readDatasetIconValue(row.values?.[fieldId])\n ? <DatasetIconPreview value={row.values?.[fieldId]} />\n : '--'\n : field\n ? formatDatasetValue(field, row.values?.[fieldId]) || '--'\n : '--'\n return {\n field: recordColumn(fieldId),\n headerName: field?.name ?? fieldId,\n // Field descriptions (AGL-560) surface as header hints.\n description: field?.description,\n flex: 1,\n minWidth: 140,\n renderCell: ({ row }: { row: any }) =>\n // A sample a site start seeded says so beside its first value (AGL-4065).\n column === 0 && isSampleDatasetRecord(row) ? (\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center', height: '100%', minWidth: 0 }}>\n <Typography variant=\"body2\" noWrap>\n {shown(row)}\n </Typography>\n <Tooltip title={DATASET_SAMPLE_RECORD_NOTE}>\n <Chip label=\"Sample\" size=\"small\" variant=\"outlined\" color=\"info\" />\n </Tooltip>\n </Stack>\n ) : (\n shown(row)\n ),\n }\n }),\n listActionsColumn(\n (record: any) => (\n <Stack\n direction=\"row\"\n sx={{ height: '100%', alignItems: 'center', justifyContent: 'flex-end' }}\n >\n <Button size=\"small\" onClick={() => openRecord(record.$id)}>\n {'View'}\n </Button>\n <BlockedControl blocked={blocked.writes} reason={blocked.writesReason}>\n <Button size=\"small\" onClick={handleOpenRecord(record)}>\n {'Edit'}\n </Button>\n </BlockedControl>\n <BlockedControl blocked={blocked.writes} reason={blocked.writesReason}>\n <Button\n size=\"small\"\n color=\"error\"\n onClick={handleDeleteRecord(record)}\n >\n {'Delete'}\n </Button>\n </BlockedControl>\n </Stack>\n ),\n { width: 220 },\n ),\n ] as Parameters<typeof listFilterGridColumns>[0],\n recordFilter.fields,\n recordFilter.options,\n recordFilter.headers,\n ),\n [\n fields,\n model,\n referenceLabel,\n handleOpenRecord,\n handleDeleteRecord,\n openRecord,\n recordFilter,\n blocked.writes,\n blocked.writesReason,\n ],\n )\n\n /*\n * EVERY HEADER SORTS — THE PAGE ON SCREEN (AGL-3680). A record's values are\n * per-schema and no field is on every record (see the walk above), so no\n * query can order by one; each value column sorts the loaded page by what\n * it shows (a reference by its label, a number or switch by its value) and\n * the notice says it is this page only.\n */\n const recordPageSorts = useMemo(\n () =>\n Object.fromEntries(\n fields.map((fieldId) => {\n const field = model.fields[fieldId]\n return [\n recordColumn(fieldId),\n (row: any) => {\n const value = row.values?.[fieldId]\n if (field?.type === 'reference') return referenceLabel(fieldId, value) || null\n if (typeof value === 'number' || typeof value === 'boolean') return value\n return field ? formatDatasetValue(field, value) || null : null\n },\n ]\n }),\n ),\n [fields, model, referenceLabel],\n )\n const recordSortHeaders = useMemo(\n () =>\n Object.fromEntries(\n fields.map((fieldId) => [recordColumn(fieldId), model.fields[fieldId]?.name ?? fieldId]),\n ),\n [fields, model],\n )\n const recordColumnSort = useListColumnSort<any>({\n sorts: NO_QUERY_SORTS,\n rows: records,\n pageSorts: recordPageSorts,\n headers: recordSortHeaders,\n })\n\n /**\n * The rail (AGL-4047): one tab per dataset, at the dataset's own address,\n * with a second line that tells two of one name apart. Past\n * {@link DATASET_RAIL_GROUP_AT} the tabs are grouped by who they are shared\n * with, and the organization page offers the Shared with filter.\n */\n const grouped = datasets.length > DATASET_RAIL_GROUP_AT\n const railSections = useMemo<HubSection[]>(() => {\n if (!basePath) return []\n const tab = (item: DatasetRailEntry, group?: string): HubSection => ({\n href: `${basePath}/${item.$id}`,\n label: datasetRailName(item),\n secondary: datasetRailSecondary(item, { hostNames, grouped }),\n ...(group ? { group } : {}),\n })\n if (!grouped) return datasets.map((item: DatasetRailEntry) => tab(item))\n return groupDatasetsBySharing(datasets, hostNames).flatMap((group) =>\n group.datasets.map((item) => tab(item, group.label)),\n )\n }, [basePath, datasets, hostNames, grouped])\n /** The join dialog's names, told apart where two match (AGL-4047). */\n const joinLabels = useMemo(() => datasetPickerLabelsOf(datasets, hostNames), [datasets, hostNames])\n const offerSharedWith =\n !pageHostId && orgSites.length > 1 && (datasets.length > DATASET_RAIL_GROUP_AT || Boolean(sharedWith))\n const sitesByName = useMemo(\n () => [...orgSites].sort((a, b) => (hostNames[a.$id] ?? '').localeCompare(hostNames[b.$id] ?? '')),\n [orgSites, hostNames],\n )\n const railHeader =\n datasets.length || nameSearch || sharedWith ? (\n <Stack spacing={1.5} sx={{ mb: 1 }}>\n <TextField\n size=\"small\"\n fullWidth\n placeholder=\"Search datasets by name\"\n value={nameSearch}\n onChange={(event) => setNameSearch(event.target.value)}\n slotProps={{ htmlInput: { 'aria-label': 'Search datasets by name' } }}\n />\n {offerSharedWith ? (\n <TextField\n select\n size=\"small\"\n fullWidth\n label=\"Shared with\"\n value={sharedWith}\n onChange={(event) => {\n setSharedWith(event.target.value)\n setRailWindow(DATASET_LIST_WINDOW)\n }}\n >\n <MenuItem value=\"\">{'Any site'}</MenuItem>\n {sitesByName.map((site) => (\n <MenuItem key={site.$id} value={site.$id}>\n {hostNames[site.$id]}\n </MenuItem>\n ))}\n </TextField>\n ) : null}\n </Stack>\n ) : null\n const railFooter = (\n <>\n {/*\n The Datasets card's own loading state (AGL-4047), the same rule as the\n panel beside it: while the list has nothing to show and the server has\n not answered, the card says it is loading instead of sitting blank.\n Rows the cache already holds show at once, and an answer that is\n empty, or refused, leaves the panel to say so.\n */}\n {!listConfirmed && !listUnreadable && datasets.length === 0 ? (\n <Box sx={{ px: 2, py: 1 }}>\n <CircularProgress size={24} aria-label=\"Loading the dataset list\" />\n </Box>\n ) : null}\n {listConfirmed && serverNameKey && datasets.length === 0 ? (\n <Typography variant=\"body2\" color=\"text.secondary\" sx={{ px: 2, py: 1 }}>\n {'No datasets match.'}\n </Typography>\n ) : null}\n {moreDatasets ? (\n <Button size=\"small\" sx={{ mt: 1 }} onClick={() => setRailWindow((window) => window + DATASET_LIST_WINDOW)}>\n {'Show more datasets'}\n </Button>\n ) : null}\n </>\n )\n\n /** The open dataset's facts, under its name. */\n const facts: Array<[string, string]> = selected\n ? [\n ['Shared with', datasetSharingLabel(selected, hostNames)],\n ['Fields', String(fields.length)],\n ['Records', blocked.records ? '--' : recordCount.toLocaleString()],\n ['Source', datasetSourceLabel(selected)],\n ['Created', datasetCreatedLabel(selected)],\n ]\n : []\n\n /** Label-over-value facts, under a heading. */\n const factsRow = (pairs: Array<[string, string]>) => (\n <Stack direction=\"row\" spacing={3} useFlexGap sx={{ flexWrap: 'wrap', mt: 1 }}>\n {pairs.map(([label, value]) => (\n <Box key={label}>\n <Typography variant=\"caption\" color=\"text.secondary\" component=\"div\">\n {label}\n </Typography>\n <Typography variant=\"body2\" color=\"text.primary\" component=\"div\" sx={{ overflowWrap: 'anywhere' }}>\n {value}\n </Typography>\n </Box>\n ))}\n </Stack>\n )\n\n /**\n * A record's own page (AGL-4047): back to its dataset, its fields, and\n * today's record actions with today's gates. It takes the place of the View\n * record dialog where the Data page is routed.\n */\n const recordTitle = routeRecord ? datasetRecordTitle(model, routeRecord.values) : undefined\n const recordPanel =\n selected && routeRecordId ? (\n <CardDisplay\n help={pluginDocsHelp('datasets', { anchor: '#organization-data-page' })}\n header={\n <Stack spacing={1} sx={{ alignItems: 'flex-start' }}>\n {datasetHref ? (\n <Button\n size=\"small\"\n component={AppLink}\n href={datasetHref}\n startIcon={<MdiIcon path={mdiArrowLeft.path} size={0.8} />}\n >\n {datasetRailName(selected)}\n </Button>\n ) : null}\n {recordTitle ? <span>{recordTitle}</span> : null}\n </Stack>\n }\n contentGutterX\n contentGutterY\n contentBordered=\"top\"\n HeaderProps={{\n action: routeRecord ? (\n <Stack direction=\"row\" spacing={1} useFlexGap sx={{ alignItems: 'center', flexWrap: 'wrap', justifyContent: 'flex-end' }}>\n <BlockedControl blocked={blocked.writes} reason={blocked.writesReason}>\n <Button size=\"small\" onClick={handleOpenRecord(routeRecord)}>\n {'Edit record'}\n </Button>\n </BlockedControl>\n <BlockedControl blocked={blocked.writes} reason={blocked.writesReason}>\n <Button\n size=\"small\"\n color=\"error\"\n onClick={handleDeleteRecord(routeRecord, () => {\n if (datasetHref) router.push(datasetHref)\n })}\n >\n {'Delete'}\n </Button>\n </BlockedControl>\n </Stack>\n ) : undefined,\n subheader: factsRow([\n ['Record ID', routeRecordId],\n ['Dataset', `${datasetRailName(selected)} · ${datasetSharingLabel(selected, hostNames)}`],\n ]),\n }}\n >\n <Stack spacing={1.5}>\n {blocked.records ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {DATASETS_VIEW_RECORDS_REFUSAL}\n </Typography>\n ) : routeRecordMissing ? (\n <Alert severity=\"info\">{'This record doesn’t exist, or you can’t open it.'}</Alert>\n ) : routeRecord ? (\n <DatasetRecordFieldList\n record={routeRecord}\n model={model}\n resolveReference={resolveReferenceLabel}\n divided\n />\n ) : null}\n </Stack>\n </CardDisplay>\n ) : null\n\n const panel = notSharedHere ? (\n <Alert severity=\"info\">{'This dataset isn’t shared with this site.'}</Alert>\n ) : notFound ? (\n <Alert severity=\"info\">{'This dataset doesn’t exist, or you can’t open it.'}</Alert>\n ) : recordPanel ? (\n recordPanel\n ) : !selected ? (\n listUnreadable && !wantedId ? (\n <Alert severity=\"error\">\n {'We couldn’t load your datasets. This does not mean there are none.'}\n </Alert>\n ) : !listConfirmed || wantedId ? (\n // Until the server answers, and while the dataset the address names is\n // read on its own: never the empty state, which is a verdict.\n <CardDisplay contentGutterX contentGutterY>\n <CircularProgress size={24} aria-label=\"Loading datasets\" />\n </CardDisplay>\n ) : datasets.length === 0 && !sharedWith && !serverNameKey ? (\n <CardDisplay contentGutterX contentGutterY>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Create a dataset, like Products, then add a repeating section ' +\n 'to any page to show one item per record.'}\n </Typography>\n </CardDisplay>\n ) : null\n ) : (\n <CardDisplay\n header={datasetRailName(selected)}\n help={pluginDocsHelp('datasets', { anchor: '#filter-records' })}\n contentGutterX\n contentGutterY\n contentBordered=\"top\"\n HeaderProps={{\n action: (\n <Stack\n direction=\"row\"\n spacing={1}\n useFlexGap\n sx={{ alignItems: 'center', flexWrap: 'wrap', justifyContent: 'flex-end' }}\n >\n <BlockedControl blocked={blocked.writes} reason={blocked.writesReason}>\n <Button\n size=\"small\"\n color=\"primary\"\n onClick={handleOpenRecord()}\n >\n {'Add record'}\n </Button>\n </BlockedControl>\n <BlockedControl blocked={blocked.writes && !blocked.sharingOnly} reason={blocked.writesReason}>\n <Button size=\"small\" onClick={() => setSchemaOpen(true)}>\n {'Schema'}\n </Button>\n </BlockedControl>\n {/* An import left unfinished, reopened where it stopped (AGL-3549). */}\n {transferTarget ? (\n <TransferResumeImport\n target={transferTarget}\n {...(selected ? { title: `Import into ${datasetDisplayName(selected)}` } : {})}\n onFinished={() => setRecordCountEpoch((epoch) => epoch + 1)}\n />\n ) : null}\n {/* Off with the permission named for a member known not to hold it,\n not hidden. Still absent while the answer is out, and where the\n launcher refuses for another reason than the key. */}\n {canImport || (transfer && transferTarget && blocked.writes) ? (\n <BlockedControl blocked={!canImport} reason={blocked.writesReason}>\n <Button size=\"small\" onClick={handleImport}>\n {'Import'}\n </Button>\n </BlockedControl>\n ) : null}\n {/* The real dataset size, not the loaded window (AGL-2335) —\n the export is a server stream, so a dataset whose first page\n has not landed yet is still exportable. */}\n {(canExport && (recordCount || records.length)) || (transfer && blocked.exports) ? (\n <BlockedControl blocked={blocked.exports} reason={DATASETS_EXPORT_REFUSAL}>\n <Button size=\"small\" onClick={handleExport}>\n {'Export'}\n </Button>\n </BlockedControl>\n ) : null}\n <BlockedControl blocked={blocked.deletes} reason={blocked.deletesReason}>\n <Button size=\"small\" color=\"error\" onClick={handleDeleteDataset}>\n {'Delete'}\n </Button>\n </BlockedControl>\n </Stack>\n ),\n subheader: factsRow(facts),\n }}\n >\n <Stack spacing={1.5}>\n {/* The per-dataset record cap, standing rather than only on refusal\n (AGL-2113). `recordCount` is the dataset's real size — the same\n number `handleOpenRecord` and the importer hand to `checkQuota`,\n not the loaded window (AGL-1716). */}\n {selected ? (\n <QuotaReadoutComponent\n ready={org != null}\n used={recordCount}\n limit={checkQuota(org, 'recordsPerDataset', recordCount).limit}\n noun=\"record\"\n />\n ) : null}\n {selected && blocked.records ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {DATASETS_VIEW_RECORDS_REFUSAL}\n </Typography>\n ) : selected && (records.length > 0 || recordPage > 0 || filteringRecords) ? (\n <>\n <ListFilterChips\n fields={recordFilter.fields}\n headers={recordFilter.headers}\n clauses={recordClauses}\n onChange={gridFilter.setClauses}\n options={recordFilter.options}\n />\n <ListQueryNotices\n refused={recordRefusals}\n notices={[...recordPlan.notices, ...recordColumnSort.notices]}\n />\n <ListTable\n aria-label=\"Records\"\n // Edit and Delete stay in reach when the columns scroll sideways\n // in the panel beside the rail (AGL-4047).\n pinActions\n rows={recordColumnSort.rows}\n columnSort={recordColumnSort}\n columns={recordGridColumns}\n onOpen={(id) => openRecord(id)}\n // One page of the walk, turned by the footer below: the grid\n // neither slices nor filters it.\n hideFooter\n filterMode=\"server\"\n filterModel={gridFilter.filterModel}\n onFilterModelChange={gridFilter.onFilterModelChange}\n quickFilter\n {...(blocked.exports ? { slotProps: EXPORT_OFF_TOOLBAR } : {})}\n noRowsLabel={\n filteringRecords ? 'No records match these filters' : 'No records yet.'\n }\n />\n {/* The count line is the PAGE's, deliberately. `recordCount` is the\n dataset's real size and it already has its own readout above —\n handing it to the footer as `count` would tell MUI the walk is\n that long and leave Next live past the end of it whenever a rule,\n a scope or a filter has narrowed what this reader may list.\n `hasMore` is a fact from the probe row, so the footer answers\n for what it is actually paging. */}\n <ListPagination\n page={recordPage}\n pageSize={recordPageSize}\n rowCount={records.length}\n hasMore={hasMoreRecords}\n onPageChange={setRecordPage}\n onPageSizeChange={setRecordPageSize}\n />\n </>\n ) : selected ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'No records yet.'}\n </Typography>\n ) : null}\n </Stack>\n </CardDisplay>\n )\n\n return (\n <>\n {/* The page's own actions, in the page header beside its title. */}\n <PageHeaderActions>\n <Stack direction=\"row\" spacing={1} useFlexGap sx={{ flexWrap: 'wrap' }}>\n <BlockedControl blocked={blocked.creates} reason={DATASETS_WRITE_REFUSAL}>\n <Button variant=\"outlined\" color=\"primary\" onClick={handleOpenCreator}>\n {'Add dataset'}\n </Button>\n </BlockedControl>\n {datasets.length >= 2 ? (\n <BlockedControl blocked={blocked.creates} reason={DATASETS_WRITE_REFUSAL}>\n <Button onClick={() => setJoiner({ a: '', b: '' })}>{'Add join collection'}</Button>\n </BlockedControl>\n ) : null}\n </Stack>\n </PageHeaderActions>\n {/* The open dataset ends the trail; the heading stays the page's. */}\n {/* On a record's page the trail runs dataset, linked, then record. */}\n {routeRecordId && selected && datasetHref ? (\n <PageHeaderRecord\n title={recordTitle}\n keepHeading\n parentTitle={datasetRailName(selected)}\n parentHref={datasetHref}\n />\n ) : (\n <PageHeaderRecord title={selected && routeDatasetId ? datasetRailName(selected) : undefined} keepHeading />\n )}\n <HubSections\n sections={railSections}\n navHeader=\"Datasets\"\n railHeader={railHeader}\n railFooter={railFooter}\n scrollRail\n >\n {panel}\n </HubSections>\n <Dialog\n open={Boolean(creator)}\n onClose={() => setCreator(null)}\n maxWidth=\"xs\"\n fullWidth\n >\n <DialogTitle>{'New dataset'}</DialogTitle>\n <DialogContent\n sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}\n >\n {orgId ? (\n <Typography variant=\"body2\" color=\"text.secondary\" sx={{ mt: 1 }}>\n {/* Ownership and visibility are separate facts (AGL-1044), and\n what a new dataset starts on depends on where it is made. */}\n {newDatasetSharingNote(createsSiteOnly)}\n </Typography>\n ) : null}\n <TextField\n label=\"Name\"\n value={creator?.name ?? ''}\n onChange={(event) =>\n setCreator((prev) =>\n prev ? { ...prev, name: event.target.value } : prev,\n )\n }\n size=\"small\"\n autoFocus\n sx={{ mt: 1 }}\n helperText=\"e.g. Products, Team, FAQ\"\n />\n <TextField\n label=\"Fields\"\n value={creator?.fields ?? ''}\n onChange={(event) =>\n setCreator((prev) =>\n prev ? { ...prev, fields: event.target.value } : prev,\n )\n }\n size=\"small\"\n helperText={\n creatorEntries.length\n ? `Columns: ${creatorEntries\n .map((entry) => entry.name)\n .join(', ')}`\n : 'Comma-separated column names, e.g. Title, Unit price'\n }\n />\n </DialogContent>\n <DialogActions>\n <Button onClick={() => setCreator(null)}>{'Cancel'}</Button>\n <Button\n variant=\"contained\"\n color=\"primary\"\n disabled={\n !scopeReady ||\n !creator?.name.trim() ||\n creatorFields.length === 0\n }\n onClick={handleCreate}\n >\n {'Create'}\n </Button>\n </DialogActions>\n </Dialog>\n {/*\n ONE viewer for the table, not one per row. Its record is a prop out of\n the page already in hand, so opening it reads nothing — and mounting\n the table does not open a dialog per row to discover that.\n */}\n <DatasetRecordDialog\n record={viewerRecord}\n model={model}\n resolveReference={resolveReferenceLabel}\n onClose={() => setViewerId(null)}\n // Explicitly separate, and a hand-off rather than a second editor:\n // the viewer closes and the record opens in the dialog that has\n // always owned writing.\n onEdit={() => {\n const record = viewerRecord\n setViewerId(null)\n if (record) handleOpenRecord(record)()\n }}\n />\n <Dialog\n open={Boolean(editor)}\n onClose={() => setEditor(null)}\n maxWidth=\"xs\"\n fullWidth\n >\n <DialogTitle>{editor?.id ? 'Edit record' : 'New record'}</DialogTitle>\n <DialogContent\n sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}\n >\n {editor?.sample ? <Alert severity=\"info\">{DATASET_SAMPLE_RECORD_NOTE}</Alert> : null}\n <DatasetRecordSiteContext.Provider value={recordSite}>\n {fields.map((fieldId, index) => {\n const field = model.fields[fieldId]\n if (!field) return null\n const value = editor?.values[fieldId] ?? ''\n const error = editor?.errors[fieldId]\n const label = field.required ? `${field.name} *` : field.name\n const setValue = (nextValue: string) =>\n setEditor((prev) =>\n prev\n ? {\n ...prev,\n values: { ...prev.values, [fieldId]: nextValue },\n errors: { ...prev.errors, [fieldId]: '' },\n }\n : prev,\n )\n const common = {\n label,\n value,\n size: 'small' as const,\n autoFocus: index === 0,\n error: Boolean(error),\n helperText: error || field.description,\n sx: index === 0 ? { mt: 1 } : undefined,\n onChange: (event: { target: { value: string } }) =>\n setValue(event.target.value),\n }\n // Custom field types (AGL-434): the declaring plugin's Input\n // takes over; values stay in input form (strings) so the\n // existing coerce/validate pipeline is unchanged.\n const customFieldType = getCustomFieldType(field.customType)\n if (customFieldType?.Input) {\n const CustomInput = customFieldType.Input\n return (\n <Stack key={fieldId} sx={index === 0 ? { mt: 1 } : undefined}>\n <CustomInput\n value={value}\n label={common.label}\n onChange={(next) => setValue(String(next ?? ''))}\n />\n {(error || field.description) ? (\n <Typography\n variant=\"caption\"\n color={error ? 'error' : 'text.secondary'}\n >\n {error || field.description}\n </Typography>\n ) : null}\n </Stack>\n )\n }\n // Typed inputs per FT.Tag (AGL-179).\n if (field.type === 'bool') {\n return (\n <TextField key={fieldId} {...common} select>\n <MenuItem value=\"\">{'—'}</MenuItem>\n <MenuItem value=\"true\">{'Yes'}</MenuItem>\n <MenuItem value=\"false\">{'No'}</MenuItem>\n </TextField>\n )\n }\n if (field.type === 'text' && field.validation?.options?.length) {\n return (\n <TextField key={fieldId} {...common} select>\n <MenuItem value=\"\">{'—'}</MenuItem>\n {field.validation.options.map((option) => (\n <MenuItem key={option} value={option}>\n {option}\n </MenuItem>\n ))}\n </TextField>\n )\n }\n if (field.type === 'reference') {\n const options = refOptions[fieldId] ?? []\n const multiple = Boolean(field.reference?.multiple)\n const selectedIds = value\n .split(',')\n .map((part) => part.trim())\n .filter(Boolean)\n return (\n <TextField\n key={fieldId}\n {...common}\n select\n value={multiple ? selectedIds : value}\n slotProps={{\n select: multiple\n ? {\n multiple: true,\n onChange: (event: any) =>\n setValue(\n (event.target.value as string[]).join(', '),\n ),\n }\n : undefined,\n }}\n >\n {multiple ? null : <MenuItem value=\"\">{'—'}</MenuItem>}\n {options.map((option) => (\n <MenuItem key={option.id} value={option.id}>\n {option.label}\n </MenuItem>\n ))}\n </TextField>\n )\n }\n if (\n field.type === 'int32' ||\n field.type === 'int64' ||\n field.type === 'float'\n ) {\n return <TextField key={fieldId} {...common} type=\"number\" />\n }\n if (field.type === 'timestamp') {\n return (\n <TextField\n key={fieldId}\n {...common}\n type=\"datetime-local\"\n slotProps={{ inputLabel: { shrink: true } }}\n />\n )\n }\n if (field.type === 'coordinates') {\n return (\n <TextField\n key={fieldId}\n {...common}\n helperText={error || field.description || 'lat, lon'}\n />\n )\n }\n if (field.type === 'sorted') {\n return (\n <TextField\n key={fieldId}\n {...common}\n helperText={\n error || field.description || 'Comma-separated list'\n }\n />\n )\n }\n return <TextField key={fieldId} {...common} />\n })}\n </DatasetRecordSiteContext.Provider>\n </DialogContent>\n <DialogActions>\n <Button onClick={() => setEditor(null)}>{'Cancel'}</Button>\n <Button\n variant=\"contained\"\n color=\"primary\"\n onClick={handleSaveRecord}\n >\n {editor?.id ? 'Save' : 'Add'}\n </Button>\n </DialogActions>\n </Dialog>\n <Dialog\n open={Boolean(joiner)}\n onClose={() => setJoiner(null)}\n maxWidth=\"xs\"\n fullWidth\n >\n <DialogTitle>{'New join collection'}</DialogTitle>\n <DialogContent\n sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}\n >\n <Typography variant=\"body2\" color=\"text.secondary\" sx={{ mt: 1 }}>\n {'Links two collections many-to-many; each row pairs one ' +\n 'document from each side.'}\n </Typography>\n {(['a', 'b'] as const).map((side) => (\n <TextField\n key={side}\n select\n size=\"small\"\n label={side === 'a' ? 'First collection' : 'Second collection'}\n value={joiner?.[side] ?? ''}\n onChange={(event) =>\n setJoiner((prev) =>\n prev ? { ...prev, [side]: event.target.value } : prev,\n )\n }\n >\n {datasets.map((item) => (\n <MenuItem key={item.$id} value={item.$id}>\n {/* Who it is shared with only where two share a name (AGL-4047). */}\n {joinLabels[item.$id]}\n </MenuItem>\n ))}\n </TextField>\n ))}\n </DialogContent>\n <DialogActions>\n <Button onClick={() => setJoiner(null)}>{'Cancel'}</Button>\n <Button\n variant=\"contained\"\n color=\"primary\"\n disabled={\n !scopeReady || !joiner?.a || !joiner?.b || joiner.a === joiner.b\n }\n onClick={handleCreateJoin}\n >\n {'Create'}\n </Button>\n </DialogActions>\n </Dialog>\n <DatasetSchemaDialog\n hostId={hostId}\n orgId={orgId ?? undefined}\n dataset={schemaOpen && selected ? selected : null}\n datasets={knownDatasets}\n // The dataset's documents, not the loaded window (AGL-1716) — the\n // dialog warns \"N documents exist\" before a narrowing type change,\n // and 500 was the cap talking, not the collection.\n recordCount={recordCount}\n seedFromCache={seed.fromCache}\n seedUnreadable={seed.unreadable}\n seedListen={seed.listen}\n canChangeSharing={!blocked.creates}\n {...(blocked.sharingOnly ? { sharingOnlyReason: blocked.writesReason } : {})}\n onClose={() => setSchemaOpen(false)}\n />\n </>\n )\n}\nHostDatasetsCard.displayName = 'HostDatasetsCard'\n\nexport default HostDatasetsCard\n"],"names":["TransferResumeImport","checkDatasetQuota","checkEntitlement","checkQuota","getCustomFieldType","PageHeaderActions","PageHeaderRecord","pluginDocsHelp","scopeTokensForHost","useTransferLauncher","visibleToHost","nameSearchKey","HubSections","AppLink","CardDisplay","MdiIcon","useConfirmationContext","mdiArrowLeft","ListFilterChips","ListPagination","ListQueryNotices","listQueryRefusals","ListTable","listActionsColumn","QuotaReadoutComponent","listFilterGridColumns","useListGridFilter","useSnackbar","Timestamp","Alert","Box","Button","Chip","CircularProgress","Dialog","DialogActions","DialogContent","DialogTitle","MenuItem","Stack","TextField","Tooltip","Typography","collection","deleteDoc","deleteField","doc","endAt","getCountFromServer","getDoc","getDocs","limit","orderBy","query","startAt","where","setDoc","writeBatch","useRouter","useCallback","useEffect","useMemo","useState","useListColumnSort","useFirestore","useFirestoreCollection","useFirestoreDoc","useHostActivityLogger","useOrgDataScope","usePagedCollection","useScopeTokens","useUser","listQueryConstraints","authorizedFetch","DatasetSchemaDialog","DatasetRecordDialog","DatasetRecordFieldList","DatasetRecordSiteContext","DatasetIconPreview","DATASET_ICON_FIELD_TYPE","readDatasetIconValue","datasetRecordFilter","planRecordQuery","recordColumn","coerceDocumentValues","datasetIntegrityUpdate","datasetValueToInput","effectiveDatasetModel","formatDatasetValue","modelFromFieldEntries","validateDocument","fillRecordAddresses","planReferenceFixups","referencingFieldIds","restrictedDeleteMessage","BlockedControl","datasetListScope","DATASETS_EXPORT_REFUSAL","DATASETS_VIEW_RECORDS_REFUSAL","DATASETS_WRITE_REFUSAL","useDatasetWritesBlocked","DATASET_SAMPLE_RECORD_NOTE","datasetDisplayName","isSampleDatasetRecord","parseDatasetFieldEntries","datasetTransferResourceKey","DATASET_RAIL_GROUP_AT","datasetCreatedLabel","datasetPickerLabelsOf","datasetRailName","datasetRecordTitle","datasetRailSecondary","datasetSharingLabel","datasetSourceLabel","groupDatasetsBySharing","sortDatasetsByName","useOrgSites","NO_QUERY_SORTS","EXPORT_OFF_TOOLBAR","toolbar","csvOptions","disableToolbarButton","printOptions","NO_DATASETS","DATASET_LIST_WINDOW","datasetRow","snapshot","$id","id","data","newDatasetSharingNote","siteOnly","HostDatasetsCard","props","routeDatasetId","listed","hostId","basePath","segments","router","scope","dataScope","orgId","tokens","scopeTokens","orgWide","viewerOrgWide","loaded","scopeLoaded","pageHostId","undefined","reachScope","listScope","memberScope","scopeReady","Boolean","firestore","enqueueSnackbar","confirm","org","logActivity","user","createdFromHostId","createdFrom","recordSite","createsSiteOnly","defaultResourceScope","callDatasetApi","payload","response","method","headers","body","JSON","stringify","result","json","catch","ok","Error","error","announceRecords","datasetId","action","console","nameSearch","setNameSearch","sharedWith","setSharedWith","railWindow","setRailWindow","railScope","serverNameKey","hostNames","sites","orgSites","datasetDocs","status","datasetsStatus","fromCache","datasetsFromCache","listen","datasetsListen","idField","datasets","slice","moreDatasets","length","railNarrowed","routeRecordId","selectedId","setSelectedId","wantedId","find","item","listAnswered","listConfirmed","listUnreadable","linkedRead","linked","notSharedHere","visibleTo","notFound","selected","seed","unreadable","openDataset","push","landing","replace","schemaOpen","setSchemaOpen","blocked","model","fields","order","recordFilter","gridFilter","selectFields","recordClauses","clauses","filter","clause","some","field","column","recordPlan","searchWords","recordPlanKey","filters","plan","rows","records","hasMore","hasMoreRecords","page","recordPage","setPage","setRecordPage","pageSize","recordPageSize","setPageSize","setRecordPageSize","pageLimit","routeRecordRead","routeRecord","routeRecordMissing","recordRefusals","refused","options","filteringRecords","word","trim","datasetCountEpoch","setDatasetCountEpoch","recordCountEpoch","setRecordCountEpoch","serverDatasetCount","setServerDatasetCount","serverRecordCount","setServerRecordCount","active","then","count","countedDatasetId","datasetCount","recordCount","creator","setCreator","handleOpenCreator","variant","persist","quota","allowed","upgradeRequired","addonPriceUsd","name","creatorEntries","creatorFields","map","entry","handleCreate","displayName","String","message","epoch","type","joiner","setJoiner","handleCreateJoin","a","b","fieldFor","target","fieldId","required","reference","displayFieldId","onDelete","aRef","bRef","handleDeleteDataset","confirmed","title","description","toLocaleString","confirmationText","confirmationButtonProps","color","scopeId","kind","outsideTargets","setOutsideTargets","missing","Set","Promise","all","exists","knownDatasets","refOptions","setRefOptions","referenceFields","docs","docSnapshot","label","get","entries","Object","fromEntries","resolveReferenceLabel","option","referenceLabel","value","ids","Array","isArray","join","viewerId","setViewerId","datasetHref","openRecord","encodeURIComponent","viewerRecord","record","editor","setEditor","handleOpenRecord","values","default","errors","sample","handleSaveRecord","coerced","keys","prev","recordRef","updatedAt","now","mergeFields","handleDeleteRecord","afterDelete","alsoChanged","referencing","reach","other","otherModel","holders","start","updates","batch","update","holder","ref","commit","add","transfer","transferTarget","resource","known","importAllowed","writes","canImport","can","canExport","handleImport","dataset","openImport","onFinished","handleExport","openExport","search","recordGridColumns","isIcon","customType","shown","row","headerName","flex","minWidth","renderCell","direction","spacing","sx","alignItems","height","noWrap","size","justifyContent","onClick","reason","writesReason","width","recordPageSorts","recordSortHeaders","recordColumnSort","sorts","pageSorts","grouped","railSections","tab","group","href","secondary","flatMap","joinLabels","offerSharedWith","sitesByName","sort","localeCompare","railHeader","mb","fullWidth","placeholder","onChange","event","slotProps","htmlInput","select","site","railFooter","px","py","aria-label","mt","window","facts","factsRow","pairs","useFlexGap","flexWrap","component","overflowWrap","recordTitle","recordPanel","help","anchor","header","startIcon","path","span","contentGutterX","contentGutterY","contentBordered","HeaderProps","subheader","severity","resolveReference","divided","panel","sharingOnly","exports","deletes","deletesReason","ready","used","noun","setClauses","notices","pinActions","columnSort","columns","onOpen","hideFooter","filterMode","filterModel","onFilterModelChange","quickFilter","noRowsLabel","rowCount","onPageChange","onPageSizeChange","creates","keepHeading","parentTitle","parentHref","sections","navHeader","scrollRail","open","onClose","maxWidth","display","flexDirection","gap","autoFocus","helperText","disabled","onEdit","Provider","index","setValue","nextValue","common","customFieldType","Input","CustomInput","next","validation","multiple","selectedIds","split","part","inputLabel","shrink","side","seedFromCache","seedUnreadable","seedListen","canChangeSharing","sharingOnlyReason"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAGA,SAASA,oBAAoB,QAAQ,gDAA+C;AACpF,SAEEC,iBAAiB,EACjBC,gBAAgB,EAChBC,UAAU,EACVC,kBAAkB,EAClBC,iBAAiB,EACjBC,gBAAgB,EAChBC,cAAc,EACdC,kBAAkB,EAClBC,mBAAmB,EACnBC,aAAa,QACR,eAAc;AACrB,SAASC,aAAa,QAAQ,qCAAoC;AAClE,SAASC,WAAW,QAAyB,4CAA2C;AACxF,SAASC,OAAO,EAAEC,WAAW,EAAEC,OAAO,EAAEC,sBAAsB,QAAQ,uBAAsB;AAC5F,SAASC,YAAY,QAAQ,yBAAwB;AACrD,OAAOC,qBAAqB,8DAA6D;AACzF,SAASC,cAAc,QAAQ,4DAA2D;AAC1F,OAAOC,oBACLC,iBAAiB,QACZ,+DAA8D;AACrE,SACEC,SAAS,EACTC,iBAAiB,QACZ,uDAAsD;AAC7D,OAAOC,2BAA2B,0DAAyD;AAC3F,SAASC,qBAAqB,QAAQ,8CAA6C;AACnF,SAASC,iBAAiB,QAAQ,kDAAiD;AACnF,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SAASC,SAAS,QAAQ,+BAA8B;AACxD,SACEC,KAAK,EACLC,GAAG,EACHC,MAAM,EACNC,IAAI,EACJC,gBAAgB,EAChBC,MAAM,EACNC,aAAa,EACbC,aAAa,EACbC,WAAW,EACXC,QAAQ,EACRC,KAAK,EACLC,SAAS,EACTC,OAAO,EACPC,UAAU,QACL,gBAAe;AACtB,SACEC,UAAU,EACVC,SAAS,EACTC,WAAW,EACXC,GAAG,EACHC,KAAK,EACLC,kBAAkB,EAClBC,MAAM,EACNC,OAAO,EACPC,KAAK,EACLC,OAAO,EACPC,KAAK,EACLC,OAAO,EACPC,KAAK,EACLC,MAAM,EACNC,UAAU,QACL,qBAAoB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