diff --git a/.changeset/35619-user-actions-export-csv-enforced.md b/.changeset/35619-user-actions-export-csv-enforced.md new file mode 100644 index 00000000000..e652cf84caf --- /dev/null +++ b/.changeset/35619-user-actions-export-csv-enforced.md @@ -0,0 +1,27 @@ +--- +'@objectstack/spec': minor +'@object-ui/core': minor +'@object-ui/plugin-grid': minor +'@object-ui/plugin-list': minor +'@object-ui/plugin-report': minor +'@objectstack/platform-objects': patch +--- + +feat: an object's `userActions.exportCsv: false` hides the console's Export entry + +Clause-②: yes +Metadata-protocol: semantic + +`userActions.exportCsv` on an object now does what the Studio object form says it does. Set to `false`, the console offers no Export entry for downloading that object's data, in any of its formats (CSV, XLSX, JSON): + +- the object grid hides its toolbar Export menu, and the table's own CSV button that `operations.export: true` turns on; +- the list view hides Export in both toolbar forms, the wide toolbar's button and the Display panel's export footer; +- a dataset report hides its Export control when the dataset's base object sets it. + +A view's export of the picture it draws is not covered: a Gantt view's PNG and PDF buttons stay. + +Every surface reads one verdict, the new `isObjectExportOffered(objectSchema, effectiveApiOperations)` from `@object-ui/core`: the authored `exportCsv` over the object's `managedBy` default, ANDed with the caller's effective `export` API operation. Before this change the grid's toolbar menu, the list view and the report read the effective operation but not the object's bit, and the grid's table CSV button read neither half (only `operations.export`), so `exportCsv: false` changed nothing. Export is a read, so the verdict is not a row of `AFFORDANCE_GRANTS` and asks no `can(object, verb)`: the caller's export grant reaches the console through the effective `export` operation, which the server derives from `list` and `allowExport`. + +An object that does not author the key keeps its Export entries, since every `managedBy` bucket still defaults `exportCsv` to `true` (ADR-0103), with one change: the grid's table CSV button (`operations.export: true`) now also follows the effective `export` operation, as the toolbar menu beside it already did. So a viewer whose effective operations exclude `export` no longer sees that button, even on an object that authors nothing. The setting hides the entry and is not a permission: no export request is refused because of it, and who may export is still the permission set's `allowExport`. The report reads the base object's definition through the report's data source, and a report whose source cannot serve one keeps its Export control. + +The spec's `exportCsv` description and the Studio form's help text now say this; the form's English help text bundle in `@objectstack/platform-objects` is regenerated to match, and the translated locales keep their wording. The liveness ledger grades `userActions.exportCsv` `live`, so an authored `exportCsv: true` no longer raises the `liveness-dead-property` warning at `os lint` / `os validate`. Nothing needs migrating. diff --git a/content/docs/data-modeling/objects.mdx b/content/docs/data-modeling/objects.mdx index 1f8302878ea..eca6eab7468 100644 --- a/content/docs/data-modeling/objects.mdx +++ b/content/docs/data-modeling/objects.mdx @@ -333,7 +333,7 @@ indexes: [ | :--- | :--- | :--- | | `isSystem` | `boolean` | System object, protected from deletion (default: `false`) | | `managedBy` | `enum` | Lifecycle bucket that sets the default CRUD affordances and write policy — `'platform'` (default), `'config'`, `'system-data'`, `'engine-owned'`, `'append-only'`, `'synced'`, `'better-auth'`. See [Lifecycle bucket](#lifecycle-bucket-managedby) below. | -| `userActions` | `object` | Per-object override of the CRUD affordances the `managedBy` default implies — `{ create?, edit?, delete?, import?, exportCsv? }`. This is what NARROWS a `system-data` object, opens CSV `import` on one, or opens a verb on an `engine-owned`/`append-only` one. See [Lifecycle bucket](#lifecycle-bucket-managedby). | +| `userActions` | `object` | Per-object override of the CRUD affordances the `managedBy` default implies — `{ create?, edit?, delete?, import?, exportCsv? }`. This is what NARROWS a `system-data` object, opens CSV `import` on one, or opens a verb on an `engine-owned`/`append-only` one. `exportCsv: false` hides the Export entry that downloads the object's data (CSV, XLSX or JSON) on its grids, list views and dataset reports; a Gantt view's PNG / PDF export of its chart is not covered. It refuses no export request, since who may export is the permission set's `allowExport`. See [Lifecycle bucket](#lifecycle-bucket-managedby). | | `sharingModel` | `enum` | Org-Wide Default record visibility (ADR-0055/0056/0090). Canonical four only: `'private'`, `'public_read'`, `'public_read_write'`, `'controlled_by_parent'` (detail visibility derived from its master). The legacy aliases (`'read'`, `'read_write'`, `'full'`) were removed from the enum (ADR-0090 D4) — authoring rejects them. Unset on a custom object resolves to `'private'` (ADR-0090 D1) | | `ownership` | `enum` | Record-ownership model: `'user'` (default — injects the reassignable `owner_id` lookup, engaging owner-scoped RLS, "My" views and owner reports, plus `owning_business_unit_id`), `'business_unit'` (owned by an org unit rather than a person — injects `owning_business_unit_id` and deliberately **no** `owner_id`; ADR-0117 D1), `'org'`, or `'none'` (no per-record owner of either kind — Dataverse-style catalog / junction tables). Distinct from the package `own`/`extend` contribution kind. | | `validations` | `ValidationRule[]` | Object-level validation rules (see [Validation](/docs/data-modeling/validation)) | diff --git a/content/docs/frontend/plugins/plugin-list.mdx b/content/docs/frontend/plugins/plugin-list.mdx index 5a11225910c..3ccca7ce26b 100644 --- a/content/docs/frontend/plugins/plugin-list.mdx +++ b/content/docs/frontend/plugins/plugin-list.mdx @@ -72,6 +72,20 @@ console passes `false` for a view authored `navigation: { mode: 'none' }` or data API serves no single-record read (objectstack#33317, objectstack#33548, objectstack#33549). +## The object's Export switch + +The list's Export entry (the wide toolbar's button and the Display panel's +footer) follows the object as well as the view. An object that sets +`userActions.exportCsv: false` gets no Export entry for downloading its data, +in any of the list's formats (CSV, XLSX, JSON); the object grid and a dataset +report on that object hide theirs too. All three read one +verdict, `isObjectExportOffered(objectDef, effectiveApiOperations)` from +`@object-ui/core`: the authored switch over the object's `managedBy` +default, ANDed with the caller's effective `export` API operation. Unset, the +switch is on in every bucket. It hides the entry and is not a permission: who +may export is the permission set's `allowExport`. A Gantt view's PNG and PDF +export of the chart it draws is not covered by the switch. + ## Status This plugin is part of the v3.3.0 release. For full API reference and usage diff --git a/content/docs/references/data/object.mdx b/content/docs/references/data/object.mdx index b2ee4e1b037..543e017a1ce 100644 --- a/content/docs/references/data/object.mdx +++ b/content/docs/references/data/object.mdx @@ -205,7 +205,7 @@ const result = ApiMethod.parse(data); | **import** | `boolean \| { enabled?: boolean; visibleWhen?: string \| object; disabledWhen?: string \| object }` | optional | Show CSV import wizard entry. Boolean, or an object adding visibleWhen/disabledWhen CEL predicates evaluated once per toolbar against the record in scope (the host record on a related list). | | **edit** | `boolean \| { enabled?: boolean; visibleWhen?: string \| object; disabledWhen?: string \| object }` | optional | Allow inline / form edit of existing rows. Boolean, or an object adding per-record visibleWhen/disabledWhen CEL predicates. | | **delete** | `boolean \| { enabled?: boolean; visibleWhen?: string \| object; disabledWhen?: string \| object }` | optional | Show row-level delete + bulk delete. Boolean, or an object adding per-record visibleWhen/disabledWhen CEL predicates. | -| **exportCsv** | `boolean` | optional | Show CSV export entry. | +| **exportCsv** | `boolean` | optional | Show the Export entry that downloads this object's data as CSV, XLSX or JSON: the grid's Export menu and its table CSV button, the list view's Export, and a dataset report's Export over this object; false hides it. A view's export of the picture it draws (the Gantt chart's PNG / PDF) is not covered. Omitted: shown, in every managedBy bucket. It hides the entry and refuses no export request: who may export is the permission set's allowExport. | | **transfer** | `boolean \| { enabled?: boolean; visibleWhen?: string \| object; disabledWhen?: string \| object }` | optional | Offer the Change Owner action (single and bulk) on records of this object. Boolean, or an object adding per-record visibleWhen/disabledWhen CEL predicates. Omitted: on, except off on a controlled_by_parent detail. Offered only where the platform injects a reassignable owner_id that is provable and not declared readonly (ownership user or omitted, no managedBy, not a sys_ object; an external object declares owner_id or maps a remote column onto it); enabled: true elsewhere is refused. Gates the action, not a plain owner_id write. Resolved by resolveUserActionTransfer. | ### Nested Shape: `Object.systemFields` diff --git a/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts index fc9a6a87748..64a90b9f383 100644 --- a/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts @@ -455,7 +455,7 @@ export const enMetadataForms: NonNullable = { }, "userActions.exportCsv": { label: "Export CSV", - helpText: "The CSV export entry. Unset: shown, since every managedBy bucket offers export." + helpText: "The Export entry that downloads this object's data (CSV, XLSX or JSON) on its grids, list views and dataset reports: on shows it, off hides it. A Gantt chart's PNG / PDF export is not covered. Unset: shown, since every managedBy bucket offers export. It is not a permission: who may export is the permission set's allowExport." }, "userActions.transfer": { label: "Change Owner", diff --git a/packages/spec/liveness/object.json b/packages/spec/liveness/object.json index 0d8ea0f8c84..f367a2b1c82 100644 --- a/packages/spec/liveness/object.json +++ b/packages/spec/liveness/object.json @@ -245,7 +245,7 @@ "status": "live", "verifiedAt": "2026-11-19", "evidence": "packages/spec/src/data/object.zod.ts#resolveCrudAffordances (collapses `obj.userActions` onto the managedBy bucket's default row, the one resolution of the five CRUD entries); ui/packages/core/src/utils/managedBy.ts#resolveEffectiveCrudAffordances (hands the object's `userActions` to it and intersects the answer with the server's effective API operations)", - "note": "Drilled 2026-11-19 when `transfer` (the Change Owner switch, ruling 7000907189 point 1, card #35401) landed beside the five CRUD entries with a different verdict: the container used to carry one blanket `live` (\"objectui ObjectGrid per-object CRUD.\") and was recorded in undrilled-containers.baseline.json, so its children had no verdict of their own. Each child below is graded by its own reader, measured at this tree: create/import/edit/delete read through resolveCrudAffordances by the server write guard, the apiMethods reconciliation, the /me/permissions clamp and the console's affordance rows; exportCsv by nothing past the resolver (see its row); transfer by nothing yet (planned).", + "note": "Drilled 2026-11-19 when `transfer` (the Change Owner switch, ruling 7000907189 point 1, card #35401) landed beside the five CRUD entries with a different verdict: the container used to carry one blanket `live` (\"objectui ObjectGrid per-object CRUD.\") and was recorded in undrilled-containers.baseline.json, so its children had no verdict of their own. Each child below is graded by its own reader, measured at this tree: create/import/edit/delete read through resolveCrudAffordances by the server write guard, the apiMethods reconciliation, the /me/permissions clamp and the console's affordance rows; exportCsv by the console's export entries through isObjectExportOffered (see its row; it was graded dead on 2026-11-19 and flipped live on 2026-11-21 when those entries were wired, #35619); transfer by nothing yet (planned).", "children": { "create": { "status": "live", @@ -268,10 +268,11 @@ "evidence": "packages/plugins/plugin-security/src/system-write-guard.ts#assertEngineOwnedWriteAllowed (a user-context `delete`, `purge` or `restore` on an engine-owned bucket needs the resolved `delete`); packages/spec/src/data/managed-api-affordance.ts#checkManagedApiMethodAffordances (apiMethods `delete` against the resolved `delete`); packages/core/src/security/effective-object-permissions.ts#clampManagedObjectWrites (reads `userActions.delete`); ui/packages/core/src/utils/affordanceGrants.ts#resolveAffordance (the `rowDelete`, `recordDelete`, `listBulkDelete` and related-list rows read the resolved `delete` and `deletePredicates`); ui/packages/plugin-grid/src/ObjectGrid.tsx#ObjectGrid (per-row delete verdict and `objectDeletePredicates`)" }, "exportCsv": { - "status": "dead", - "verifiedAt": "2026-11-19", - "authorHint": "Remove it: no export menu reads it, so it neither shows nor hides CSV export. The export entry follows the view's exportOptions and the object's effective API operations.", - "note": "Measured 2026-11-19 while drilling this container, by closing the call graph by hand: the key's only reader is packages/spec/src/data/object.zod.ts#resolveCrudAffordances, which copies it onto `CrudAffordances.exportCsv`, and nothing reads that bit. Server side: plugin-security's WRITE_OP_AFFORDANCE and the spec's MANAGED_WRITE_VERB_AFFORDANCE map only create/edit/delete, and core's clampManagedObjectWrites reads only create/edit/delete. Console side: ui/packages/core/src/utils/managedBy.ts#resolveEffectiveCrudAffordances only ANDs the bit with the effective `export` operation, AFFORDANCE_GRANTS has no export row (its `crud` column is create/import/edit/delete), and the export menus (ui/packages/plugin-grid/src/ObjectGrid.tsx `exportEnabled`, ui/packages/plugin-list/src/ListView.tsx `exportPermitted`, ui/packages/plugin-detail/src/RelatedList.tsx, ui/packages/plugin-report/src/ReportExport.tsx) gate on `exportOptions`, `operations.export`, `allowExport` and the effective `export` operation, never on it. `git grep exportCsv` over packages/ and ui/ at this tree returns the declaration, the resolver, the form row, the FLS table (`keep`) and tests only. So `exportCsv: false` does not hide the export entry. Its blanket `live` came from the container's undrilled verdict; drilling may not fan that out (README, Granularity). Enforce-or-remove (ADR-0049) is owed: wire the console export menus to the resolved bit, or retire the key." + "status": "live", + "verifiedAt": "2026-11-21", + "evidenceScope": "in-repo", + "evidence": "ui/packages/core/src/utils/managedBy.ts#isObjectExportOffered (the resolved `exportCsv` bit, through resolveEffectiveCrudAffordances, which hands the object's `userActions` to resolveCrudAffordances and ANDs the bit with the effective `export` API operation: the one export verdict every entry below reads); ui/packages/plugin-grid/src/ObjectGrid.tsx#ObjectGrid (`objectExportOffered`: the toolbar Export menu, its handler and the table's own CSV button); ui/packages/plugin-list/src/ListView.tsx#ListView (`exportPermitted`: the wide toolbar's Export, the Display panel's export footer and the export handler); ui/packages/plugin-report/src/ReportExport.tsx#ReportExportControl (the dataset report's Export, on the query answer's base object, whose definition it reads through the report's data source)", + "note": "Flipped dead → live 2026-11-21 (#35619, ruling 7035537883: enforce). `exportCsv: false` hides the data Export entry (the CSV / XLSX / JSON download: the grid's Export menu and table CSV button, the list view's Export, the dataset report's Export), matching the `exportCsv → export` operation mapping in resolveEffectiveCrudAffordances; a view's export of the picture it draws is not covered (the Gantt view's PNG / PDF buttons in ui/packages/plugin-gantt/src/GanttView.tsx read no export verdict); the bucket defaults (ADR-0103, `exportCsv: true` in every bucket) are unchanged, so an object that does not author the key keeps its entry. It is a console affordance, not a permission: no server door reads it (plugin-security's WRITE_OP_AFFORDANCE, the spec's MANAGED_WRITE_VERB_AFFORDANCE and core's clampManagedObjectWrites map only create/edit/delete), and who may export stays the permission set's allowExport through the effective `export` operation. RelatedList (ui/packages/plugin-detail/src/RelatedList.tsx) offers no export entry at this tree: its table is drawn with `exportable: false`, its enlarged grid carries no `exportOptions`, and its toolbar has no export control, so there is nothing there to gate. Pinned per surface by the `*-35619` render tests beside each reader, each with a CONTROL that the default still shows the entry." }, "transfer": { "status": "planned", diff --git a/packages/spec/liveness/state-counts/object.md b/packages/spec/liveness/state-counts/object.md index be828af2273..77bf836ed94 100644 --- a/packages/spec/liveness/state-counts/object.md +++ b/packages/spec/liveness/state-counts/object.md @@ -12,4 +12,4 @@ committed anywhere: `check:liveness` sums the shards when it reads them. | Type | live | exp | elsewhere | dead | planned | classified | |---|---|---|---|---|---|---| -| `object` | 85 | 0 | 0 | 2 | 2 | 89 | +| `object` | 86 | 0 | 0 | 1 | 2 | 89 | diff --git a/packages/spec/src/data/object.form.ts b/packages/spec/src/data/object.form.ts index 1156d1bbeb1..b177b0807ee 100644 --- a/packages/spec/src/data/object.form.ts +++ b/packages/spec/src/data/object.form.ts @@ -745,7 +745,7 @@ export const objectForm = defineForm({ { field: 'import', label: 'Import', widget: 'json', helpText: 'The CSV import entry: on shows it, off hides it. A stored {enabled, visibleWhen, disabledWhen} object is edited key by key; write one in source to gate the entry on the record in scope, evaluated once per toolbar.' }, { field: 'edit', label: 'Edit', widget: 'json', helpText: 'Editing existing records, inline and in the form: on offers it, off hides it. A stored {enabled, visibleWhen, disabledWhen} object is edited key by key; write one in source to gate each row on its own record.' }, { field: 'delete', label: 'Delete', widget: 'json', helpText: 'Row and bulk delete: on offers it, off hides it. A stored {enabled, visibleWhen, disabledWhen} object is edited key by key; write one in source to gate each row on its own record.' }, - { field: 'exportCsv', label: 'Export CSV', type: 'boolean', helpText: 'The CSV export entry. Unset: shown, since every managedBy bucket offers export.' }, + { field: 'exportCsv', label: 'Export CSV', type: 'boolean', helpText: 'The Export entry that downloads this object\'s data (CSV, XLSX or JSON) on its grids, list views and dataset reports: on shows it, off hides it. A Gantt chart\'s PNG / PDF export is not covered. Unset: shown, since every managedBy bucket offers export. It is not a permission: who may export is the permission set\'s allowExport.' }, { field: 'transfer', label: 'Change Owner', widget: 'json', helpText: 'The Change Owner action, single and bulk: on offers it, off hides it. Unset: on, except off on a controlled_by_parent detail. Offered only on an object whose records have a reassignable owner (ownership user or unset, no managedBy, not a sys_ object, owner_id not readonly and, on an external object, declared or mapped); turning it on anywhere else is refused. It gates the action only, not a plain edit of owner_id. A stored {enabled, visibleWhen, disabledWhen} object is edited key by key; write one in source to gate the action on each record.' }, ], }, diff --git a/packages/spec/src/data/object.zod.ts b/packages/spec/src/data/object.zod.ts index c835e3289b5..b30dc14b3f9 100644 --- a/packages/spec/src/data/object.zod.ts +++ b/packages/spec/src/data/object.zod.ts @@ -4082,9 +4082,9 @@ const ObjectSchemaBase = strictObject( * surfaces. Each flag overrides the default derived from * {@link managedBy} via {@link resolveCrudAffordances}. Useful for the * handful of objects whose lifecycle doesn't cleanly fit a single - * bucket — e.g. an `append-only` table that should still expose CSV - * Export, or a `config` table that admins legitimately want to bulk - * import via CSV. + * bucket — e.g. a `platform` table whose records the console should not + * offer for download (`exportCsv: false`), or a `config` table that + * admins legitimately want to bulk import via CSV. * * Omitting the block (or leaving individual flags `undefined`) keeps * the {@link managedBy}-derived default. @@ -4162,10 +4162,10 @@ const ObjectSchemaBase = strictObject( '`clone` is a CAPABILITY, not a user action — write `enable: { clone: false }`. ' + 'The `enable` block (ObjectCapabilities) is where record deep-cloning is governed.', read: - '`userActions` toggles WRITE affordances only; there is no read toggle. Read ' + + '`userActions` toggles the write affordances and the data Export entry; there is no read toggle. Read ' + 'access is governed by permissions (`requiredPermissions`) and `access.default`.', view: - '`userActions` toggles WRITE affordances only; there is no view toggle. ' + + '`userActions` toggles the write affordances and the data Export entry; there is no view toggle. ' + 'Visibility is governed by permissions (`requiredPermissions`) and `access.default`.', }, }, { @@ -4181,7 +4181,9 @@ const ObjectSchemaBase = strictObject( delete: z.union([z.boolean(), RowCrudActionOverrideSchema]).optional().describe( 'Show row-level delete + bulk delete. Boolean, or an object adding per-record visibleWhen/disabledWhen CEL predicates.', ), - exportCsv: z.boolean().optional().describe('Show CSV export entry.'), + exportCsv: z.boolean().optional().describe( + "Show the Export entry that downloads this object's data as CSV, XLSX or JSON: the grid's Export menu and its table CSV button, the list view's Export, and a dataset report's Export over this object; false hides it. A view's export of the picture it draws (the Gantt chart's PNG / PDF) is not covered. Omitted: shown, in every managedBy bucket. It hides the entry and refuses no export request: who may export is the permission set's allowExport.", + ), transfer: z.union([z.boolean(), RowCrudActionOverrideSchema]).optional().describe( 'Offer the Change Owner action (single and bulk) on records of this object. Boolean, or an object adding per-record visibleWhen/disabledWhen CEL predicates. Omitted: on, except off on a controlled_by_parent detail. Offered only where the platform injects a reassignable owner_id that is provable and not declared readonly (ownership user or omitted, no managedBy, not a sys_ object; an external object declares owner_id or maps a remote column onto it); enabled: true elsewhere is refused. Gates the action, not a plain owner_id write. Resolved by resolveUserActionTransfer.', ), @@ -5798,7 +5800,11 @@ export interface CrudAffordances { edit: boolean; /** Row-level + bulk delete. */ delete: boolean; - /** CSV / clipboard export. Allowed even on append-only audit tables by default. */ + /** + * The console's data Export entry: a CSV, XLSX or JSON download of the + * object's data (not a view's picture export). On by default in every + * bucket, append-only audit tables included. + */ exportCsv: boolean; /** * Per-record CEL predicates for the built-in row Edit action, present only diff --git a/ui/packages/core/README.md b/ui/packages/core/README.md index 9af68f57572..17f2288e7b2 100644 --- a/ui/packages/core/README.md +++ b/ui/packages/core/README.md @@ -248,6 +248,32 @@ sites it found with no row yet formed a frozen backlog, which the pin now holds empty: a new one cannot be added, so a write affordance gets its row when it lands. +### The Export verdict (`isObjectExportOffered`) + +Every Export entry that downloads an object's data as CSV, XLSX or JSON (a +grid's Export menu and its table's own CSV button, a list view's Export, a +dataset report's Export control) reads one verdict, +`isObjectExportOffered(objectSchema, effectiveApiOperations)`. It +is the resolved `exportCsv` bit: the object's `userActions.exportCsv` over its +`managedBy` default, ANDed with the server's effective `export` operation when a +set is handed down. Every bucket defaults the bit on, so an object closes its +data Export entry only by setting `userActions.exportCsv: false`. A view's +export of the picture it draws, such as the Gantt chart's PNG and PDF buttons, +does not read this verdict. + +Export is a read, not a write, so it has no row in `AFFORDANCE_GRANTS` and asks +no `can(object, verb)`. The caller's export grant, the permission set's +`allowExport`, reaches the client through the effective `export` operation, +which the server derives from `list` and that grant. + +```typescript +import { isObjectExportOffered } from '@object-ui/core' + +isObjectExportOffered({ managedBy: 'append-only' }) // true +isObjectExportOffered({ userActions: { exportCsv: false } }) // false +isObjectExportOffered({ managedBy: 'platform' }, ['get', 'list']) // false: no `export` served +``` + ### Undo snapshot for an update (`captureUpdateUndoData`) An `undoable` update restores exactly the fields it wrote, from their values diff --git a/ui/packages/core/src/utils/managedBy.test.ts b/ui/packages/core/src/utils/managedBy.test.ts index cf0600a8a63..33f9cb52595 100644 --- a/ui/packages/core/src/utils/managedBy.test.ts +++ b/ui/packages/core/src/utils/managedBy.test.ts @@ -5,6 +5,7 @@ import { isWriteOptedIn, isSystemWritable, isObjectInlineEditable, + isObjectExportOffered, normalizeUserAction, userActionPredicates, type UserActionsOverride, @@ -234,6 +235,47 @@ describe('isObjectInlineEditable — effective API operations (#3546)', () => { }); }); +describe('isObjectExportOffered — the one export verdict (objectstack#35619)', () => { + it('an object that does not author exportCsv offers export in every bucket', () => { + for (const managedBy of MANAGED_BY_BUCKETS) { + expect(isObjectExportOffered({ managedBy }), managedBy).toBe(true); + } + expect(isObjectExportOffered(null)).toBe(true); + expect(isObjectExportOffered(undefined)).toBe(true); + }); + + it('exportCsv false closes it, in every bucket; exportCsv true keeps it open', () => { + for (const managedBy of MANAGED_BY_BUCKETS) { + expect(isObjectExportOffered({ managedBy, userActions: { exportCsv: false } }), managedBy).toBe(false); + expect(isObjectExportOffered({ managedBy, userActions: { exportCsv: true } }), managedBy).toBe(true); + } + }); + + it('a closing userActions on another verb leaves it open', () => { + expect(isObjectExportOffered({ managedBy: 'platform', userActions: { edit: false, delete: false, create: false } })).toBe(true); + }); + + it('an effective set without `export` closes it; one with `export` keeps the bit as authored', () => { + expect(isObjectExportOffered({ managedBy: 'platform' }, ['get', 'list'])).toBe(false); + expect(isObjectExportOffered({ managedBy: 'platform' }, [])).toBe(false); + expect(isObjectExportOffered({ managedBy: 'platform' }, ['list', 'export'])).toBe(true); + // The set never re-opens what the object closed. + expect(isObjectExportOffered({ managedBy: 'platform', userActions: { exportCsv: false } }, ['list', 'export'])).toBe(false); + }); + + it('is the resolved exportCsv bit, for every bucket, authored value and effective set', () => { + const sets: Array = [undefined, [], ['list'], ['list', 'export']]; + for (const managedBy of MANAGED_BY_BUCKETS) { + for (const exportCsv of [undefined, true, false]) { + const obj = exportCsv === undefined ? { managedBy } : { managedBy, userActions: { exportCsv } }; + for (const ops of sets) { + expect(isObjectExportOffered(obj, ops)).toBe(resolveEffectiveCrudAffordances(obj, ops).exportCsv); + } + } + } + }); +}); + /** * [#5142] The `import` half of the toolbar-scope predicate pair. * diff --git a/ui/packages/core/src/utils/managedBy.ts b/ui/packages/core/src/utils/managedBy.ts index cd47869f85e..3320f34573c 100644 --- a/ui/packages/core/src/utils/managedBy.ts +++ b/ui/packages/core/src/utils/managedBy.ts @@ -202,6 +202,38 @@ export function resolveEffectiveCrudAffordances( return out; } +/** + * Whether the console offers an object's data Export entry, the CSV, XLSX or + * JSON download of its data (objectstack#35619). The entries that read this + * one verdict are the grid's Export menu and its table CSV button, the list + * view's Export (the wide toolbar and the Display panel) and a dataset + * report's Export. A view's export of the picture it draws, such as the Gantt + * chart's PNG / PDF, does not read it. + * + * It is the resolved `exportCsv` bit: the object's `userActions.exportCsv` over + * its `managedBy` default (ADR-0103 offers export in every bucket, so `false` + * is the only way to close it), ANDed with the server's effective `export` + * operation when a set is handed down. + * + * Export is a read, not a write, so it has no row in `AFFORDANCE_GRANTS` and + * asks no `can(object, verb)`. The caller's export grant, the permission set's + * opt-in `allowExport`, reaches the client through the effective `export` + * operation, which the server derives from `list` ∧ `allowExport`. A + * `can(object, 'export')` question would read `allowRead` instead. The setting + * hides an entry and refuses no export request. + * + * @param effectiveApiOperations OPTIONAL server-resolved effective API operation + * set for this object (`/me/permissions` `apiOperations`, objectstack#3391). + * `undefined` (old backend / unrestricted object / no provider) leaves the + * object's own bit as the verdict. + */ +export function isObjectExportOffered( + obj: SchemaLike | null | undefined, + effectiveApiOperations?: readonly string[] | null, +): boolean { + return resolveEffectiveCrudAffordances(obj, effectiveApiOperations).exportCsv; +} + /** True only when a `userActions` flag (bare boolean or #2614 object form) opts the write in. */ export function isWriteOptedIn(v: UserActionOverride | undefined | null): boolean { return v === true || (typeof v === 'object' && v !== null && v.enabled === true); diff --git a/ui/packages/plugin-grid/README.md b/ui/packages/plugin-grid/README.md index fa5642489f0..990d99f7523 100644 --- a/ui/packages/plugin-grid/README.md +++ b/ui/packages/plugin-grid/README.md @@ -1127,6 +1127,20 @@ const persistence = ( - Save all changes at once using "Save All" button - Cancel individual row changes or all changes +### Export + +The toolbar's Export menu (offered when the schema declares `exportOptions`) and +the table's own CSV button (`operations.export: true`) are both offered only +while the object's resolved export verdict is open: +`isObjectExportOffered(objectSchema, effectiveApiOperations)` from +`@object-ui/core`, which is the object's `userActions.exportCsv` over its +`managedBy` default, ANDed with the caller's effective `export` API operation. +An object that sets `userActions.exportCsv: false` gets neither entry, in any +format; one that does not set it keeps them, since every `managedBy` bucket +defaults it on. `operations.export: false` on the schema closes them too. The +setting hides the entries and is not a permission: who may export is the +permission set's `allowExport`. + ## TypeScript Support The schema and column types come from `@object-ui/types`; this package exports the diff --git a/ui/packages/plugin-grid/src/ObjectGrid.tsx b/ui/packages/plugin-grid/src/ObjectGrid.tsx index 4fd0013bff7..96ddb1ee4c4 100644 --- a/ui/packages/plugin-grid/src/ObjectGrid.tsx +++ b/ui/packages/plugin-grid/src/ObjectGrid.tsx @@ -71,7 +71,7 @@ import { AlertDialogHeader, AlertDialogTitle, } from '@object-ui/components'; -import { captureUpdateUndoData, resolveConditionalFormatting, declaredNameField, buildExportFileName, resolveAffordance, resolveAffordanceGrant, resolveFieldAffordance, type SchemaLike, isExpandableFieldType, isUnmaterializedFieldType, readObjectSortability, isPlatformSortableField, filterPlatformSortableSort, filterRefusalSubject, FilterOperatorError, resolveRecordSourceConfig, resolveRecordSourceObjectName, partitionRowsByPredicate, csvBlob, readActionPayload } from '@object-ui/core'; +import { captureUpdateUndoData, resolveConditionalFormatting, declaredNameField, buildExportFileName, resolveAffordance, resolveAffordanceGrant, resolveFieldAffordance, isObjectExportOffered, type SchemaLike, isExpandableFieldType, isUnmaterializedFieldType, readObjectSortability, isPlatformSortableField, filterPlatformSortableSort, filterRefusalSubject, FilterOperatorError, resolveRecordSourceConfig, resolveRecordSourceObjectName, partitionRowsByPredicate, csvBlob, readActionPayload } from '@object-ui/core'; import { usePermissions } from '@object-ui/permissions'; import { RECORD_OVERLAY_DEFAULT_WIDTH, @@ -1032,9 +1032,9 @@ export const ObjectGrid: React.FC = ({ const objectTypesPending = !!objectName && typeof dataSource?.getObjectSchema === 'function' && !objectFields; // [objectstack#3391] Server-resolved effective API operation set for this object - // (/me/permissions `apiOperations`). The Export button and handler AND their - // gate with this — a missing set (unrestricted object / old backend / no - // provider) keeps the current behavior. The frontend consumes the effective + // (/me/permissions `apiOperations`). The Export entries and handler AND their + // gate with this through `objectExportOffered` below — a missing set + // (unrestricted object / old backend / no provider) keeps the current behavior. The frontend consumes the effective // set the server resolved; it never reads the raw `apiMethods`. const perms = usePermissions(); const { getObjectApiOperations } = perms; @@ -1082,6 +1082,20 @@ export const ObjectGrid: React.FC = ({ // the three read as one block rather than drifting apart again. const addRowGranted = resolveAffordance('gridAddRow', affordanceSource).allowed; + // [objectstack#35619] The object's export verdict, read by every export entry + // this grid draws — the toolbar's Export menu, its handler and the table's own + // CSV button. `isObjectExportOffered` (`@object-ui/core`) folds the object's + // `userActions.exportCsv` over its `managedBy` default (`false` hides every + // format) with the server's effective `export` operation, so neither half is + // spelled here. It describes the OBJECT, from `objectSchema` alone, and is not + // a grant: who may export is the permission set's `allowExport`, which reaches + // this grid through the effective operation set. With no object definition in + // hand the bucket default applies, which offers export in every bucket. + const objectExportOffered = isObjectExportOffered( + objectSchema as SchemaLike | null | undefined, + effectiveApiOps, + ); + // [#5143] Whether THIS principal may edit THIS object's rows in place — the // single verdict behind every inline-edit affordance this grid renders // (`editable`, the cell editor, and the save/cancel column that serves them). @@ -1817,11 +1831,13 @@ export const ObjectGrid: React.FC = ({ const handleExport = useCallback((format: ListViewExportFormat) => { // Object-level export permission gate. Default-allow: an explicit - // `operations.export === false` blocks it, and — when the server hands down - // an effective API operation set for this object (objectstack#3391) — so does its - // exclusion of `export`. Missing effective set keeps current behavior. + // `operations.export === false` blocks it, and so does a closed object export + // verdict (`objectExportOffered`: the object's `userActions.exportCsv`, and + // the server's effective API operation set excluding `export` when one is + // handed down, objectstack#3391). A missing effective set leaves the + // object's own verdict alone. if (schema.operations?.export === false) return; - if (effectiveApiOps && !effectiveApiOps.includes('export')) return; + if (!objectExportOffered) return; const exportConfig = schema.exportOptions; const maxRecords = exportConfig?.maxRecords || 0; const includeHeaders = exportConfig?.includeHeaders !== false; @@ -1953,7 +1969,7 @@ export const ObjectGrid: React.FC = ({ downloadFile(new Blob([JSON.stringify(unmasked, null, 2)], { type: 'application/json' }), fileNameFor('json')); } setShowExport(false); - }, [data, schema.exportOptions, schema.operations?.export, effectiveApiOps, schema.objectName, objectName, objectSchema, objectFields, objectTypesPending, generateColumns, dataSource, hasInlineData, schemaFilter, schemaSort, t]); + }, [data, schema.exportOptions, schema.operations?.export, objectExportOffered, schema.objectName, objectName, objectSchema, objectFields, objectTypesPending, generateColumns, dataSource, hasInlineData, schemaFilter, schemaSort, t]); // objectui#9050 step 2 — a refused filter: `schema.filter` (a render-time // `useMemo`, which would otherwise have thrown out of render), or a @@ -3425,7 +3441,9 @@ export const ObjectGrid: React.FC = ({ // above the table when search/export are handled by the outer toolbar. showSelectionCount: false, sortable: true, - exportable: operations?.export, + // The table's own CSV button follows the object's export verdict too + // (objectstack#35619): `operations.export` asks for it, the object allows it. + exportable: operations?.export && objectExportOffered, // Flat list view: drop the rounded outer frame so the table sits flush // beneath the toolbar's `border-b`. Matches the Airtable-style grouped // mode introduced for `buildGroupedTableSchema`. Metadata can re-enable @@ -4216,14 +4234,16 @@ export const ObjectGrid: React.FC = ({ // key the save gate refuses. Pinned by // `__tests__/gridNonAuthorKeys.test.tsx`. const showRowHeightToggle = schema.rowHeight !== undefined && !(schema as any).hideRowHeightToggle; - // Export is offered only when configured AND not blocked by object-level perms - // — including the server's effective API operation set (objectstack#3391): when present - // and it excludes `export`, the button is hidden. Missing set → unchanged. + // Export is offered only when configured AND not blocked: by the view's + // `operations.export`, or by the object's resolved export verdict + // (`objectExportOffered`: `userActions.exportCsv` over the bucket default, + // ANDed with the server's effective API operation set, objectstack#3391 / + // objectstack#35619). Missing set → the object's own verdict alone. const exportEnabled = !!schema.exportOptions && exportableFormats.length > 0 && schema.operations?.export !== false && - (effectiveApiOps ? effectiveApiOps.includes('export') : true); + objectExportOffered; const hasToolbar = exportEnabled || showRowHeightToggle; const gridToolbar = hasToolbar ? (
diff --git a/ui/packages/plugin-grid/src/__tests__/exportCsvGate-35619.test.tsx b/ui/packages/plugin-grid/src/__tests__/exportCsvGate-35619.test.tsx new file mode 100644 index 00000000000..52e8c978c4d --- /dev/null +++ b/ui/packages/plugin-grid/src/__tests__/exportCsvGate-35619.test.tsx @@ -0,0 +1,108 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * objectstack#35619 — the object's `userActions.exportCsv: false` hides the + * grid's export entries: the toolbar's Export menu (every format) and the + * table's own CSV button that `operations.export: true` turns on. Both read + * the object's resolved export verdict, `resolveEffectiveCrudAffordances`'s + * `exportCsv`, which is the authored bit over the `managedBy` default ANDed + * with the server's effective `export` operation. + * + * The verdict is read off the object definition the grid fetches, so every + * case waits for the first row to draw: an untyped column is withheld until + * that definition lands, so a drawn row means the verdict is the settled one. + * The CONTROLS render the same grid over an object that does not author the + * key, and over one that authors `true`, and find both entries — the probe + * can see them, so the absence below is a reading and not a blind instrument. + */ + +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; +import { render, screen, waitFor, cleanup } from '@testing-library/react'; +import '@testing-library/jest-dom'; +import React from 'react'; + +import { ObjectGrid } from '../ObjectGrid'; +import { __clearRecordCrudVerdictCache } from '../hooks/useRecordCrudVerdicts'; +import { installExplainDouble } from './explainDouble'; +import { registerAllFields } from '@object-ui/fields'; +import { ActionProvider, SchemaRendererProvider } from '@object-ui/react'; +import type { DataSource, ObjectGridSchema } from '@object-ui/types'; + +registerAllFields(); + +const ROWS = [ + { id: '1', name: 'Alice' }, + { id: '2', name: 'Bob' }, +]; + +async function renderGrid(userActions?: Record) { + const getObjectSchema = vi.fn(async (name: string) => ({ + name, + fields: { id: { type: 'text' }, name: { type: 'text', label: 'Name' } }, + ...(userActions ? { userActions } : {}), + })); + // Only the definition read is answered: the rows are inline. + const dataSource = { getObjectSchema } as unknown as DataSource; + const schema = { + type: 'object-grid', + objectName: 'test_object', + columns: [{ field: 'name', label: 'Name' }], + data: { provider: 'value', items: ROWS }, + exportOptions: { formats: ['csv', 'json'] }, + // Turns on the table's own CSV button beside the toolbar menu. + operations: { export: true }, + } as unknown as ObjectGridSchema; + render( + + + + + , + ); + await waitFor(() => expect(getObjectSchema).toHaveBeenCalledWith('test_object')); + await waitFor(() => expect(screen.getByText('Alice')).toBeInTheDocument()); +} + +const toolbarExport = () => screen.queryByRole('button', { name: /^export$/i }); +const tableCsvExport = () => screen.queryByRole('button', { name: /^export csv$/i }); + +beforeEach(() => { + __clearRecordCrudVerdictCache(); + installExplainDouble(); +}); +afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); +}); + +describe('ObjectGrid — userActions.exportCsv gates every export entry (objectstack#35619)', () => { + it('exportCsv false: no toolbar Export menu and no table CSV button', async () => { + await renderGrid({ exportCsv: false }); + expect(toolbarExport()).toBeNull(); + expect(tableCsvExport()).toBeNull(); + }); + + it('CONTROL: an object that does not author exportCsv keeps both entries', async () => { + await renderGrid(); + expect(toolbarExport()).toBeInTheDocument(); + expect(tableCsvExport()).toBeInTheDocument(); + }); + + it('CONTROL: exportCsv true keeps both entries', async () => { + await renderGrid({ exportCsv: true }); + expect(toolbarExport()).toBeInTheDocument(); + expect(tableCsvExport()).toBeInTheDocument(); + }); + + it('a closing userActions on another verb leaves export open', async () => { + // The bit is read on its own: closing edit and delete is no export verdict. + await renderGrid({ edit: false, delete: false }); + expect(toolbarExport()).toBeInTheDocument(); + }); +}); diff --git a/ui/packages/plugin-list/README.md b/ui/packages/plugin-list/README.md index 28a84eafafd..dfb228682b6 100644 --- a/ui/packages/plugin-list/README.md +++ b/ui/packages/plugin-list/README.md @@ -681,6 +681,22 @@ says how many records its list holds. `page:tabs` mounts a tab holding a list block while it is inactive (hidden), so the badge is there before the tab is opened; a tab with an authored `count` is not mounted early. +## Export + +The Export entry (the wide toolbar's button and the Display panel's footer) is +offered when the view declares `exportOptions` and three things allow it: the +view's `allowExport` and `operations.export` are not `false`, and the object's +resolved export verdict is open. That verdict is +`isObjectExportOffered(objectDef, effectiveApiOperations)` from +`@object-ui/core`: the object's `userActions.exportCsv` over its +`managedBy` default, ANDed with the caller's effective `export` API operation. +An object that sets `userActions.exportCsv: false` therefore gets no Export +entry in any of its formats (CSV, XLSX, JSON); one that does not set it keeps +the entry, since every `managedBy` bucket defaults it on. The setting hides the +entry and is not a permission: who may export is the permission set's +`allowExport`. It covers the download of the object's data only: a Gantt view's +PNG and PDF export of the chart it draws is not gated by it. + ## Sorting (and why relational columns are not offered) The toolbar sort becomes a server `$orderby` on the **flat field name**, so the diff --git a/ui/packages/plugin-list/src/ListView.tsx b/ui/packages/plugin-list/src/ListView.tsx index 7ecfd1938a6..7044c6da251 100644 --- a/ui/packages/plugin-list/src/ListView.tsx +++ b/ui/packages/plugin-list/src/ListView.tsx @@ -49,7 +49,7 @@ import { useDensityMode, resolveInlineAriaProps } from '@object-ui/react'; import type { DataTableSchema, DependsOnInput, ListViewSchema, ObjectMapConfig } from '@object-ui/types'; import { detectStatusField, isSystemManagedField } from '@object-ui/types'; import { usePullToRefresh } from '@object-ui/mobile'; -import { type ListViewVisualization, resolveConditionalFormatting, buildExpandFields, buildExportFileName, resolveAffordance, type SchemaLike, partitionRowsByPredicate, normalizeListViewSchema, isListViewVisualization, rowHeightToDensityMode, mergeFilterNodes, toFilterNodeSafely, FilterOperatorError, columnIdentity, collectPredicateFieldRefs, collectGroupingFieldRefs, listViewPredicates, PLATFORM_RECORD_COLUMNS, EXPANDABLE_FIELD_TYPES, UNMATERIALIZED_FIELD_TYPES, readObjectSortability, isPlatformSortableField, leadWithNameField, filterPlatformSortableSort, applyNonGridRowCeiling, type NonGridCeilingResult, resolveNameField, declaredNameField, resolveDependsOnFields, GANTT_CONFIG_SPELLING, kanbanDeclaredLanes, csvBlob, readWithheldFieldNames, refersToWithheldField } from '@object-ui/core'; +import { type ListViewVisualization, resolveConditionalFormatting, buildExpandFields, buildExportFileName, resolveAffordance, isObjectExportOffered, type SchemaLike, partitionRowsByPredicate, normalizeListViewSchema, isListViewVisualization, rowHeightToDensityMode, mergeFilterNodes, toFilterNodeSafely, FilterOperatorError, columnIdentity, collectPredicateFieldRefs, collectGroupingFieldRefs, listViewPredicates, PLATFORM_RECORD_COLUMNS, EXPANDABLE_FIELD_TYPES, UNMATERIALIZED_FIELD_TYPES, readObjectSortability, isPlatformSortableField, leadWithNameField, filterPlatformSortableSort, applyNonGridRowCeiling, type NonGridCeilingResult, resolveNameField, declaredNameField, resolveDependsOnFields, GANTT_CONFIG_SPELLING, kanbanDeclaredLanes, csvBlob, readWithheldFieldNames, refersToWithheldField } from '@object-ui/core'; import { useObjectLabel, useSafeFieldLabel, createSafeTranslation, useDisplayLocale, pickLocalized, recordCurrencyField, recordCurrencyReadField } from '@object-ui/i18n'; // Two resolvers, two vocabularies — the repo spells the distinction into the // NAMES (objectui#4167). `resolveInlineI18nLabel` is the spec's own @@ -3059,19 +3059,26 @@ export const ListView = React.forwardRef(({ const [exportError, setExportError] = React.useState(null); // Object-level export permission gate. Default-allow: export stays enabled - // unless `allowExport === false` or `operations.export === false`, AND — when - // the server hands down an effective API operation set for this object - // (/me/permissions `apiOperations`, objectstack#3391) — unless it excludes `export`. - // Missing effective set (unrestricted object / old backend / no provider) - // keeps the current behavior. The frontend consumes the effective set the - // server resolved; it never reads the raw `apiMethods`. + // unless `allowExport === false` or `operations.export === false`, AND unless + // the object's resolved export verdict closes it. That verdict is + // `isObjectExportOffered` from `@object-ui/core`: + // the object's `userActions.exportCsv` over its `managedBy` default + // (objectstack#35619 — `exportCsv: false` hides the whole entry, every + // format) ANDed with the server's effective API operation set + // (/me/permissions `apiOperations`, objectstack#3391) when one is handed + // down. A missing set (unrestricted object / old backend / no provider) and + // an object definition still in flight keep the default, which offers + // export in every bucket. The frontend consumes the effective set the server + // resolved; it never reads the raw `apiMethods`. Every export door below — + // the wide toolbar, the Display panel's footer and `handleExport` — reads + // this one name. const affordancePerms = usePermissions(); const { getObjectApiOperations } = affordancePerms; const effectiveApiOps = schema.objectName ? getObjectApiOperations(schema.objectName) : undefined; const exportPermitted = schema.allowExport !== false && schema.operations?.export !== false && - (effectiveApiOps ? effectiveApiOps.includes('export') : true); + isObjectExportOffered(objectDef as SchemaLike | null, effectiveApiOps); // [objectstack#3720] Bulk-action gate for the NON-grid views (kanban / calendar / // gallery / …), whose bulk bar this component renders itself — the grid path diff --git a/ui/packages/plugin-list/src/__tests__/ListView.harness.test.tsx b/ui/packages/plugin-list/src/__tests__/ListView.harness.test.tsx index 84eef1620b7..1ee3fff0179 100644 --- a/ui/packages/plugin-list/src/__tests__/ListView.harness.test.tsx +++ b/ui/packages/plugin-list/src/__tests__/ListView.harness.test.tsx @@ -2450,6 +2450,94 @@ describe('ListView.switcherChrome-7547', () => { }); }); +// ── ListView.exportCsvGate-35619 ──────────────────────────────────────────────── + +/** + * objectstack#35619 — the object's `userActions.exportCsv: false` hides the + * list's Export entry, every format, in both toolbar forms: the wide form's + * Export button and the Display panel's export footer. The verdict is the + * object's, read off the definition the list fetches, so each case waits for + * the row read, which runs only once that definition has settled. The + * CONTROLS render the same view over an object that does not author the key, + * and over one that authors `true`, and find the entry: the probe can see it. + */ +describe('ListView.exportCsvGate-35619', () => { + restoreAfterBlock(); + + function makeDataSource(userActions?: Record) { + return { + find: vi.fn().mockResolvedValue({ data: [{ id: '1', name: 'Acme' }], total: 1 }), + findOne: vi.fn(), + create: vi.fn(), + update: vi.fn(), + delete: vi.fn(), + getObjectSchema: vi.fn().mockResolvedValue({ + name: 'account', + fields: { name: { type: 'text', label: 'Name' } }, + ...(userActions ? { userActions } : {}), + }), + } as any; + } + + async function renderList(compactToolbar: boolean, userActions?: Record) { + const ds = makeDataSource(userActions); + render( + + + , + ); + await waitFor(() => expect(ds.getObjectSchema).toHaveBeenCalledWith('account')); + // The row read waits for the definition, so once it runs the verdict is the settled one. + await waitFor(() => expect(ds.find).toHaveBeenCalled()); + } + + const wideExport = () => screen.queryByRole('button', { name: /^export$/i }); + + function displayExportEntries() { + fireEvent.click(screen.getByTestId('toolbar-display-trigger')); + const panel = screen.getByTestId('view-settings-content'); + return within(panel).queryAllByTestId(/^display-export-(csv|xlsx|json)$/); + } + + it('wide toolbar: exportCsv false draws no Export button', async () => { + await renderList(false, { exportCsv: false }); + expect(wideExport()).toBeNull(); + }); + + it('wide toolbar CONTROL: an object that does not author exportCsv keeps the Export button', async () => { + await renderList(false); + expect(wideExport()).toBeInTheDocument(); + }); + + it('wide toolbar CONTROL: exportCsv true keeps the Export button', async () => { + await renderList(false, { exportCsv: true }); + expect(wideExport()).toBeInTheDocument(); + }); + + it('Display panel: exportCsv false draws no export entry, in any format', async () => { + await renderList(true, { exportCsv: false }); + expect(displayExportEntries()).toHaveLength(0); + }); + + it('Display panel CONTROL: an object that does not author exportCsv keeps both formats', async () => { + await renderList(true); + expect(displayExportEntries().map((el) => el.getAttribute('data-testid'))).toEqual([ + 'display-export-csv', + 'display-export-json', + ]); + }); +}); + // ── ListView.displayMenuClose-12621 ───────────────────────────────────────────── /** diff --git a/ui/packages/plugin-report/README.md b/ui/packages/plugin-report/README.md index 90b6b9a6bb7..fab5dd78caa 100644 --- a/ui/packages/plugin-report/README.md +++ b/ui/packages/plugin-report/README.md @@ -269,6 +269,20 @@ on every non-`joined` type. It draws above a `tabular` or `summary` table, and below the cross-tab of a `matrix` that declares `columns`; there `xAxis` may name a `rows` or a `columns` dimension. +## The Export control + +A dataset-bound report draws an Export control beside its period chip, +offering the formats `exportOptions.formats` names (`csv` and `xlsx` by +default, none for `[]`). The control writes the table as drawn. It is offered +only while the dataset's base object (the query answer's `object`) resolves an +open export verdict, the one the list toolbar and the grid read: +`isObjectExportOffered(objectDef, effectiveApiOperations)` from +`@object-ui/core`. So a base object that sets `userActions.exportCsv: +false` gets no Export control on its reports, and neither does a caller whose +effective API operations on it leave out `export`. The base object's definition +is read through the report's data source (`getObjectSchema`); a source that +cannot serve one leaves the control available. + ## Server-side aggregation + drill-down A dataset-bound report selects its dimensions (`rows`, and for `matrix` also diff --git a/ui/packages/plugin-report/src/DatasetReportRenderer.tsx b/ui/packages/plugin-report/src/DatasetReportRenderer.tsx index 522371f80e0..9d6ad9b5bc4 100644 --- a/ui/packages/plugin-report/src/DatasetReportRenderer.tsx +++ b/ui/packages/plugin-report/src/DatasetReportRenderer.tsx @@ -2621,7 +2621,7 @@ const DatasetReportRendererBody: React.FC = ({ onChange={(next) => setPicked({ key: dateRangeKey, period: next })} /> ) : null} - +
{periodError ? ( diff --git a/ui/packages/plugin-report/src/ReportExport.tsx b/ui/packages/plugin-report/src/ReportExport.tsx index f5850816c4d..bbebffcb84d 100644 --- a/ui/packages/plugin-report/src/ReportExport.tsx +++ b/ui/packages/plugin-report/src/ReportExport.tsx @@ -20,11 +20,16 @@ * * Formats are `csv` / `xlsx`, on by default: absent means both, `formats: []` * means no control. Who may export is not a report key: the control is offered - * only when the viewer's effective API operations on the dataset's BASE object - * (the query answer's `object`) include `export` — the predicate the list - * toolbar applies (`ObjectPermission.allowExport`). An absent operation set (no - * provider, an unrestricted object, an older server) keeps it available, as it - * does on the list. + * only when the dataset's BASE object (the query answer's `object`) resolves + * an open export verdict — `isObjectExportOffered` from `@object-ui/core`, + * the predicate the list toolbar and the grid apply. + * That is the object's `userActions.exportCsv` over its `managedBy` default + * (`exportCsv: false` hides the control, every format), ANDed with the + * viewer's effective API operations on the object including `export` + * (`ObjectPermission.allowExport`). The object definition is read through the + * report's data source; an absent operation set (no provider, an unrestricted + * object, an older server) and a definition not yet read or not readable keep + * the control available, as they do on the list. * * Both files are written in the browser. The list's XLSX goes through the * server record stream, which carries records, not aggregated report rows, so @@ -35,9 +40,11 @@ import * as React from 'react'; import { Download, Loader2 } from 'lucide-react'; import { Button, Popover, PopoverContent, PopoverTrigger } from '@object-ui/components'; -import { buildExportFileName } from '@object-ui/core'; +import { buildExportFileName, isObjectExportOffered, type SchemaLike } from '@object-ui/core'; import { pickLocalized, useObjectTranslation } from '@object-ui/i18n'; import { usePermissions } from '@object-ui/permissions'; +import { useSettledSchema } from '@object-ui/react'; +import type { DataSource } from '@object-ui/types'; /** One drawn cell: its text as shown, and the number behind a measure cell. */ export interface ReportExportCell { @@ -172,12 +179,22 @@ export interface ReportExportControlProps { name?: string; /** The drawn table; no control until there is one to export. */ snapshot: ReportTableSnapshot | null; + /** + * The report's data source, which the dataset's base object definition is + * read from (its `userActions.exportCsv` and `managedBy`). Absent: no + * definition is read and the object's default verdict applies. + */ + dataSource?: unknown; } /** The report header's Export control. Draws nothing when there is nothing the viewer may export. */ -export function ReportExportControl({ exportOptions, label, name, snapshot }: ReportExportControlProps) { +export function ReportExportControl({ exportOptions, label, name, snapshot, dataSource }: ReportExportControlProps) { const { t, language } = useObjectTranslation(); const { getObjectApiOperations } = usePermissions(); + const { def: baseObject } = useSettledSchema( + snapshot?.object ?? '', + dataSource as DataSource | null | undefined, + ); const [open, setOpen] = React.useState(false); const [busy, setBusy] = React.useState(false); const [error, setError] = React.useState(null); @@ -186,7 +203,7 @@ export function ReportExportControl({ exportOptions, label, name, snapshot }: Re if (formats.length === 0 || !snapshot) return null; // The list toolbar's predicate, on the dataset's base object. const ops = snapshot.object ? getObjectApiOperations(snapshot.object) : undefined; - if (ops && !ops.includes('export')) return null; + if (!isObjectExportOffered(baseObject, ops)) return null; const options = (exportOptions ?? {}) as ReportExportOptionsLike; const includeHeaders = options.includeHeaders !== false; diff --git a/ui/packages/plugin-report/src/__tests__/ReportExport.exportCsvGate-35619.test.tsx b/ui/packages/plugin-report/src/__tests__/ReportExport.exportCsvGate-35619.test.tsx new file mode 100644 index 00000000000..352ee966fd6 --- /dev/null +++ b/ui/packages/plugin-report/src/__tests__/ReportExport.exportCsvGate-35619.test.tsx @@ -0,0 +1,111 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * objectstack#35619 — the dataset report's Export control reads the BASE + * object's resolved export verdict (`resolveEffectiveCrudAffordances`'s + * `exportCsv`), the predicate the list toolbar and the grid apply: an object + * authoring `userActions.exportCsv: false` gets no Export control on its + * reports, whatever `exportOptions.formats` offers. + * + * The control reads the object's definition through the report's data source, + * keyed on the object the drawn table names, so every case waits for that read + * to be asked and answered before it looks. The CONTROLS draw the same report + * over an object that does not author the key, and over one that authors + * `true`, and find the control. + */ + +import '@testing-library/jest-dom/vitest'; +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { render, screen, waitFor, cleanup, act } from '@testing-library/react'; +import { I18nProvider } from '@object-ui/i18n'; +import { DatasetReportRenderer } from '../DatasetReportRenderer'; + +const OBJECT = 'crm_opportunity'; + +// A result that names its `object` makes the dimension-label hook read +// `/api/v1/meta/object/NAME` through the global `fetch` (no host `apiFetch` +// here). Answered by ONE module-scope double that stays up for the whole file; +// any other URL is recorded and refused. +const META_OBJECT_ROUTE = /^\/api\/v1\/meta\/object\/(.+)$/; +const strayUrls: string[] = []; +vi.stubGlobal( + 'fetch', + vi.fn(async (input: unknown) => { + const url = String(input && typeof input === 'object' && 'url' in input ? (input as { url: unknown }).url : input); + const m = META_OBJECT_ROUTE.exec(url); + if (!m) { + strayUrls.push(url); + return { ok: false, status: 404, json: async () => ({}) }; + } + return { ok: true, status: 200, json: async () => ({ item: { name: decodeURIComponent(m[1]), fields: {} } }) }; + }), +); + +const RESULT = { + rows: [ + { stage: 'Prospecting', amount: 1200 }, + { stage: 'Closed Won', amount: 5000 }, + ], + fields: [ + { name: 'stage', type: 'string', label: 'Stage' }, + { name: 'amount', type: 'number', label: 'Amount' }, + ], + object: OBJECT, +}; + +const REPORT = { + name: 'pipeline_by_stage', + label: 'Pipeline by Stage', + type: 'summary', + dataset: 'opportunity_metrics', + rows: ['stage'], + values: ['amount'], +}; + +afterEach(() => { + cleanup(); + vi.restoreAllMocks(); + expect(strayUrls).toEqual([]); +}); + +async function renderReport(userActions?: Record) { + const getObjectSchema = vi.fn(async (name: string) => ({ name, fields: {}, ...(userActions ? { userActions } : {}) })); + const source = { queryDataset: vi.fn(async () => RESULT), getObjectSchema }; + render( + + + , + ); + await waitFor(() => expect(screen.getByRole('table')).toBeInTheDocument()); + // The definition is asked for the object the drawn table names; let its answer land. + await waitFor(() => expect(getObjectSchema).toHaveBeenCalledWith(OBJECT)); + await act(async () => { + await getObjectSchema.mock.results[getObjectSchema.mock.results.length - 1].value; + }); +} + +const exportControl = () => screen.queryByRole('button', { name: 'Export' }); + +describe('ReportExportControl — the base object\'s userActions.exportCsv (objectstack#35619)', () => { + it('exportCsv false: no Export control on the report', async () => { + await renderReport({ exportCsv: false }); + expect(exportControl()).toBeNull(); + expect(screen.queryByTestId('report-export')).toBeNull(); + }); + + it('CONTROL: an object that does not author exportCsv keeps the Export control', async () => { + await renderReport(); + expect(exportControl()).toBeInTheDocument(); + }); + + it('CONTROL: exportCsv true keeps the Export control', async () => { + await renderReport({ exportCsv: true }); + expect(exportControl()).toBeInTheDocument(); + }); +});