@aglyn/plugins-data 1.10.0 → 1.12.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 +10 -10
- package/src/lib/components/host-datasets-card.component.js +178 -63
- package/src/lib/components/host-datasets-card.component.js.map +1 -1
- package/src/lib/components/use-dataset-writes-blocked.d.ts +47 -0
- package/src/lib/components/use-dataset-writes-blocked.js +61 -0
- package/src/lib/components/use-dataset-writes-blocked.js.map +1 -0
- package/src/lib/model/dataset-record-list.d.ts +16 -0
- package/src/lib/model/dataset-record-list.js +16 -2
- package/src/lib/model/dataset-record-list.js.map +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aglyn/plugins-data",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.12.0",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"homepage": "https://aglyn.com",
|
|
6
6
|
"repository": {
|
|
@@ -25,15 +25,15 @@
|
|
|
25
25
|
"./package.json": "./package.json"
|
|
26
26
|
},
|
|
27
27
|
"dependencies": {
|
|
28
|
-
"@aglyn/aglyn": "1.
|
|
29
|
-
"@aglyn/shared-data-mdi": "1.
|
|
30
|
-
"@aglyn/shared-ui-jsx": "1.
|
|
31
|
-
"@aglyn/shared-ui-snackstack": "1.
|
|
32
|
-
"@aglyn/shared-util-http": "1.
|
|
33
|
-
"@aglyn/shared-util-timestamp": "1.
|
|
34
|
-
"@aglyn/tenant-data-admin": "1.
|
|
35
|
-
"@aglyn/tenant-feature-instance": "1.
|
|
36
|
-
"@aglyn/tenant-runtime": "1.
|
|
28
|
+
"@aglyn/aglyn": "1.12.0",
|
|
29
|
+
"@aglyn/shared-data-mdi": "1.12.0",
|
|
30
|
+
"@aglyn/shared-ui-jsx": "1.12.0",
|
|
31
|
+
"@aglyn/shared-ui-snackstack": "1.12.0",
|
|
32
|
+
"@aglyn/shared-util-http": "1.12.0",
|
|
33
|
+
"@aglyn/shared-util-timestamp": "1.12.0",
|
|
34
|
+
"@aglyn/tenant-data-admin": "1.12.0",
|
|
35
|
+
"@aglyn/tenant-feature-instance": "1.12.0",
|
|
36
|
+
"@aglyn/tenant-runtime": "1.12.0",
|
|
37
37
|
"@swc/helpers": "0.5.23"
|
|
38
38
|
},
|
|
39
39
|
"peerDependencies": {
|
|
@@ -29,7 +29,7 @@ import { useListGridFilter } from "@aglyn/shared-ui-jsx/hooks/use-list-grid-filt
|
|
|
29
29
|
import { useSnackbar } from "@aglyn/shared-ui-snackstack";
|
|
30
30
|
import { Timestamp } from "@aglyn/shared-util-timestamp";
|
|
31
31
|
import { Alert, Button, Chip, Dialog, DialogActions, DialogContent, DialogTitle, MenuItem, Stack, TextField, Tooltip, Typography } from "@mui/material";
|
|
32
|
-
import { collection, deleteDoc, deleteField, doc, getCountFromServer, getDocs, limit, query, where, setDoc, writeBatch } from "firebase/firestore";
|
|
32
|
+
import { collection, deleteDoc, deleteField, doc, getCountFromServer, getDoc, getDocs, limit, query, where, setDoc, writeBatch } from "firebase/firestore";
|
|
33
33
|
import { useCallback, useEffect, useMemo, useState } from "react";
|
|
34
34
|
import { useListColumnSort } from "@aglyn/shared-ui-jsx/hooks/use-list-column-sort";
|
|
35
35
|
import { useFirestore, useFirestoreCollection, useHostActivityLogger, useOrgDataScope, usePagedCollection, useScopeTokens, useUser } from "@aglyn/tenant-feature-instance";
|
|
@@ -42,6 +42,9 @@ import { datasetRecordFilter, planRecordQuery, recordColumn } from "./dataset-re
|
|
|
42
42
|
import { coerceDocumentValues, datasetIntegrityUpdate, datasetValueToInput, effectiveDatasetModel, formatDatasetValue, modelFromFieldEntries, validateDocument } from "../model/dataset-models.js";
|
|
43
43
|
import { fillRecordAddresses } from "../record-pages/record-pages.js";
|
|
44
44
|
import { planReferenceFixups, referencingFieldIds, restrictedDeleteMessage } from "../model/dataset-record-delete-plan.js";
|
|
45
|
+
import { BlockedControl } from "@aglyn/shared-ui-jsx/components/blocked-control.component";
|
|
46
|
+
import { datasetListScope } from "../model/dataset-record-list.js";
|
|
47
|
+
import { DATASETS_DELETE_REFUSAL, DATASETS_WRITE_REFUSAL, useDatasetWritesBlocked } from "./use-dataset-writes-blocked.js";
|
|
45
48
|
import { DATASET_SAMPLE_RECORD_NOTE, datasetDisplayName, isSampleDatasetRecord, parseDatasetFieldEntries } from "../model/datasets.js";
|
|
46
49
|
import { datasetTransferResourceKey } from "../transfer/dataset-transfer-key.js";
|
|
47
50
|
/**
|
|
@@ -52,6 +55,11 @@ import { datasetTransferResourceKey } from "../transfer/dataset-transfer-key.js"
|
|
|
52
55
|
* sharing is "Only the site they were created in". Everywhere else a new
|
|
53
56
|
* dataset starts on All sites: the org Data page has no site to limit it to.
|
|
54
57
|
*/ /** The records walk serves no header order: every header sorts the page. */ const NO_QUERY_SORTS = [];
|
|
58
|
+
/** Stable, so an empty answer does not re-render the card. */ const NO_DATASETS = [];
|
|
59
|
+
/** The most datasets the card lists, and the most a delete's reference check walks. */ const DATASET_LIST_WINDOW = 100;
|
|
60
|
+
/** A dataset read off its document, as the card's rows carry it. */ const datasetRow = (snapshot)=>_extends({
|
|
61
|
+
$id: snapshot.id
|
|
62
|
+
}, snapshot.data());
|
|
55
63
|
export function newDatasetSharingNote(siteOnly) {
|
|
56
64
|
return siteOnly ? 'Datasets belong to your organization. Your default sharing starts a ' + 'new one on this site only — use Schema to share it with more.' : 'Datasets belong to your organization. A new one is shared with ' + 'every site — use Schema to narrow that.';
|
|
57
65
|
}
|
|
@@ -77,14 +85,30 @@ export function newDatasetSharingNote(siteOnly) {
|
|
|
77
85
|
// rules a scoped member's UNFILTERED list is rejected outright —
|
|
78
86
|
// Firestore fails the whole query if any candidate would fail — so
|
|
79
87
|
// without this the Data page errors rather than showing fewer rows.
|
|
80
|
-
// Org-wide members get no filter: they read everything, and adding one
|
|
81
|
-
// would hide any dataset the AGL-1040 backfill missed.
|
|
82
88
|
const { tokens: scopeTokens, orgWide: viewerOrgWide, loaded: scopeLoaded } = useScopeTokens(orgId);
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
89
|
+
/**
|
|
90
|
+
* The site whose Data page this is, or undefined on the organization Data
|
|
91
|
+
* page. The explicit `orgId` is that page's own scope and already wins over
|
|
92
|
+
* `hostId` when the org is resolved, so it wins here too, even if a caller
|
|
93
|
+
* hands the card both.
|
|
94
|
+
*/ const pageHostId = props.orgId ? undefined : hostId || undefined;
|
|
95
|
+
// What the VIEWER reaches: their scope tokens, or no filter for an org-wide
|
|
96
|
+
// member, who reads everything. Every dataset here is an org dataset, and
|
|
97
|
+
// org datasets are all scoped (AGL-1041).
|
|
98
|
+
const reachScope = viewerOrgWide ? null : scopeTokens;
|
|
99
|
+
/**
|
|
100
|
+
* What this page lists (AGL-4047): a site's Data page shows that site's and
|
|
101
|
+
* the workspace-wide datasets, whoever is looking, as every other site
|
|
102
|
+
* surface does. It used to ask only the viewer's reach, so an owner, who
|
|
103
|
+
* reaches everything, saw every site's datasets on every site. The
|
|
104
|
+
* organization Data page lists the viewer's reach.
|
|
105
|
+
*/ const listScope = useMemo(()=>datasetListScope({
|
|
106
|
+
hostId: pageHostId,
|
|
107
|
+
memberScope: reachScope
|
|
108
|
+
}), [
|
|
109
|
+
pageHostId,
|
|
110
|
+
reachScope
|
|
111
|
+
]);
|
|
88
112
|
// Two answers must be in before listing: the org path (AGL-1061) and the
|
|
89
113
|
// viewer's scope tokens (AGL-1047). `useScopeTokens` reports org-wide
|
|
90
114
|
// while loading, so without `scopeLoaded` a scoped collaborator's first
|
|
@@ -93,6 +117,7 @@ export function newDatasetSharingNote(siteOnly) {
|
|
|
93
117
|
// it easy to miss: the page looks right and logs a denial every mount.
|
|
94
118
|
const scopeReady = Boolean(dataScope) && scopeLoaded;
|
|
95
119
|
const firestore = useFirestore();
|
|
120
|
+
const blocked = useDatasetWritesBlocked(orgId);
|
|
96
121
|
const { enqueueSnackbar } = useSnackbar();
|
|
97
122
|
const { confirm } = useConfirmationContext();
|
|
98
123
|
const { org } = props;
|
|
@@ -104,11 +129,8 @@ export function newDatasetSharingNote(siteOnly) {
|
|
|
104
129
|
*
|
|
105
130
|
* `/api/orgs/datasets` stamps a new dataset with the org's Default sharing,
|
|
106
131
|
* and that setting can only narrow to a site the request names — so a
|
|
107
|
-
* create that names none lands on All sites whatever the org chose.
|
|
108
|
-
|
|
109
|
-
* `hostId` when the org is resolved, so it wins here too: a create made
|
|
110
|
-
* there names no site, even if a caller hands the card both.
|
|
111
|
-
*/ const createdFromHostId = props.orgId ? undefined : hostId || undefined;
|
|
132
|
+
* create that names none lands on All sites whatever the org chose.
|
|
133
|
+
*/ const createdFromHostId = pageHostId;
|
|
112
134
|
const createdFrom = useMemo(()=>createdFromHostId ? {
|
|
113
135
|
hostId: createdFromHostId
|
|
114
136
|
} : {}, [
|
|
@@ -186,13 +208,14 @@ export function newDatasetSharingNote(siteOnly) {
|
|
|
186
208
|
* than recomputed there.
|
|
187
209
|
*/ fromCache: datasetsFromCache, listen: datasetsListen } = useFirestoreCollection(()=>// `scopeReady` already implies a non-null `dataScope`; testing it
|
|
188
210
|
// directly is what lets the compiler see that too.
|
|
189
|
-
dataScope && scopeReady ? query(collection(firestore, dataScope[0], dataScope[1], 'datasets'), ...
|
|
190
|
-
where('visibleTo', 'array-contains-any',
|
|
191
|
-
|
|
211
|
+
dataScope && scopeReady ? query(collection(firestore, dataScope[0], dataScope[1], 'datasets'), ...listScope ? [
|
|
212
|
+
where('visibleTo', 'array-contains-any', [
|
|
213
|
+
...listScope
|
|
214
|
+
])
|
|
215
|
+
] : [], limit(DATASET_LIST_WINDOW)) : null, [
|
|
192
216
|
firestore,
|
|
193
217
|
dataScope,
|
|
194
|
-
|
|
195
|
-
scopeTokens,
|
|
218
|
+
listScope,
|
|
196
219
|
scopeReady
|
|
197
220
|
], {
|
|
198
221
|
idField: '$id'
|
|
@@ -630,6 +653,46 @@ export function newDatasetSharingNote(siteOnly) {
|
|
|
630
653
|
enqueueSnackbar,
|
|
631
654
|
logActivity
|
|
632
655
|
]);
|
|
656
|
+
/**
|
|
657
|
+
* What the selected dataset's references point at beyond this site's list
|
|
658
|
+
* (AGL-4047). A dataset this site sees can name a target another site holds;
|
|
659
|
+
* the schema dialog warns about exactly that, and a cell still labels the
|
|
660
|
+
* row it points at, so the target has to be known even though the site's
|
|
661
|
+
* list does not show it. Read one by one, and only when there is one; a
|
|
662
|
+
* target the viewer may not read stays unknown.
|
|
663
|
+
*/ const [outsideTargets, setOutsideTargets] = useState(NO_DATASETS);
|
|
664
|
+
useEffect(()=>{
|
|
665
|
+
let active = true;
|
|
666
|
+
const missing = pageHostId ? [
|
|
667
|
+
...new Set(model.order.map((fieldId)=>{
|
|
668
|
+
var _model_fields_fieldId_reference, _model_fields_fieldId;
|
|
669
|
+
return (_model_fields_fieldId = model.fields[fieldId]) == null ? void 0 : (_model_fields_fieldId_reference = _model_fields_fieldId.reference) == null ? void 0 : _model_fields_fieldId_reference.datasetId;
|
|
670
|
+
}).filter((id)=>Boolean(id)))
|
|
671
|
+
].filter((id)=>!datasets.some((item)=>item.$id === id)) : [];
|
|
672
|
+
if (!missing.length || !dataScope) {
|
|
673
|
+
setOutsideTargets(NO_DATASETS);
|
|
674
|
+
return;
|
|
675
|
+
}
|
|
676
|
+
void Promise.all(missing.map((id)=>getDoc(doc(firestore, dataScope[0], dataScope[1], 'datasets', id)).then((snapshot)=>snapshot.exists() ? datasetRow(snapshot) : null, ()=>null))).then((rows)=>{
|
|
677
|
+
if (active) setOutsideTargets(rows.filter(Boolean));
|
|
678
|
+
});
|
|
679
|
+
return ()=>{
|
|
680
|
+
active = false;
|
|
681
|
+
};
|
|
682
|
+
}, [
|
|
683
|
+
pageHostId,
|
|
684
|
+
model,
|
|
685
|
+
datasets,
|
|
686
|
+
firestore,
|
|
687
|
+
dataScope
|
|
688
|
+
]);
|
|
689
|
+
const knownDatasets = useMemo(()=>outsideTargets.length ? [
|
|
690
|
+
...datasets,
|
|
691
|
+
...outsideTargets
|
|
692
|
+
] : datasets, [
|
|
693
|
+
datasets,
|
|
694
|
+
outsideTargets
|
|
695
|
+
]);
|
|
633
696
|
// Reference pickers (AGL-180): load target-collection rows for every
|
|
634
697
|
// reference field in the model (id -> display label).
|
|
635
698
|
const [refOptions, setRefOptions] = useState({});
|
|
@@ -646,7 +709,7 @@ export function newDatasetSharingNote(siteOnly) {
|
|
|
646
709
|
void Promise.all(referenceFields.map(async (fieldId)=>{
|
|
647
710
|
var _reference_displayFieldId, _ref;
|
|
648
711
|
const reference = model.fields[fieldId].reference;
|
|
649
|
-
const target =
|
|
712
|
+
const target = knownDatasets.find((item)=>item.$id === reference.datasetId);
|
|
650
713
|
const displayFieldId = (_reference_displayFieldId = reference.displayFieldId) != null ? _reference_displayFieldId : effectiveDatasetModel(target != null ? target : {}).order[0];
|
|
651
714
|
const snapshot = await getDocs(query(collection(firestore, dataScope[0], dataScope[1], 'datasets', reference.datasetId, 'records'), limit(200))).catch(()=>null);
|
|
652
715
|
const options = ((_ref = snapshot == null ? void 0 : snapshot.docs) != null ? _ref : []).map((docSnapshot)=>{
|
|
@@ -669,7 +732,7 @@ export function newDatasetSharingNote(siteOnly) {
|
|
|
669
732
|
};
|
|
670
733
|
}, [
|
|
671
734
|
model,
|
|
672
|
-
|
|
735
|
+
knownDatasets,
|
|
673
736
|
firestore,
|
|
674
737
|
dataScope
|
|
675
738
|
]);
|
|
@@ -873,11 +936,32 @@ export function newDatasetSharingNote(siteOnly) {
|
|
|
873
936
|
* fails open is worse than no check, because the UI then tells the user
|
|
874
937
|
* the record is safe to remove.
|
|
875
938
|
*
|
|
876
|
-
* ⚠️ Reaches the collections in
|
|
877
|
-
*
|
|
878
|
-
*
|
|
879
|
-
*
|
|
880
|
-
|
|
939
|
+
* ⚠️ Reaches the collections in this viewer's scoped, capped window. A
|
|
940
|
+
* referencing collection shared with no site this member can see is one
|
|
941
|
+
* the client may not read at all, so it is not consulted; only a server
|
|
942
|
+
* route could close that.
|
|
943
|
+
*
|
|
944
|
+
* On a site's Data page that window is NOT the list (AGL-4047). The list
|
|
945
|
+
* is the site's, and a dataset another site holds can reference a row of
|
|
946
|
+
* one shared with both: narrowing what the page shows must not narrow
|
|
947
|
+
* what a delete protects. So the page reads the viewer's reach here, once,
|
|
948
|
+
* at the moment of the delete, and refuses if it cannot.
|
|
949
|
+
*/ let referencing = datasets;
|
|
950
|
+
if (pageHostId) {
|
|
951
|
+
try {
|
|
952
|
+
const reach = await getDocs(query(collection(firestore, dataScope[0], dataScope[1], 'datasets'), ...reachScope ? [
|
|
953
|
+
where('visibleTo', 'array-contains-any', [
|
|
954
|
+
...reachScope
|
|
955
|
+
])
|
|
956
|
+
] : [], limit(DATASET_LIST_WINDOW)));
|
|
957
|
+
referencing = reach.docs.map(datasetRow);
|
|
958
|
+
} catch (unused) {
|
|
959
|
+
return void enqueueSnackbar('Cannot delete: the datasets that may reference this record could ' + 'not be checked, so removing it could break them. Nothing was ' + 'deleted.', {
|
|
960
|
+
variant: 'error'
|
|
961
|
+
});
|
|
962
|
+
}
|
|
963
|
+
}
|
|
964
|
+
for (const other of referencing){
|
|
881
965
|
const otherModel = effectiveDatasetModel(other);
|
|
882
966
|
if (!referencingFieldIds(otherModel, selected.$id).length) continue;
|
|
883
967
|
let snapshot;
|
|
@@ -935,6 +1019,8 @@ export function newDatasetSharingNote(siteOnly) {
|
|
|
935
1019
|
}, [
|
|
936
1020
|
selected,
|
|
937
1021
|
datasets,
|
|
1022
|
+
pageHostId,
|
|
1023
|
+
reachScope,
|
|
938
1024
|
firestore,
|
|
939
1025
|
dataScope,
|
|
940
1026
|
announceRecords,
|
|
@@ -1065,16 +1151,24 @@ export function newDatasetSharingNote(siteOnly) {
|
|
|
1065
1151
|
onClick: ()=>setViewerId(record.$id),
|
|
1066
1152
|
children: 'View'
|
|
1067
1153
|
}),
|
|
1068
|
-
/*#__PURE__*/ _jsx(
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
children:
|
|
1154
|
+
/*#__PURE__*/ _jsx(BlockedControl, {
|
|
1155
|
+
blocked: blocked.writes,
|
|
1156
|
+
reason: DATASETS_WRITE_REFUSAL,
|
|
1157
|
+
children: /*#__PURE__*/ _jsx(Button, {
|
|
1158
|
+
size: "small",
|
|
1159
|
+
onClick: handleOpenRecord(record),
|
|
1160
|
+
children: 'Edit'
|
|
1161
|
+
})
|
|
1072
1162
|
}),
|
|
1073
|
-
/*#__PURE__*/ _jsx(
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1163
|
+
/*#__PURE__*/ _jsx(BlockedControl, {
|
|
1164
|
+
blocked: blocked.writes,
|
|
1165
|
+
reason: DATASETS_WRITE_REFUSAL,
|
|
1166
|
+
children: /*#__PURE__*/ _jsx(Button, {
|
|
1167
|
+
size: "small",
|
|
1168
|
+
color: "error",
|
|
1169
|
+
onClick: handleDeleteRecord(record),
|
|
1170
|
+
children: 'Delete'
|
|
1171
|
+
})
|
|
1078
1172
|
})
|
|
1079
1173
|
]
|
|
1080
1174
|
}), {
|
|
@@ -1086,7 +1180,8 @@ export function newDatasetSharingNote(siteOnly) {
|
|
|
1086
1180
|
referenceLabel,
|
|
1087
1181
|
handleOpenRecord,
|
|
1088
1182
|
handleDeleteRecord,
|
|
1089
|
-
recordFilter
|
|
1183
|
+
recordFilter,
|
|
1184
|
+
blocked.writes
|
|
1090
1185
|
]);
|
|
1091
1186
|
/*
|
|
1092
1187
|
* EVERY HEADER SORTS — THE PAGE ON SCREEN (AGL-3680). A record's values are
|
|
@@ -1172,16 +1267,24 @@ export function newDatasetSharingNote(siteOnly) {
|
|
|
1172
1267
|
children: datasetDisplayName(item)
|
|
1173
1268
|
}, item.$id))
|
|
1174
1269
|
}),
|
|
1175
|
-
/*#__PURE__*/ _jsx(
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1270
|
+
/*#__PURE__*/ _jsx(BlockedControl, {
|
|
1271
|
+
blocked: blocked.writes,
|
|
1272
|
+
reason: DATASETS_WRITE_REFUSAL,
|
|
1273
|
+
children: /*#__PURE__*/ _jsx(Button, {
|
|
1274
|
+
size: "small",
|
|
1275
|
+
color: "primary",
|
|
1276
|
+
onClick: handleOpenRecord(),
|
|
1277
|
+
children: 'Add record'
|
|
1278
|
+
})
|
|
1180
1279
|
}),
|
|
1181
|
-
/*#__PURE__*/ _jsx(
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
children:
|
|
1280
|
+
/*#__PURE__*/ _jsx(BlockedControl, {
|
|
1281
|
+
blocked: blocked.writes,
|
|
1282
|
+
reason: DATASETS_WRITE_REFUSAL,
|
|
1283
|
+
children: /*#__PURE__*/ _jsx(Button, {
|
|
1284
|
+
size: "small",
|
|
1285
|
+
onClick: ()=>setSchemaOpen(true),
|
|
1286
|
+
children: 'Schema'
|
|
1287
|
+
})
|
|
1185
1288
|
}),
|
|
1186
1289
|
transferTarget ? /*#__PURE__*/ _jsx(TransferResumeImport, _extends({
|
|
1187
1290
|
target: transferTarget
|
|
@@ -1200,11 +1303,15 @@ export function newDatasetSharingNote(siteOnly) {
|
|
|
1200
1303
|
onClick: handleExport,
|
|
1201
1304
|
children: 'Export'
|
|
1202
1305
|
}) : null,
|
|
1203
|
-
/*#__PURE__*/ _jsx(
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
|
|
1306
|
+
/*#__PURE__*/ _jsx(BlockedControl, {
|
|
1307
|
+
blocked: blocked.deletes,
|
|
1308
|
+
reason: DATASETS_DELETE_REFUSAL,
|
|
1309
|
+
children: /*#__PURE__*/ _jsx(Button, {
|
|
1310
|
+
size: "small",
|
|
1311
|
+
color: "error",
|
|
1312
|
+
onClick: handleDeleteDataset,
|
|
1313
|
+
children: 'Delete'
|
|
1314
|
+
})
|
|
1208
1315
|
})
|
|
1209
1316
|
]
|
|
1210
1317
|
}),
|
|
@@ -1267,20 +1374,28 @@ export function newDatasetSharingNote(siteOnly) {
|
|
|
1267
1374
|
flexWrap: 'wrap'
|
|
1268
1375
|
},
|
|
1269
1376
|
children: [
|
|
1270
|
-
/*#__PURE__*/ _jsx(
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1377
|
+
/*#__PURE__*/ _jsx(BlockedControl, {
|
|
1378
|
+
blocked: blocked.writes,
|
|
1379
|
+
reason: DATASETS_WRITE_REFUSAL,
|
|
1380
|
+
children: /*#__PURE__*/ _jsx(Button, {
|
|
1381
|
+
size: "small",
|
|
1382
|
+
variant: "outlined",
|
|
1383
|
+
color: "primary",
|
|
1384
|
+
onClick: handleOpenCreator,
|
|
1385
|
+
children: 'Add dataset'
|
|
1386
|
+
})
|
|
1276
1387
|
}),
|
|
1277
|
-
datasets.length >= 2 ? /*#__PURE__*/ _jsx(
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
1388
|
+
datasets.length >= 2 ? /*#__PURE__*/ _jsx(BlockedControl, {
|
|
1389
|
+
blocked: blocked.writes,
|
|
1390
|
+
reason: DATASETS_WRITE_REFUSAL,
|
|
1391
|
+
children: /*#__PURE__*/ _jsx(Button, {
|
|
1392
|
+
size: "small",
|
|
1393
|
+
onClick: ()=>setJoiner({
|
|
1394
|
+
a: '',
|
|
1395
|
+
b: ''
|
|
1396
|
+
}),
|
|
1397
|
+
children: 'Add join collection'
|
|
1398
|
+
})
|
|
1284
1399
|
}) : null
|
|
1285
1400
|
]
|
|
1286
1401
|
})
|
|
@@ -1605,7 +1720,7 @@ export function newDatasetSharingNote(siteOnly) {
|
|
|
1605
1720
|
hostId: hostId,
|
|
1606
1721
|
orgId: orgId != null ? orgId : undefined,
|
|
1607
1722
|
dataset: schemaOpen && selected ? selected : null,
|
|
1608
|
-
datasets:
|
|
1723
|
+
datasets: knownDatasets,
|
|
1609
1724
|
// The dataset's documents, not the loaded window (AGL-1716) — the
|
|
1610
1725
|
// dialog warns "N documents exist" before a narrowing type change,
|
|
1611
1726
|
// and 500 was the cap talking, not the collection.
|
|
@@ -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 { TransferResumeImport } from '@aglyn/aglyn/app-utils/transfer-resume-import'\nimport {\n type AglynOrgBilling,\n checkDatasetQuota,\n checkEntitlement,\n checkQuota,\n getCustomFieldType,\n pluginDocsHelp,\n useTransferLauncher,\n} from '@aglyn/aglyn'\nimport { CardDisplay, useConfirmationContext } from '@aglyn/shared-ui-jsx'\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 Button,\n Chip,\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 getCountFromServer,\n getDocs,\n limit,\n query,\n where,\n setDoc,\n writeBatch,\n} from 'firebase/firestore'\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 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 } 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 { DATASET_SAMPLE_RECORD_NOTE, datasetDisplayName, isSampleDatasetRecord, parseDatasetFieldEntries } from '../model/datasets'\nimport { datasetTransferResourceKey } from '../transfer/dataset-transfer-key'\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\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\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 } = props\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 // Org-wide members get no filter: they read everything, and adding one\n // would hide any dataset the AGL-1040 backfill missed.\n const {\n tokens: scopeTokens,\n orgWide: viewerOrgWide,\n loaded: scopeLoaded,\n } = useScopeTokens(orgId)\n // Every dataset this card can now reach is an org dataset, and org\n // datasets are all scoped (AGL-1041) — so the filter turns purely on\n // whether the VIEWER is org-wide. It used to also ask whether an org had\n // resolved, for the sake of unscoped rows on the host path.\n const needsScope = !viewerOrgWide\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. The\n * explicit `orgId` is the org Data page's own scope and already wins over\n * `hostId` when the org is resolved, so it wins here too: a create made\n * there names no site, even if a caller hands the card both.\n */\n const createdFromHostId = props.orgId ? undefined : hostId || undefined\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 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 ...(needsScope\n ? [where('visibleTo', 'array-contains-any', scopeTokens)]\n : []),\n limit(100),\n )\n : null,\n [firestore, dataScope, needsScope, scopeTokens, scopeReady],\n { idField: '$id' },\n )\n const datasets = useMemo(\n () =>\n [...(datasetDocs ?? [])].sort((a, b) =>\n datasetDisplayName(a).localeCompare(datasetDisplayName(b)),\n ),\n [datasetDocs],\n )\n const [selectedId, setSelectedId] = useState<string | null>(null)\n const [schemaOpen, setSchemaOpen] = useState(false)\n const selected =\n datasets.find((item) => item.$id === selectedId) ?? datasets[0]\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 dataScope && selected?.$id\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],\n { idField: '$id' },\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) 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])\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 setSelectedId(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])\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 setSelectedId(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])\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 setSelectedId(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 ])\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 = datasets.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, datasets, 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 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) => 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 `datasets`, which is this viewer's\n * scoped, capped picker window. A referencing collection shared with no\n * site this member can see is one the client may not read at all, so it\n * is not consulted; only a server route could close that.\n */\n for (const other of datasets) {\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 },\n [selected, datasets, firestore, dataScope, announceRecords, enqueueSnackbar],\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 offered to a member who\n * may import (Manage data) and Export to any member who can see the\n * dataset (AGL-3546) — the transfer routes' own rule.\n */\n const transfer = useTransferLauncher()\n const transferTarget = selected?.$id\n ? { resource: datasetTransferResourceKey(selected.$id), scope: 'org' as const }\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={() => setViewerId(record.$id)}>\n {'View'}\n </Button>\n <Button size=\"small\" onClick={handleOpenRecord(record)}>\n {'Edit'}\n </Button>\n <Button\n size=\"small\"\n color=\"error\"\n onClick={handleDeleteRecord(record)}\n >\n {'Delete'}\n </Button>\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 recordFilter,\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 return (\n <CardDisplay\n header={'Data'}\n help={pluginDocsHelp('datasets', { anchor: '#filter-records' })}\n contentGutterX\n contentGutterY\n contentBordered=\"all\"\n >\n <Stack spacing={1.5}>\n {orgId ? (\n <Typography variant=\"caption\" color=\"text.secondary\">\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 {datasets.length === 0 ? (\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 ) : (\n <Stack\n direction=\"row\"\n spacing={1}\n useFlexGap\n sx={{ alignItems: 'center', flexWrap: 'wrap' }}\n >\n {/* A scope, not a filter: it picks which collection the table\n walks, and the grid's own Filters panel narrows within it. */}\n <TextField\n select\n size=\"small\"\n label=\"Dataset\"\n value={selected?.$id ?? ''}\n onChange={(event) => setSelectedId(event.target.value)}\n sx={{ minWidth: 180 }}\n >\n {datasets.map((item) => (\n <MenuItem key={item.$id} value={item.$id}>\n {datasetDisplayName(item)}\n </MenuItem>\n ))}\n </TextField>\n <Button\n size=\"small\"\n color=\"primary\"\n onClick={handleOpenRecord()}\n >\n {'Add record'}\n </Button>\n <Button size=\"small\" onClick={() => setSchemaOpen(true)}>\n {'Schema'}\n </Button>\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 {canImport ? (\n <Button size=\"small\" onClick={handleImport}>\n {'Import'}\n </Button>\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) ? (\n <Button size=\"small\" onClick={handleExport}>\n {'Export'}\n </Button>\n ) : null}\n <Button size=\"small\" color=\"error\" onClick={handleDeleteDataset}>\n {'Delete'}\n </Button>\n </Stack>\n )}\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 && (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 rows={recordColumnSort.rows}\n columnSort={recordColumnSort}\n columns={recordGridColumns}\n onOpen={(id) => setViewerId(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 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 direction=\"row\"\n spacing={1}\n useFlexGap\n sx={{ flexWrap: 'wrap' }}\n >\n <Button\n size=\"small\"\n variant=\"outlined\"\n color=\"primary\"\n onClick={handleOpenCreator}\n >\n {'Add dataset'}\n </Button>\n {datasets.length >= 2 ? (\n <Button size=\"small\" onClick={() => setJoiner({ a: '', b: '' })}>\n {'Add join collection'}\n </Button>\n ) : null}\n </Stack>\n </Stack>\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 <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 {datasetDisplayName(item)}\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={datasets}\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={datasetsFromCache}\n seedUnreadable={datasetsStatus === 'error'}\n seedListen={datasetsListen}\n onClose={() => setSchemaOpen(false)}\n />\n </CardDisplay>\n )\n}\nHostDatasetsCard.displayName = 'HostDatasetsCard'\n\nexport default HostDatasetsCard\n"],"names":["TransferResumeImport","checkDatasetQuota","checkEntitlement","checkQuota","getCustomFieldType","pluginDocsHelp","useTransferLauncher","CardDisplay","useConfirmationContext","ListFilterChips","ListPagination","ListQueryNotices","listQueryRefusals","ListTable","listActionsColumn","QuotaReadoutComponent","listFilterGridColumns","useListGridFilter","useSnackbar","Timestamp","Alert","Button","Chip","Dialog","DialogActions","DialogContent","DialogTitle","MenuItem","Stack","TextField","Tooltip","Typography","collection","deleteDoc","deleteField","doc","getCountFromServer","getDocs","limit","query","where","setDoc","writeBatch","useCallback","useEffect","useMemo","useState","useListColumnSort","useFirestore","useFirestoreCollection","useHostActivityLogger","useOrgDataScope","usePagedCollection","useScopeTokens","useUser","listQueryConstraints","authorizedFetch","DatasetSchemaDialog","DatasetRecordDialog","DatasetRecordSiteContext","datasetRecordFilter","planRecordQuery","recordColumn","coerceDocumentValues","datasetIntegrityUpdate","datasetValueToInput","effectiveDatasetModel","formatDatasetValue","modelFromFieldEntries","validateDocument","fillRecordAddresses","planReferenceFixups","referencingFieldIds","restrictedDeleteMessage","DATASET_SAMPLE_RECORD_NOTE","datasetDisplayName","isSampleDatasetRecord","parseDatasetFieldEntries","datasetTransferResourceKey","NO_QUERY_SORTS","newDatasetSharingNote","siteOnly","HostDatasetsCard","props","datasets","hostId","scope","dataScope","orgId","tokens","scopeTokens","orgWide","viewerOrgWide","loaded","scopeLoaded","needsScope","scopeReady","Boolean","firestore","enqueueSnackbar","confirm","org","logActivity","data","user","createdFromHostId","undefined","createdFrom","recordSite","createsSiteOnly","defaultResourceScope","callDatasetApi","payload","response","method","headers","body","JSON","stringify","result","json","catch","ok","Error","error","announceRecords","datasetId","action","console","datasetDocs","status","datasetsStatus","fromCache","datasetsFromCache","listen","datasetsListen","idField","sort","a","b","localeCompare","selectedId","setSelectedId","schemaOpen","setSchemaOpen","selected","find","item","$id","model","fields","order","recordFilter","gridFilter","selectFields","recordClauses","clauses","filter","clause","some","field","column","recordPlan","searchWords","recordPlanKey","filters","plan","orderBy","rows","records","hasMore","hasMoreRecords","page","recordPage","setPage","setRecordPage","pageSize","recordPageSize","setPageSize","setRecordPageSize","pageLimit","recordRefusals","refused","options","filteringRecords","length","word","trim","datasetCountEpoch","setDatasetCountEpoch","recordCountEpoch","setRecordCountEpoch","serverDatasetCount","setServerDatasetCount","serverRecordCount","setServerRecordCount","active","then","snapshot","count","countedDatasetId","datasetCount","recordCount","creator","setCreator","handleOpenCreator","variant","persist","quota","allowed","upgradeRequired","addonPriceUsd","name","creatorEntries","creatorFields","map","entry","id","handleCreate","displayName","String","message","epoch","type","joiner","setJoiner","handleCreateJoin","fieldFor","target","fieldId","required","reference","displayFieldId","onDelete","aRef","bRef","handleDeleteDataset","confirmed","title","description","toLocaleString","confirmationText","confirmationButtonProps","color","scopeId","kind","refOptions","setRefOptions","referenceFields","Promise","all","docs","docSnapshot","label","get","entries","Object","fromEntries","resolveReferenceLabel","option","referenceLabel","value","ids","Array","isArray","join","viewerId","setViewerId","viewerRecord","record","editor","setEditor","handleOpenRecord","values","default","errors","sample","handleSaveRecord","coerced","keys","prev","recordRef","updatedAt","now","mergeFields","handleDeleteRecord","alsoChanged","Set","other","otherModel","holders","start","updates","batch","update","slice","holder","ref","commit","add","transfer","transferTarget","resource","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","width","recordPageSorts","recordSortHeaders","recordColumnSort","sorts","pageSorts","header","help","anchor","contentGutterX","contentGutterY","contentBordered","useFlexGap","flexWrap","select","onChange","event","ready","used","noun","setClauses","notices","aria-label","columnSort","columns","onOpen","hideFooter","filterMode","filterModel","onFilterModelChange","quickFilter","noRowsLabel","rowCount","onPageChange","onPageSizeChange","open","onClose","maxWidth","fullWidth","display","flexDirection","gap","autoFocus","mt","helperText","disabled","resolveReference","onEdit","severity","Provider","index","setValue","nextValue","common","customFieldType","customType","Input","CustomInput","next","validation","multiple","selectedIds","split","part","slotProps","inputLabel","shrink","side","seedFromCache","seedUnreadable","seedListen"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GAAG,CAAC,CAACqL;;qDAC1B,KAAC/W;oCAEC0T,MAAM;oCACNjB,MAAK;oCACLzE,OAAO+I,SAAS,MAAM,qBAAqB;oCAC3CvI,KAAK,UAAErC,0BAAAA,MAAQ,CAAC4K,KAAK,mBAAI;oCACzBpD,UAAU,CAACC,QACTxH,UAAU,CAACuD,OACTA,OAAO,aAAKA;gDAAM,CAACoH,KAAK,EAAEnD,MAAMrH,MAAM,CAACiC,KAAK;iDAAKmB;8CAIpDpM,SAASmI,GAAG,CAAC,CAACpE,qBACb,KAACxH;4CAAwB0O,OAAOlH,KAAKC,GAAG;sDACrCzE,mBAAmBwE;2CADPA,KAAKC,GAAG;mCAZpBwP;;;;kCAmBX,MAACpX;;0CACC,KAACH;gCAAOmT,SAAS,IAAMvG,UAAU;0CAAQ;;0CACzC,KAAC5M;gCACCyL,SAAQ;gCACRqC,OAAM;gCACNmI,UACE,CAACtR,cAAc,EAACgI,0BAAAA,OAAQtF,CAAC,KAAI,EAACsF,0BAAAA,OAAQrF,CAAC,KAAIqF,OAAOtF,CAAC,KAAKsF,OAAOrF,CAAC;gCAElE6L,SAAStG;0CAER;;;;;;0BAIP,KAACzK;gBACC4B,QAAQA;gBACRG,KAAK,EAAEA,gBAAAA,QAASkB;gBAChByM,SAASpK,cAAcE,WAAWA,WAAW;gBAC7C7D,UAAUA;gBACV,kEAAkE;gBAClE,mEAAmE;gBACnE,mDAAmD;gBACnDsH,aAAaA;gBACbmM,eAAexQ;gBACfyQ,gBAAgB3Q,mBAAmB;gBACnC4Q,YAAYxQ;gBACZsO,SAAS,IAAM7N,cAAc;;;;AAIrC;AACA9D,iBAAiByI,WAAW,GAAG;AAE/B,eAAezI,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 { TransferResumeImport } from '@aglyn/aglyn/app-utils/transfer-resume-import'\nimport {\n type AglynOrgBilling,\n checkDatasetQuota,\n checkEntitlement,\n checkQuota,\n getCustomFieldType,\n pluginDocsHelp,\n useTransferLauncher,\n} from '@aglyn/aglyn'\nimport { CardDisplay, useConfirmationContext } from '@aglyn/shared-ui-jsx'\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 Button,\n Chip,\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 getCountFromServer,\n getDoc,\n getDocs,\n limit,\n query,\n where,\n setDoc,\n writeBatch,\n} from 'firebase/firestore'\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 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 } 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_DELETE_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'\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\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/** Stable, so an empty answer does not re-render the card. */\nconst NO_DATASETS: any[] = []\n\n/** The most datasets the card lists, and the most a delete's reference check walks. */\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 } = props\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 blocked = useDatasetWritesBlocked(orgId)\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 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 ...(listScope\n ? [where('visibleTo', 'array-contains-any', [...listScope])]\n : []),\n limit(DATASET_LIST_WINDOW),\n )\n : null,\n [firestore, dataScope, listScope, scopeReady],\n { idField: '$id' },\n )\n const datasets = useMemo(\n () =>\n [...(datasetDocs ?? [])].sort((a, b) =>\n datasetDisplayName(a).localeCompare(datasetDisplayName(b)),\n ),\n [datasetDocs],\n )\n const [selectedId, setSelectedId] = useState<string | null>(null)\n const [schemaOpen, setSchemaOpen] = useState(false)\n const selected =\n datasets.find((item) => item.$id === selectedId) ?? datasets[0]\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 dataScope && selected?.$id\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],\n { idField: '$id' },\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) 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])\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 setSelectedId(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])\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 setSelectedId(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])\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 setSelectedId(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 ])\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 = pageHostId\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 }, [pageHostId, 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 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) => 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 (pageHostId) {\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 },\n [\n selected,\n datasets,\n pageHostId,\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 offered to a member who\n * may import (Manage data) and Export to any member who can see the\n * dataset (AGL-3546) — the transfer routes' own rule.\n */\n const transfer = useTransferLauncher()\n const transferTarget = selected?.$id\n ? { resource: datasetTransferResourceKey(selected.$id), scope: 'org' as const }\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={() => setViewerId(record.$id)}>\n {'View'}\n </Button>\n <BlockedControl blocked={blocked.writes} reason={DATASETS_WRITE_REFUSAL}>\n <Button size=\"small\" onClick={handleOpenRecord(record)}>\n {'Edit'}\n </Button>\n </BlockedControl>\n <BlockedControl blocked={blocked.writes} reason={DATASETS_WRITE_REFUSAL}>\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 recordFilter,\n blocked.writes,\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 return (\n <CardDisplay\n header={'Data'}\n help={pluginDocsHelp('datasets', { anchor: '#filter-records' })}\n contentGutterX\n contentGutterY\n contentBordered=\"all\"\n >\n <Stack spacing={1.5}>\n {orgId ? (\n <Typography variant=\"caption\" color=\"text.secondary\">\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 {datasets.length === 0 ? (\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 ) : (\n <Stack\n direction=\"row\"\n spacing={1}\n useFlexGap\n sx={{ alignItems: 'center', flexWrap: 'wrap' }}\n >\n {/* A scope, not a filter: it picks which collection the table\n walks, and the grid's own Filters panel narrows within it. */}\n <TextField\n select\n size=\"small\"\n label=\"Dataset\"\n value={selected?.$id ?? ''}\n onChange={(event) => setSelectedId(event.target.value)}\n sx={{ minWidth: 180 }}\n >\n {datasets.map((item) => (\n <MenuItem key={item.$id} value={item.$id}>\n {datasetDisplayName(item)}\n </MenuItem>\n ))}\n </TextField>\n <BlockedControl blocked={blocked.writes} reason={DATASETS_WRITE_REFUSAL}>\n <Button\n size=\"small\"\n color=\"primary\"\n onClick={handleOpenRecord()}\n >\n {'Add record'}\n </Button>\n </BlockedControl>\n <BlockedControl blocked={blocked.writes} reason={DATASETS_WRITE_REFUSAL}>\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 {canImport ? (\n <Button size=\"small\" onClick={handleImport}>\n {'Import'}\n </Button>\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) ? (\n <Button size=\"small\" onClick={handleExport}>\n {'Export'}\n </Button>\n ) : null}\n <BlockedControl blocked={blocked.deletes} reason={DATASETS_DELETE_REFUSAL}>\n <Button size=\"small\" color=\"error\" onClick={handleDeleteDataset}>\n {'Delete'}\n </Button>\n </BlockedControl>\n </Stack>\n )}\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 && (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 rows={recordColumnSort.rows}\n columnSort={recordColumnSort}\n columns={recordGridColumns}\n onOpen={(id) => setViewerId(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 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 direction=\"row\"\n spacing={1}\n useFlexGap\n sx={{ flexWrap: 'wrap' }}\n >\n <BlockedControl blocked={blocked.writes} reason={DATASETS_WRITE_REFUSAL}>\n <Button\n size=\"small\"\n variant=\"outlined\"\n color=\"primary\"\n onClick={handleOpenCreator}\n >\n {'Add dataset'}\n </Button>\n </BlockedControl>\n {datasets.length >= 2 ? (\n <BlockedControl blocked={blocked.writes} reason={DATASETS_WRITE_REFUSAL}>\n <Button size=\"small\" onClick={() => setJoiner({ a: '', b: '' })}>\n {'Add join collection'}\n </Button>\n </BlockedControl>\n ) : null}\n </Stack>\n </Stack>\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 <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 {datasetDisplayName(item)}\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={datasetsFromCache}\n seedUnreadable={datasetsStatus === 'error'}\n seedListen={datasetsListen}\n onClose={() => setSchemaOpen(false)}\n />\n </CardDisplay>\n )\n}\nHostDatasetsCard.displayName = 'HostDatasetsCard'\n\nexport default HostDatasetsCard\n"],"names":["TransferResumeImport","checkDatasetQuota","checkEntitlement","checkQuota","getCustomFieldType","pluginDocsHelp","useTransferLauncher","CardDisplay","useConfirmationContext","ListFilterChips","ListPagination","ListQueryNotices","listQueryRefusals","ListTable","listActionsColumn","QuotaReadoutComponent","listFilterGridColumns","useListGridFilter","useSnackbar","Timestamp","Alert","Button","Chip","Dialog","DialogActions","DialogContent","DialogTitle","MenuItem","Stack","TextField","Tooltip","Typography","collection","deleteDoc","deleteField","doc","getCountFromServer","getDoc","getDocs","limit","query","where","setDoc","writeBatch","useCallback","useEffect","useMemo","useState","useListColumnSort","useFirestore","useFirestoreCollection","useHostActivityLogger","useOrgDataScope","usePagedCollection","useScopeTokens","useUser","listQueryConstraints","authorizedFetch","DatasetSchemaDialog","DatasetRecordDialog","DatasetRecordSiteContext","datasetRecordFilter","planRecordQuery","recordColumn","coerceDocumentValues","datasetIntegrityUpdate","datasetValueToInput","effectiveDatasetModel","formatDatasetValue","modelFromFieldEntries","validateDocument","fillRecordAddresses","planReferenceFixups","referencingFieldIds","restrictedDeleteMessage","BlockedControl","datasetListScope","DATASETS_DELETE_REFUSAL","DATASETS_WRITE_REFUSAL","useDatasetWritesBlocked","DATASET_SAMPLE_RECORD_NOTE","datasetDisplayName","isSampleDatasetRecord","parseDatasetFieldEntries","datasetTransferResourceKey","NO_QUERY_SORTS","NO_DATASETS","DATASET_LIST_WINDOW","datasetRow","snapshot","$id","id","data","newDatasetSharingNote","siteOnly","HostDatasetsCard","props","datasets","hostId","scope","dataScope","orgId","tokens","scopeTokens","orgWide","viewerOrgWide","loaded","scopeLoaded","pageHostId","undefined","reachScope","listScope","memberScope","scopeReady","Boolean","firestore","blocked","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","datasetDocs","status","datasetsStatus","fromCache","datasetsFromCache","listen","datasetsListen","idField","sort","a","b","localeCompare","selectedId","setSelectedId","schemaOpen","setSchemaOpen","selected","find","item","model","fields","order","recordFilter","gridFilter","selectFields","recordClauses","clauses","filter","clause","some","field","column","recordPlan","searchWords","recordPlanKey","filters","plan","orderBy","rows","records","hasMore","hasMoreRecords","page","recordPage","setPage","setRecordPage","pageSize","recordPageSize","setPageSize","setRecordPageSize","pageLimit","recordRefusals","refused","options","filteringRecords","length","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","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","viewerRecord","record","editor","setEditor","handleOpenRecord","values","default","errors","sample","handleSaveRecord","coerced","keys","prev","recordRef","updatedAt","now","mergeFields","handleDeleteRecord","alsoChanged","referencing","reach","other","otherModel","holders","start","updates","batch","update","slice","holder","ref","commit","add","transfer","transferTarget","resource","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","writes","reason","width","recordPageSorts","recordSortHeaders","recordColumnSort","sorts","pageSorts","header","help","anchor","contentGutterX","contentGutterY","contentBordered","useFlexGap","flexWrap","select","onChange","event","deletes","ready","used","noun","setClauses","notices","aria-label","columnSort","columns","onOpen","hideFooter","filterMode","filterModel","onFilterModelChange","quickFilter","noRowsLabel","rowCount","onPageChange","onPageSizeChange","open","onClose","maxWidth","fullWidth","display","flexDirection","gap","autoFocus","mt","helperText","disabled","resolveReference","onEdit","severity","Provider","index","setValue","nextValue","common","customFieldType","customType","Input","CustomInput","next","validation","multiple","selectedIds","split","part","slotProps","inputLabel","shrink","side","seedFromCache","seedUnreadable","seedListen"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,SAASA,oBAAoB,QAAQ,gDAA+C;AACpF,SAEEC,iBAAiB,EACjBC,gBAAgB,EAChBC,UAAU,EACVC,kBAAkB,EAClBC,cAAc,EACdC,mBAAmB,QACd,eAAc;AACrB,SAASC,WAAW,EAAEC,sBAAsB,QAAQ,uBAAsB;A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A,MAAQ,CAACsL,KAAK,mBAAI;oCACzBrD,UAAU,CAACC,QACTjI,UAAU,CAAC6D,OACTA,OAAO,aAAKA;gDAAM,CAACwH,KAAK,EAAEpD,MAAM9H,MAAM,CAACuC,KAAK;iDAAKmB;8CAIpD1M,SAASoI,GAAG,CAAC,CAAClE,qBACb,KAACxI;4CAAwB6P,OAAOrH,KAAKzE,GAAG;sDACrCT,mBAAmBkF;2CADPA,KAAKzE,GAAG;mCAZpByU;;;;kCAmBX,MAAC3Y;;0CACC,KAACH;gCAAOuU,SAAS,IAAM9G,UAAU;0CAAQ;;0CACzC,KAACzN;gCACCuM,SAAQ;gCACRoC,OAAM;gCACN6I,UACE,CAAC5R,cAAc,EAAC4H,0BAAAA,OAAQnF,CAAC,KAAI,EAACmF,0BAAAA,OAAQlF,CAAC,KAAIkF,OAAOnF,CAAC,KAAKmF,OAAOlF,CAAC;gCAElEiM,SAAS7G;0CAER;;;;;;0BAIP,KAACrL;gBACCwC,QAAQA;gBACRG,KAAK,EAAEA,gBAAAA,QAASQ;gBAChB0N,SAASxK,cAAcE,WAAWA,WAAW;gBAC7ChE,UAAUyK;gBACV,kEAAkE;gBAClE,mEAAmE;gBACnE,mDAAmD;gBACnDlD,aAAaA;gBACb4M,eAAe/Q;gBACfgR,gBAAgBlR,mBAAmB;gBACnCmR,YAAY/Q;gBACZ6O,SAAS,IAAMpO,cAAc;;;;AAIrC;AACAjE,iBAAiByI,WAAW,GAAG;AAE/B,eAAezI,iBAAgB"}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2026 Aglyn LLC
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/
|
|
17
|
+
import { type OrgPermission, resolveOrgPermissions } from '@aglyn/aglyn/app-utils/org-permissions';
|
|
18
|
+
/** What the doors read off a membership document. */
|
|
19
|
+
type DatasetWriter = NonNullable<Parameters<typeof resolveOrgPermissions>[0]> & {
|
|
20
|
+
resolvedPermissions?: Readonly<Record<string, unknown>>;
|
|
21
|
+
permissions?: Readonly<Record<string, unknown>>;
|
|
22
|
+
};
|
|
23
|
+
/** Creating, editing and sharing datasets, and every record write. */
|
|
24
|
+
export declare const DATASETS_WRITE_PERMISSION: OrgPermission;
|
|
25
|
+
/** Deleting a whole dataset, which the erase route asks. */
|
|
26
|
+
export declare const DATASETS_DELETE_PERMISSION: OrgPermission;
|
|
27
|
+
export declare const DATASETS_WRITE_REFUSAL: string;
|
|
28
|
+
export declare const DATASETS_DELETE_REFUSAL: string;
|
|
29
|
+
/**
|
|
30
|
+
* A member's answer for a dataset key (AGL-4047), as the rules' `canWriteOrgDatasets`
|
|
31
|
+
* and the routes' `memberHasOrgPermission` read it: the decision written on
|
|
32
|
+
* `resolvedPermissions`, or, for a member the projection never stamped, on their
|
|
33
|
+
* own `permissions`; else their workspace role's default. A workspace key: no
|
|
34
|
+
* site narrows it, so a site's Data page asks the same thing as the workspace's.
|
|
35
|
+
*/
|
|
36
|
+
export declare function holdsDatasetPermission(member: DatasetWriter, permission: OrgPermission): boolean;
|
|
37
|
+
/**
|
|
38
|
+
* Which dataset writes the signed-in member is known not to hold, so those
|
|
39
|
+
* controls switch off with the permission named rather than failing on save.
|
|
40
|
+
* Neither is blocked until the read lands, nor for a reader with no membership,
|
|
41
|
+
* who is staff. Not a security boundary: the rules and routes refuse regardless.
|
|
42
|
+
*/
|
|
43
|
+
export declare function useDatasetWritesBlocked(orgId: string | null | undefined): {
|
|
44
|
+
writes: boolean;
|
|
45
|
+
deletes: boolean;
|
|
46
|
+
};
|
|
47
|
+
export {};
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2026 Aglyn LLC
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/ import { permissionRefusalText, resolveOrgPermissions } from "@aglyn/aglyn/app-utils/org-permissions";
|
|
17
|
+
import { useFirestore, useFirestoreDoc, useUser } from "@aglyn/tenant-feature-instance";
|
|
18
|
+
import { doc } from "firebase/firestore";
|
|
19
|
+
/** Creating, editing and sharing datasets, and every record write. */ export const DATASETS_WRITE_PERMISSION = 'data.manage';
|
|
20
|
+
/** Deleting a whole dataset, which the erase route asks. */ export const DATASETS_DELETE_PERMISSION = 'org.eraseRecords';
|
|
21
|
+
export const DATASETS_WRITE_REFUSAL = permissionRefusalText(DATASETS_WRITE_PERMISSION);
|
|
22
|
+
export const DATASETS_DELETE_REFUSAL = permissionRefusalText(DATASETS_DELETE_PERMISSION);
|
|
23
|
+
/**
|
|
24
|
+
* A member's answer for a dataset key (AGL-4047), as the rules' `canWriteOrgDatasets`
|
|
25
|
+
* and the routes' `memberHasOrgPermission` read it: the decision written on
|
|
26
|
+
* `resolvedPermissions`, or, for a member the projection never stamped, on their
|
|
27
|
+
* own `permissions`; else their workspace role's default. A workspace key: no
|
|
28
|
+
* site narrows it, so a site's Data page asks the same thing as the workspace's.
|
|
29
|
+
*/ export function holdsDatasetPermission(member, permission) {
|
|
30
|
+
var _member_resolvedPermissions;
|
|
31
|
+
var _this;
|
|
32
|
+
const stamped = (_this = (_member_resolvedPermissions = member.resolvedPermissions) != null ? _member_resolvedPermissions : member.permissions) == null ? void 0 : _this[permission];
|
|
33
|
+
if (typeof stamped === 'boolean') return stamped;
|
|
34
|
+
return resolveOrgPermissions(member)[permission] === true;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Which dataset writes the signed-in member is known not to hold, so those
|
|
38
|
+
* controls switch off with the permission named rather than failing on save.
|
|
39
|
+
* Neither is blocked until the read lands, nor for a reader with no membership,
|
|
40
|
+
* who is staff. Not a security boundary: the rules and routes refuse regardless.
|
|
41
|
+
*/ export function useDatasetWritesBlocked(orgId) {
|
|
42
|
+
var _ref;
|
|
43
|
+
const firestore = useFirestore();
|
|
44
|
+
const { data: user } = useUser();
|
|
45
|
+
const uid = (_ref = user == null ? void 0 : user.uid) != null ? _ref : '';
|
|
46
|
+
const { data: member, status } = useFirestoreDoc(()=>orgId && uid ? doc(firestore, 'orgs', orgId, 'members', uid) : null, [
|
|
47
|
+
firestore,
|
|
48
|
+
orgId,
|
|
49
|
+
uid
|
|
50
|
+
]);
|
|
51
|
+
if (status !== 'success' || !member) return {
|
|
52
|
+
writes: false,
|
|
53
|
+
deletes: false
|
|
54
|
+
};
|
|
55
|
+
return {
|
|
56
|
+
writes: !holdsDatasetPermission(member, DATASETS_WRITE_PERMISSION),
|
|
57
|
+
deletes: !holdsDatasetPermission(member, DATASETS_DELETE_PERMISSION)
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
//# sourceMappingURL=use-dataset-writes-blocked.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/data/src/lib/components/use-dataset-writes-blocked.ts"],"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\nimport {\n type OrgPermission,\n permissionRefusalText,\n resolveOrgPermissions,\n} from '@aglyn/aglyn/app-utils/org-permissions'\nimport { useFirestore, useFirestoreDoc, useUser } from '@aglyn/tenant-feature-instance'\nimport { doc } from 'firebase/firestore'\n\n/** What the doors read off a membership document. */\ntype DatasetWriter = NonNullable<Parameters<typeof resolveOrgPermissions>[0]> & {\n resolvedPermissions?: Readonly<Record<string, unknown>>\n permissions?: Readonly<Record<string, unknown>>\n}\n\n/** Creating, editing and sharing datasets, and every record write. */\nexport const DATASETS_WRITE_PERMISSION: OrgPermission = 'data.manage'\n/** Deleting a whole dataset, which the erase route asks. */\nexport const DATASETS_DELETE_PERMISSION: OrgPermission = 'org.eraseRecords'\n\nexport const DATASETS_WRITE_REFUSAL = permissionRefusalText(DATASETS_WRITE_PERMISSION)\nexport const DATASETS_DELETE_REFUSAL = permissionRefusalText(DATASETS_DELETE_PERMISSION)\n\n/**\n * A member's answer for a dataset key (AGL-4047), as the rules' `canWriteOrgDatasets`\n * and the routes' `memberHasOrgPermission` read it: the decision written on\n * `resolvedPermissions`, or, for a member the projection never stamped, on their\n * own `permissions`; else their workspace role's default. A workspace key: no\n * site narrows it, so a site's Data page asks the same thing as the workspace's.\n */\nexport function holdsDatasetPermission(member: DatasetWriter, permission: OrgPermission): boolean {\n const stamped = (member.resolvedPermissions ?? member.permissions)?.[permission]\n if (typeof stamped === 'boolean') return stamped\n return resolveOrgPermissions(member)[permission] === true\n}\n\n/**\n * Which dataset writes the signed-in member is known not to hold, so those\n * controls switch off with the permission named rather than failing on save.\n * Neither is blocked until the read lands, nor for a reader with no membership,\n * who is staff. Not a security boundary: the rules and routes refuse regardless.\n */\nexport function useDatasetWritesBlocked(orgId: string | null | undefined): {\n writes: boolean\n deletes: boolean\n} {\n const firestore = useFirestore()\n const { data: user } = useUser()\n const uid = (user as { uid?: string } | undefined)?.uid ?? ''\n const { data: member, status } = useFirestoreDoc<DatasetWriter>(\n () => (orgId && uid ? doc(firestore, 'orgs', orgId, 'members', uid) : null),\n [firestore, orgId, uid],\n )\n if (status !== 'success' || !member) return { writes: false, deletes: false }\n return {\n writes: !holdsDatasetPermission(member, DATASETS_WRITE_PERMISSION),\n deletes: !holdsDatasetPermission(member, DATASETS_DELETE_PERMISSION),\n }\n}\n"],"names":["permissionRefusalText","resolveOrgPermissions","useFirestore","useFirestoreDoc","useUser","doc","DATASETS_WRITE_PERMISSION","DATASETS_DELETE_PERMISSION","DATASETS_WRITE_REFUSAL","DATASETS_DELETE_REFUSAL","holdsDatasetPermission","member","permission","stamped","resolvedPermissions","permissions","useDatasetWritesBlocked","orgId","firestore","data","user","uid","status","writes","deletes"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAEEA,qBAAqB,EACrBC,qBAAqB,QAChB,yCAAwC;AAC/C,SAASC,YAAY,EAAEC,eAAe,EAAEC,OAAO,QAAQ,iCAAgC;AACvF,SAASC,GAAG,QAAQ,qBAAoB;AAQxC,oEAAoE,GACpE,OAAO,MAAMC,4BAA2C,cAAa;AACrE,0DAA0D,GAC1D,OAAO,MAAMC,6BAA4C,mBAAkB;AAE3E,OAAO,MAAMC,yBAAyBR,sBAAsBM,2BAA0B;AACtF,OAAO,MAAMG,0BAA0BT,sBAAsBO,4BAA2B;AAExF;;;;;;CAMC,GACD,OAAO,SAASG,uBAAuBC,MAAqB,EAAEC,UAAyB;QACpED;QAAAA;IAAjB,MAAME,WAAWF,SAAAA,8BAAAA,OAAOG,mBAAmB,YAA1BH,8BAA8BA,OAAOI,WAAW,qBAAjD,AAACJ,KAAmD,CAACC,WAAW;IAChF,IAAI,OAAOC,YAAY,WAAW,OAAOA;IACzC,OAAOZ,sBAAsBU,OAAO,CAACC,WAAW,KAAK;AACvD;AAEA;;;;;CAKC,GACD,OAAO,SAASI,wBAAwBC,KAAgC;;IAItE,MAAMC,YAAYhB;IAClB,MAAM,EAAEiB,MAAMC,IAAI,EAAE,GAAGhB;IACvB,MAAMiB,cAAOD,wBAAD,AAACA,KAAuCC,GAAG,mBAAI;IAC3D,MAAM,EAAEF,MAAMR,MAAM,EAAEW,MAAM,EAAE,GAAGnB,gBAC/B,IAAOc,SAASI,MAAMhB,IAAIa,WAAW,QAAQD,OAAO,WAAWI,OAAO,MACtE;QAACH;QAAWD;QAAOI;KAAI;IAEzB,IAAIC,WAAW,aAAa,CAACX,QAAQ,OAAO;QAAEY,QAAQ;QAAOC,SAAS;IAAM;IAC5E,OAAO;QACLD,QAAQ,CAACb,uBAAuBC,QAAQL;QACxCkB,SAAS,CAACd,uBAAuBC,QAAQJ;IAC3C;AACF"}
|
|
@@ -15,6 +15,22 @@
|
|
|
15
15
|
* limitations under the License.
|
|
16
16
|
*/
|
|
17
17
|
import { type PluginRecordListSource } from '@aglyn/aglyn/plugin-manager/plugin-record-lists';
|
|
18
|
+
/**
|
|
19
|
+
* The `visibleTo` tokens a list of datasets asks for, or `null` for no filter.
|
|
20
|
+
*
|
|
21
|
+
* Narrowed to a site, the site decides, whoever is looking: an owner who
|
|
22
|
+
* reaches every dataset still sees only that site's and the workspace-wide
|
|
23
|
+
* ones on that site's pages. With no site, the member's own reach decides:
|
|
24
|
+
* their scope tokens, or `null` for an organization-wide member, who reads
|
|
25
|
+
* everything.
|
|
26
|
+
*
|
|
27
|
+
* A site's tokens are a subset of those of anyone who can open the site, so
|
|
28
|
+
* the query also satisfies the `canReadScoped` rule for a site collaborator.
|
|
29
|
+
*/
|
|
30
|
+
export declare function datasetListScope(request: {
|
|
31
|
+
hostId?: string | null;
|
|
32
|
+
memberScope?: readonly string[] | null;
|
|
33
|
+
}): readonly string[] | null;
|
|
18
34
|
/**
|
|
19
35
|
* The workspace's datasets, listed in the console for another plugin's picker
|
|
20
36
|
* or check (AGL-3080) — an automation step choosing the dataset it writes to,
|
|
@@ -18,6 +18,21 @@ import { registerPluginRecordListSource } from "@aglyn/aglyn/plugin-manager/plug
|
|
|
18
18
|
import { collection, documentId, limit, orderBy, query, where } from "firebase/firestore";
|
|
19
19
|
import { BUNDLE_ID } from "../constants/bundle-common.js";
|
|
20
20
|
import { datasetIndexedRecord } from "./dataset-record.js";
|
|
21
|
+
/**
|
|
22
|
+
* The `visibleTo` tokens a list of datasets asks for, or `null` for no filter.
|
|
23
|
+
*
|
|
24
|
+
* Narrowed to a site, the site decides, whoever is looking: an owner who
|
|
25
|
+
* reaches every dataset still sees only that site's and the workspace-wide
|
|
26
|
+
* ones on that site's pages. With no site, the member's own reach decides:
|
|
27
|
+
* their scope tokens, or `null` for an organization-wide member, who reads
|
|
28
|
+
* everything.
|
|
29
|
+
*
|
|
30
|
+
* A site's tokens are a subset of those of anyone who can open the site, so
|
|
31
|
+
* the query also satisfies the `canReadScoped` rule for a site collaborator.
|
|
32
|
+
*/ export function datasetListScope(request) {
|
|
33
|
+
var _request_memberScope;
|
|
34
|
+
return request.hostId ? scopeTokensForHost(request.hostId) : (_request_memberScope = request.memberScope) != null ? _request_memberScope : null;
|
|
35
|
+
}
|
|
21
36
|
/**
|
|
22
37
|
* The workspace's datasets, listed in the console for another plugin's picker
|
|
23
38
|
* or check (AGL-3080) — an automation step choosing the dataset it writes to,
|
|
@@ -39,9 +54,8 @@ import { datasetIndexedRecord } from "./dataset-record.js";
|
|
|
39
54
|
* server index's shape.
|
|
40
55
|
*/ export const datasetRecordListSource = {
|
|
41
56
|
query (firestore, request) {
|
|
42
|
-
var _request_memberScope;
|
|
43
57
|
if (!request.orgId) return null;
|
|
44
|
-
const scope =
|
|
58
|
+
const scope = datasetListScope(request);
|
|
45
59
|
return query(collection(firestore, 'orgs', request.orgId, 'datasets'), ...request.installedFrom ? [
|
|
46
60
|
where('source.listingId', '==', request.installedFrom)
|
|
47
61
|
] : [], ...scope ? [
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/data/src/lib/model/dataset-record-list.ts"],"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\nimport { scopeTokensForHost } from '@aglyn/aglyn/app-utils/scope-tokens'\nimport {\n registerPluginRecordListSource,\n type PluginRecordListSource,\n} from '@aglyn/aglyn/plugin-manager/plugin-record-lists'\nimport {\n collection,\n documentId,\n limit,\n orderBy,\n query,\n where,\n} from 'firebase/firestore'\nimport { BUNDLE_ID } from '../constants/bundle-common'\nimport { datasetIndexedRecord } from './dataset-record'\n\n/**\n * The workspace's datasets, listed in the console for another plugin's picker\n * or check (AGL-3080) — an automation step choosing the dataset it writes to,\n * a reference check confirming one still exists.\n *\n * Narrowed to a site (`hostId`), the query asks only for the datasets shared\n * with it, by the site's scope tokens: an automation runs on the site, so it\n * may only reach datasets the site can use, and the filter is the one the\n * security rules require of a member scoped to the site. With no site, a\n * member who is not organization-wide (`memberScope`) is asked for the ones\n * shared with any site they reach — the rules refuse them an unfiltered\n * list — and an organization-wide reader lists the organization's own.\n * `installedFrom` keeps the ones installed from that listing, by the\n * `source.listingId` every dataset install stamps.\n *\n * Ordered by document id, which the automatic index serves beside the\n * `visibleTo` filter, and the composite index on (`source.listingId`,\n * `visibleTo`) beside both. Each record is `datasetIndexedRecord`'s, the\n * server index's shape.\n */\nexport const datasetRecordListSource: PluginRecordListSource = {\n query(firestore, request) {\n if (!request.orgId) return null\n const scope =
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/data/src/lib/model/dataset-record-list.ts"],"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\nimport { scopeTokensForHost } from '@aglyn/aglyn/app-utils/scope-tokens'\nimport {\n registerPluginRecordListSource,\n type PluginRecordListSource,\n} from '@aglyn/aglyn/plugin-manager/plugin-record-lists'\nimport {\n collection,\n documentId,\n limit,\n orderBy,\n query,\n where,\n} from 'firebase/firestore'\nimport { BUNDLE_ID } from '../constants/bundle-common'\nimport { datasetIndexedRecord } from './dataset-record'\n\n/**\n * The `visibleTo` tokens a list of datasets asks for, or `null` for no filter.\n *\n * Narrowed to a site, the site decides, whoever is looking: an owner who\n * reaches every dataset still sees only that site's and the workspace-wide\n * ones on that site's pages. With no site, the member's own reach decides:\n * their scope tokens, or `null` for an organization-wide member, who reads\n * everything.\n *\n * A site's tokens are a subset of those of anyone who can open the site, so\n * the query also satisfies the `canReadScoped` rule for a site collaborator.\n */\nexport function datasetListScope(request: {\n hostId?: string | null\n memberScope?: readonly string[] | null\n}): readonly string[] | null {\n return request.hostId ? scopeTokensForHost(request.hostId) : (request.memberScope ?? null)\n}\n\n/**\n * The workspace's datasets, listed in the console for another plugin's picker\n * or check (AGL-3080) — an automation step choosing the dataset it writes to,\n * a reference check confirming one still exists.\n *\n * Narrowed to a site (`hostId`), the query asks only for the datasets shared\n * with it, by the site's scope tokens: an automation runs on the site, so it\n * may only reach datasets the site can use, and the filter is the one the\n * security rules require of a member scoped to the site. With no site, a\n * member who is not organization-wide (`memberScope`) is asked for the ones\n * shared with any site they reach — the rules refuse them an unfiltered\n * list — and an organization-wide reader lists the organization's own.\n * `installedFrom` keeps the ones installed from that listing, by the\n * `source.listingId` every dataset install stamps.\n *\n * Ordered by document id, which the automatic index serves beside the\n * `visibleTo` filter, and the composite index on (`source.listingId`,\n * `visibleTo`) beside both. Each record is `datasetIndexedRecord`'s, the\n * server index's shape.\n */\nexport const datasetRecordListSource: PluginRecordListSource = {\n query(firestore, request) {\n if (!request.orgId) return null\n const scope = datasetListScope(request)\n return query(\n collection(firestore, 'orgs', request.orgId, 'datasets'),\n ...(request.installedFrom ? [where('source.listingId', '==', request.installedFrom)] : []),\n ...(scope ? [where('visibleTo', 'array-contains-any', [...scope])] : []),\n orderBy(documentId()),\n limit(request.limit),\n )\n },\n record: datasetIndexedRecord,\n}\n\n/** Called from the console registrar, owner named for a spec that calls it directly. */\nexport function registerDatasetRecordList(): void {\n registerPluginRecordListSource('dataset', datasetRecordListSource, { pluginId: BUNDLE_ID })\n}\n"],"names":["scopeTokensForHost","registerPluginRecordListSource","collection","documentId","limit","orderBy","query","where","BUNDLE_ID","datasetIndexedRecord","datasetListScope","request","hostId","memberScope","datasetRecordListSource","firestore","orgId","scope","installedFrom","record","registerDatasetRecordList","pluginId"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,kBAAkB,QAAQ,sCAAqC;AACxE,SACEC,8BAA8B,QAEzB,kDAAiD;AACxD,SACEC,UAAU,EACVC,UAAU,EACVC,KAAK,EACLC,OAAO,EACPC,KAAK,EACLC,KAAK,QACA,qBAAoB;AAC3B,SAASC,SAAS,QAAQ,gCAA4B;AACtD,SAASC,oBAAoB,QAAQ,sBAAkB;AAEvD;;;;;;;;;;;CAWC,GACD,OAAO,SAASC,iBAAiBC,OAGhC;QAC+DA;IAA9D,OAAOA,QAAQC,MAAM,GAAGZ,mBAAmBW,QAAQC,MAAM,KAAKD,uBAAAA,QAAQE,WAAW,YAAnBF,uBAAuB;AACvF;AAEA;;;;;;;;;;;;;;;;;;;CAmBC,GACD,OAAO,MAAMG,0BAAkD;IAC7DR,OAAMS,SAAS,EAAEJ,OAAO;QACtB,IAAI,CAACA,QAAQK,KAAK,EAAE,OAAO;QAC3B,MAAMC,QAAQP,iBAAiBC;QAC/B,OAAOL,MACLJ,WAAWa,WAAW,QAAQJ,QAAQK,KAAK,EAAE,gBACzCL,QAAQO,aAAa,GAAG;YAACX,MAAM,oBAAoB,MAAMI,QAAQO,aAAa;SAAE,GAAG,EAAE,KACrFD,QAAQ;YAACV,MAAM,aAAa,sBAAsB;mBAAIU;aAAM;SAAE,GAAG,EAAE,EACvEZ,QAAQF,eACRC,MAAMO,QAAQP,KAAK;IAEvB;IACAe,QAAQV;AACV,EAAC;AAED,sFAAsF,GACtF,OAAO,SAASW;IACdnB,+BAA+B,WAAWa,yBAAyB;QAAEO,UAAUb;IAAU;AAC3F"}
|