diff --git a/.changeset/34269-bulk-aggregate-result-reader.md b/.changeset/34269-bulk-aggregate-result-reader.md new file mode 100644 index 00000000000..a5d28ed55b8 --- /dev/null +++ b/.changeset/34269-bulk-aggregate-result-reader.md @@ -0,0 +1,19 @@ +--- +'@object-ui/plugin-grid': patch +'@object-ui/i18n': patch +'@objectstack/spec': patch +'@object-ui/types': patch +--- + +feat(plugin-grid): an aggregate bulk action that resolves with a `BulkActionResult` is reported per row: the rows it moved, the rows it refused with its own reasons, and the rows it did not confirm + +Clause-②: yes +Metadata-protocol: none + +The grid's bulk executor now reads the resolve value of an `execution: 'aggregate'` bulk handler. When it is a `BulkActionResult` (`{ succeeded: string[], failed: { id, message }[] }`, `BulkActionResultSchema` in `@objectstack/spec/ui`), the result panel shows how many selected rows were moved, lists each refused row under its record with the handler's `message` (and in the error CSV), and lists every selected row the result names in neither list as "not confirmed", never as succeeded. Ids are read against the dispatched `params._selectedIds`: an id outside the selection is dropped, a duplicate counts once, an id in both lists counts as failed, and when one id is in `failed` twice the first entry's message wins. A rejection is unchanged: it stays one outcome for the whole selection. + +A handler that partly succeeds no longer has to reject to avoid being reported as full success: resolve with the per-row answer instead. The `[PLANNED — not enforced]` marker is removed from `BulkActionResultSchema`'s description and its reference page, and the "all-or-nothing" wording is removed from the `bulkActionDefs` description (`@objectstack/spec`) and the `BulkActionDef.execution` TSDoc (`@object-ui/types`). + +**Declared behaviour change.** An existing aggregate handler whose own return value carries a top-level `succeeded` or `failed` member in another form (for example counts, `{ succeeded: 2, failed: 1 }`, or only one of the two lists) was reported as full success and is now reported as "unreadable": the panel says the action finished but its result could not be read, prints no per-row count, and the grid re-reads its rows when the dialog closes. To keep the success report, return a value with neither member (a summary under another name), or return both lists in the `BulkActionResult` shape. A handler that returns nothing, or a value with neither member, keeps today's report. + +The widening is additive: three new keys in every locale pack `@object-ui/i18n` publishes (`grid.bulk.resultNotConfirmed`, `grid.bulk.notConfirmedRecords`, `grid.bulk.aggregateUnreadable`). No metadata key, value or default changes. diff --git a/content/docs/references/api/protocol.mdx b/content/docs/references/api/protocol.mdx index f24938a4721..33b50fb99a8 100644 --- a/content/docs/references/api/protocol.mdx +++ b/content/docs/references/api/protocol.mdx @@ -2015,7 +2015,7 @@ The published metadata item body, opaque by ruling (1C). Shape is the item's own | **fieldOrder** | `string[]` | optional | Explicit field display order for this view — the ORDERING of the per-view field composition `columns` x `hiddenFields` x `fieldOrder`: it sorts what survives `columns` minus `hiddenFields` and never adds a field. A surviving column absent from `fieldOrder` sorts LAST, after every listed one, keeping its `columns`-relative order; a name listed here that did not survive orders nothing. | | **rowActions** | `string[]` | optional | Actions available for individual row items | | **bulkActions** | `string[]` | optional | Actions available when multiple rows are selected | -| **bulkActionDefs** | `{ name: string; label?: string; icon?: string; variant?: Enum<'primary' \| 'secondary' \| 'danger' \| 'ghost' \| 'outline'>; … }[]` | optional | Rich bulk action definitions (schema-driven, executed via BulkActionDialog). Use a def for a mass data-plane mutation ('update' with a `patch` / 'delete') that no action expresses, or for an `operation: 'custom'` + `execution: 'aggregate'` entry that dispatches the action it NAMES once for the whole selection — the renderer injects `params._selectedIds: string[]` (read that on the server, not `recordId`) so a single call can produce one aggregate artifact (zip of QR codes, merged PDF, batch print). Aggregate results are all-or-nothing: a handler that cannot cover the whole selection must reject, and per-row retry is replaced by re-running the action. `batchSize` does not apply (the call is never chunked); set `maxRecords` on defs whose server work is expensive. For the PER-RECORD dispatch use `bulkActions: ['']` instead — the bare-string form, promoted with the action's own label, params and `visible`; a 'custom' def without `execution: 'aggregate'` has no dispatcher and is refused at parse time. Toolbar url/api actions can also interpolate the current selection via `${ctx.selection.ids}` / `${ctx.selection.count}`. | +| **bulkActionDefs** | `{ name: string; label?: string; icon?: string; variant?: Enum<'primary' \| 'secondary' \| 'danger' \| 'ghost' \| 'outline'>; … }[]` | optional | Rich bulk action definitions (schema-driven, executed via BulkActionDialog). Use a def for a mass data-plane mutation ('update' with a `patch` / 'delete') that no action expresses, or for an `operation: 'custom'` + `execution: 'aggregate'` entry that dispatches the action it NAMES once for the whole selection — the renderer injects `params._selectedIds: string[]` (read that on the server, not `recordId`) so a single call can produce one aggregate artifact (zip of QR codes, merged PDF, batch print). A rejection is one outcome for the whole selection; a run that moved some rows and refused others resolves with a `BulkActionResult` (`{ succeeded, failed }`), a non-empty `failed` being a legal success answer. Per-row retry is replaced by re-running the action. `batchSize` does not apply (the call is never chunked); set `maxRecords` on defs whose server work is expensive. For the PER-RECORD dispatch use `bulkActions: ['']` instead — the bare-string form, promoted with the action's own label, params and `visible`; a 'custom' def without `execution: 'aggregate'` has no dispatcher and is refused at parse time. Toolbar url/api actions can also interpolate the current selection via `${ctx.selection.ids}` / `${ctx.selection.count}`. | | **conditionalFormatting** | `{ condition: string \| object; style: Record }[]` | optional | Conditional formatting rules for list rows | | **inlineEdit** | `boolean` | optional | Allow inline editing of records directly in the list view | | **exportOptions** | `Enum<'csv' \| 'xlsx' \| 'json'>[] \| { formats?: Enum<'csv' \| 'xlsx' \| 'json'>[]; maxRecords?: integer; includeHeaders?: boolean; fileNamePrefix?: string; … }` | optional | Export configuration for the list toolbar export menu: `{ formats?, maxRecords?, includeHeaders?, fileNamePrefix?, streaming? }`. A bare format array is the legacy spelling and lifts to `{ formats: [...] }` at parse. | @@ -2095,7 +2095,7 @@ The published metadata item body, opaque by ruling (1C). Shape is the item's own | **fieldOrder** | `string[]` | optional | Explicit field display order for this view — the ORDERING of the per-view field composition `columns` x `hiddenFields` x `fieldOrder`: it sorts what survives `columns` minus `hiddenFields` and never adds a field. A surviving column absent from `fieldOrder` sorts LAST, after every listed one, keeping its `columns`-relative order; a name listed here that did not survive orders nothing. | | **rowActions** | `string[]` | optional | Actions available for individual row items | | **bulkActions** | `string[]` | optional | Actions available when multiple rows are selected | -| **bulkActionDefs** | `{ name: string; label?: string; icon?: string; variant?: Enum<'primary' \| 'secondary' \| 'danger' \| 'ghost' \| 'outline'>; … }[]` | optional | Rich bulk action definitions (schema-driven, executed via BulkActionDialog). Use a def for a mass data-plane mutation ('update' with a `patch` / 'delete') that no action expresses, or for an `operation: 'custom'` + `execution: 'aggregate'` entry that dispatches the action it NAMES once for the whole selection — the renderer injects `params._selectedIds: string[]` (read that on the server, not `recordId`) so a single call can produce one aggregate artifact (zip of QR codes, merged PDF, batch print). Aggregate results are all-or-nothing: a handler that cannot cover the whole selection must reject, and per-row retry is replaced by re-running the action. `batchSize` does not apply (the call is never chunked); set `maxRecords` on defs whose server work is expensive. For the PER-RECORD dispatch use `bulkActions: ['']` instead — the bare-string form, promoted with the action's own label, params and `visible`; a 'custom' def without `execution: 'aggregate'` has no dispatcher and is refused at parse time. Toolbar url/api actions can also interpolate the current selection via `${ctx.selection.ids}` / `${ctx.selection.count}`. | +| **bulkActionDefs** | `{ name: string; label?: string; icon?: string; variant?: Enum<'primary' \| 'secondary' \| 'danger' \| 'ghost' \| 'outline'>; … }[]` | optional | Rich bulk action definitions (schema-driven, executed via BulkActionDialog). Use a def for a mass data-plane mutation ('update' with a `patch` / 'delete') that no action expresses, or for an `operation: 'custom'` + `execution: 'aggregate'` entry that dispatches the action it NAMES once for the whole selection — the renderer injects `params._selectedIds: string[]` (read that on the server, not `recordId`) so a single call can produce one aggregate artifact (zip of QR codes, merged PDF, batch print). A rejection is one outcome for the whole selection; a run that moved some rows and refused others resolves with a `BulkActionResult` (`{ succeeded, failed }`), a non-empty `failed` being a legal success answer. Per-row retry is replaced by re-running the action. `batchSize` does not apply (the call is never chunked); set `maxRecords` on defs whose server work is expensive. For the PER-RECORD dispatch use `bulkActions: ['']` instead — the bare-string form, promoted with the action's own label, params and `visible`; a 'custom' def without `execution: 'aggregate'` has no dispatcher and is refused at parse time. Toolbar url/api actions can also interpolate the current selection via `${ctx.selection.ids}` / `${ctx.selection.count}`. | | **conditionalFormatting** | `{ condition: string \| object; style: Record }[]` | optional | Conditional formatting rules for list rows | | **inlineEdit** | `boolean` | optional | Allow inline editing of records directly in the list view | | **exportOptions** | `Enum<'csv' \| 'xlsx' \| 'json'>[] \| { formats?: Enum<'csv' \| 'xlsx' \| 'json'>[]; maxRecords?: integer; includeHeaders?: boolean; fileNamePrefix?: string; … }` | optional | Export configuration for the list toolbar export menu: `{ formats?, maxRecords?, includeHeaders?, fileNamePrefix?, streaming? }`. A bare format array is the legacy spelling and lifts to `{ formats: [...] }` at parse. | diff --git a/content/docs/references/data/object.mdx b/content/docs/references/data/object.mdx index 75c9fbba046..2ec5e990cbb 100644 --- a/content/docs/references/data/object.mdx +++ b/content/docs/references/data/object.mdx @@ -417,7 +417,7 @@ const result = ApiMethod.parse(data); | **fieldOrder** | `string[]` | optional | Explicit field display order for this view — the ORDERING of the per-view field composition `columns` x `hiddenFields` x `fieldOrder`: it sorts what survives `columns` minus `hiddenFields` and never adds a field. A surviving column absent from `fieldOrder` sorts LAST, after every listed one, keeping its `columns`-relative order; a name listed here that did not survive orders nothing. | | **rowActions** | `string[]` | optional | Actions available for individual row items | | **bulkActions** | `string[]` | optional | Actions available when multiple rows are selected | -| **bulkActionDefs** | `{ name: string; label?: string; icon?: string; variant?: Enum<'primary' \| 'secondary' \| 'danger' \| 'ghost' \| 'outline'>; … }[]` | optional | Rich bulk action definitions (schema-driven, executed via BulkActionDialog). Use a def for a mass data-plane mutation ('update' with a `patch` / 'delete') that no action expresses, or for an `operation: 'custom'` + `execution: 'aggregate'` entry that dispatches the action it NAMES once for the whole selection — the renderer injects `params._selectedIds: string[]` (read that on the server, not `recordId`) so a single call can produce one aggregate artifact (zip of QR codes, merged PDF, batch print). Aggregate results are all-or-nothing: a handler that cannot cover the whole selection must reject, and per-row retry is replaced by re-running the action. `batchSize` does not apply (the call is never chunked); set `maxRecords` on defs whose server work is expensive. For the PER-RECORD dispatch use `bulkActions: ['']` instead — the bare-string form, promoted with the action's own label, params and `visible`; a 'custom' def without `execution: 'aggregate'` has no dispatcher and is refused at parse time. Toolbar url/api actions can also interpolate the current selection via `${ctx.selection.ids}` / `${ctx.selection.count}`. | +| **bulkActionDefs** | `{ name: string; label?: string; icon?: string; variant?: Enum<'primary' \| 'secondary' \| 'danger' \| 'ghost' \| 'outline'>; … }[]` | optional | Rich bulk action definitions (schema-driven, executed via BulkActionDialog). Use a def for a mass data-plane mutation ('update' with a `patch` / 'delete') that no action expresses, or for an `operation: 'custom'` + `execution: 'aggregate'` entry that dispatches the action it NAMES once for the whole selection — the renderer injects `params._selectedIds: string[]` (read that on the server, not `recordId`) so a single call can produce one aggregate artifact (zip of QR codes, merged PDF, batch print). A rejection is one outcome for the whole selection; a run that moved some rows and refused others resolves with a `BulkActionResult` (`{ succeeded, failed }`), a non-empty `failed` being a legal success answer. Per-row retry is replaced by re-running the action. `batchSize` does not apply (the call is never chunked); set `maxRecords` on defs whose server work is expensive. For the PER-RECORD dispatch use `bulkActions: ['']` instead — the bare-string form, promoted with the action's own label, params and `visible`; a 'custom' def without `execution: 'aggregate'` has no dispatcher and is refused at parse time. Toolbar url/api actions can also interpolate the current selection via `${ctx.selection.ids}` / `${ctx.selection.count}`. | | **conditionalFormatting** | `{ condition: string \| object; style: Record }[]` | optional | Conditional formatting rules for list rows | | **inlineEdit** | `boolean` | optional | Allow inline editing of records directly in the list view | | **exportOptions** | `Enum<'csv' \| 'xlsx' \| 'json'>[] \| { formats?: Enum<'csv' \| 'xlsx' \| 'json'>[]; maxRecords?: integer; includeHeaders?: boolean; fileNamePrefix?: string; … }` | optional | Export configuration for the list toolbar export menu: `{ formats?, maxRecords?, includeHeaders?, fileNamePrefix?, streaming? }`. A bare format array is the legacy spelling and lifts to `{ formats: [...] }` at parse. | diff --git a/content/docs/references/ui/bulk-action.mdx b/content/docs/references/ui/bulk-action.mdx index 4eed67bf702..4c857d76386 100644 --- a/content/docs/references/ui/bulk-action.mdx +++ b/content/docs/references/ui/bulk-action.mdx @@ -179,14 +179,14 @@ const result = BulkActionDefSchema.parse(data); ## BulkActionResult -[PLANNED — not enforced] The per-row outcome an `execution: 'aggregate'` bulk action handler MAY resolve with: `{ succeeded: [ids], failed: [{ id, message }] }` as its whole resolve value, never attached to a rejection (a rejection stays one outcome for the selection). The console does not read it yet, so until its reader lands a handler that cannot cover the whole selection must still reject: a resolved aggregate call is counted as covering every selected row. Not the data plane's batch answer: here `succeeded` and `failed` are row lists, not counts. Once read: a value with neither member keeps the one-outcome report; a value with either member that does not parse is reported as unreadable, never as full success; members beyond the two lists carry no meaning. Ids must be dispatched `params._selectedIds`: an id outside the selection is dropped, a duplicate counts once, an id in both lists counts as failed, and a selected id in neither list is reported as not confirmed, never as succeeded. +The per-row outcome an `execution: 'aggregate'` bulk action handler MAY resolve with: `{ succeeded: [ids], failed: [{ id, message }] }` as its whole resolve value, never attached to a rejection (a rejection stays one outcome for the selection). The console reads it on every aggregate dispatch. Not the data plane's batch answer: here `succeeded` and `failed` are row lists, not counts. A value with neither member keeps the one-outcome report; a value with either member that does not parse is reported as unreadable, never as full success; members beyond the two lists carry no meaning. Ids must be dispatched `params._selectedIds`: an id outside the selection is dropped, a duplicate counts once, an id in both lists counts as failed, an id in `failed` twice keeps its first message, and a selected id in neither list is reported as not confirmed, never as succeeded. ### Properties | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | -| **succeeded** | `string[]` | ✅ | Ids of the selected rows the handler wrote. Each must be one of the dispatched `params._selectedIds`. The planned reader will drop an id outside the selection, count a duplicate once, and count an id that is also in `failed` as failed. | -| **failed** | `({ id: string; message: string } & Record)[]` | ✅ | One entry per selected row the handler did not write, each with its own reason (`message`, not `error`). The planned reader will drop an id outside `params._selectedIds` and count a duplicate once. | +| **succeeded** | `string[]` | ✅ | Ids of the selected rows the handler wrote. Each must be one of the dispatched `params._selectedIds`. The reader drops an id outside the selection, counts a duplicate once, and counts an id that is also in `failed` as failed. | +| **failed** | `({ id: string; message: string } & Record)[]` | ✅ | One entry per selected row the handler did not write, each with its own reason (`message`, not `error`). The reader drops an id outside `params._selectedIds` and counts a duplicate once; an id listed twice keeps its first `message`. | ### Nested Shape: `BulkActionResult.failed[number]` diff --git a/content/docs/references/ui/view.mdx b/content/docs/references/ui/view.mdx index 72e5cbdf36c..84bad929c6f 100644 --- a/content/docs/references/ui/view.mdx +++ b/content/docs/references/ui/view.mdx @@ -810,7 +810,7 @@ Map view configuration | **fieldOrder** | `string[]` | optional | Explicit field display order for this view — the ORDERING of the per-view field composition `columns` x `hiddenFields` x `fieldOrder`: it sorts what survives `columns` minus `hiddenFields` and never adds a field. A surviving column absent from `fieldOrder` sorts LAST, after every listed one, keeping its `columns`-relative order; a name listed here that did not survive orders nothing. | | **rowActions** | `string[]` | optional | Actions available for individual row items | | **bulkActions** | `string[]` | optional | Actions available when multiple rows are selected | -| **bulkActionDefs** | `{ name: string; label?: string; icon?: string; variant?: Enum<'primary' \| 'secondary' \| 'danger' \| 'ghost' \| 'outline'>; … }[]` | optional | Rich bulk action definitions (schema-driven, executed via BulkActionDialog). Use a def for a mass data-plane mutation ('update' with a `patch` / 'delete') that no action expresses, or for an `operation: 'custom'` + `execution: 'aggregate'` entry that dispatches the action it NAMES once for the whole selection — the renderer injects `params._selectedIds: string[]` (read that on the server, not `recordId`) so a single call can produce one aggregate artifact (zip of QR codes, merged PDF, batch print). Aggregate results are all-or-nothing: a handler that cannot cover the whole selection must reject, and per-row retry is replaced by re-running the action. `batchSize` does not apply (the call is never chunked); set `maxRecords` on defs whose server work is expensive. For the PER-RECORD dispatch use `bulkActions: ['']` instead — the bare-string form, promoted with the action's own label, params and `visible`; a 'custom' def without `execution: 'aggregate'` has no dispatcher and is refused at parse time. Toolbar url/api actions can also interpolate the current selection via `${ctx.selection.ids}` / `${ctx.selection.count}`. | +| **bulkActionDefs** | `{ name: string; label?: string; icon?: string; variant?: Enum<'primary' \| 'secondary' \| 'danger' \| 'ghost' \| 'outline'>; … }[]` | optional | Rich bulk action definitions (schema-driven, executed via BulkActionDialog). Use a def for a mass data-plane mutation ('update' with a `patch` / 'delete') that no action expresses, or for an `operation: 'custom'` + `execution: 'aggregate'` entry that dispatches the action it NAMES once for the whole selection — the renderer injects `params._selectedIds: string[]` (read that on the server, not `recordId`) so a single call can produce one aggregate artifact (zip of QR codes, merged PDF, batch print). A rejection is one outcome for the whole selection; a run that moved some rows and refused others resolves with a `BulkActionResult` (`{ succeeded, failed }`), a non-empty `failed` being a legal success answer. Per-row retry is replaced by re-running the action. `batchSize` does not apply (the call is never chunked); set `maxRecords` on defs whose server work is expensive. For the PER-RECORD dispatch use `bulkActions: ['']` instead — the bare-string form, promoted with the action's own label, params and `visible`; a 'custom' def without `execution: 'aggregate'` has no dispatcher and is refused at parse time. Toolbar url/api actions can also interpolate the current selection via `${ctx.selection.ids}` / `${ctx.selection.count}`. | | **conditionalFormatting** | `{ condition: string \| object; style: Record }[]` | optional | Conditional formatting rules for list rows | | **inlineEdit** | `boolean` | optional | Allow inline editing of records directly in the list view | | **exportOptions** | `Enum<'csv' \| 'xlsx' \| 'json'>[] \| { formats?: Enum<'csv' \| 'xlsx' \| 'json'>[]; maxRecords?: integer; includeHeaders?: boolean; fileNamePrefix?: string; … }` | optional | Export configuration for the list toolbar export menu: `{ formats?, maxRecords?, includeHeaders?, fileNamePrefix?, streaming? }`. A bare format array is the legacy spelling and lifts to `{ formats: [...] }` at parse. | @@ -1207,7 +1207,7 @@ An any-of group: `{ or: [rule, ...] }` matches a record when ANY of its rules ma | **fieldOrder** | `string[]` | optional | Explicit field display order for this view — the ORDERING of the per-view field composition `columns` x `hiddenFields` x `fieldOrder`: it sorts what survives `columns` minus `hiddenFields` and never adds a field. A surviving column absent from `fieldOrder` sorts LAST, after every listed one, keeping its `columns`-relative order; a name listed here that did not survive orders nothing. | | **rowActions** | `string[]` | optional | Actions available for individual row items | | **bulkActions** | `string[]` | optional | Actions available when multiple rows are selected | -| **bulkActionDefs** | `{ name: string; label?: string; icon?: string; variant?: Enum<'primary' \| 'secondary' \| 'danger' \| 'ghost' \| 'outline'>; … }[]` | optional | Rich bulk action definitions (schema-driven, executed via BulkActionDialog). Use a def for a mass data-plane mutation ('update' with a `patch` / 'delete') that no action expresses, or for an `operation: 'custom'` + `execution: 'aggregate'` entry that dispatches the action it NAMES once for the whole selection — the renderer injects `params._selectedIds: string[]` (read that on the server, not `recordId`) so a single call can produce one aggregate artifact (zip of QR codes, merged PDF, batch print). Aggregate results are all-or-nothing: a handler that cannot cover the whole selection must reject, and per-row retry is replaced by re-running the action. `batchSize` does not apply (the call is never chunked); set `maxRecords` on defs whose server work is expensive. For the PER-RECORD dispatch use `bulkActions: ['']` instead — the bare-string form, promoted with the action's own label, params and `visible`; a 'custom' def without `execution: 'aggregate'` has no dispatcher and is refused at parse time. Toolbar url/api actions can also interpolate the current selection via `${ctx.selection.ids}` / `${ctx.selection.count}`. | +| **bulkActionDefs** | `{ name: string; label?: string; icon?: string; variant?: Enum<'primary' \| 'secondary' \| 'danger' \| 'ghost' \| 'outline'>; … }[]` | optional | Rich bulk action definitions (schema-driven, executed via BulkActionDialog). Use a def for a mass data-plane mutation ('update' with a `patch` / 'delete') that no action expresses, or for an `operation: 'custom'` + `execution: 'aggregate'` entry that dispatches the action it NAMES once for the whole selection — the renderer injects `params._selectedIds: string[]` (read that on the server, not `recordId`) so a single call can produce one aggregate artifact (zip of QR codes, merged PDF, batch print). A rejection is one outcome for the whole selection; a run that moved some rows and refused others resolves with a `BulkActionResult` (`{ succeeded, failed }`), a non-empty `failed` being a legal success answer. Per-row retry is replaced by re-running the action. `batchSize` does not apply (the call is never chunked); set `maxRecords` on defs whose server work is expensive. For the PER-RECORD dispatch use `bulkActions: ['']` instead — the bare-string form, promoted with the action's own label, params and `visible`; a 'custom' def without `execution: 'aggregate'` has no dispatcher and is refused at parse time. Toolbar url/api actions can also interpolate the current selection via `${ctx.selection.ids}` / `${ctx.selection.count}`. | | **conditionalFormatting** | `{ condition: string \| object; style: Record }[]` | optional | Conditional formatting rules for list rows | | **inlineEdit** | `boolean` | optional | Allow inline editing of records directly in the list view | | **exportOptions** | `Enum<'csv' \| 'xlsx' \| 'json'>[] \| { formats?: Enum<'csv' \| 'xlsx' \| 'json'>[]; maxRecords?: integer; includeHeaders?: boolean; fileNamePrefix?: string; … }` | optional | Export configuration for the list toolbar export menu: `{ formats?, maxRecords?, includeHeaders?, fileNamePrefix?, streaming? }`. A bare format array is the legacy spelling and lifts to `{ formats: [...] }` at parse. | @@ -1811,7 +1811,7 @@ Tab configuration for multi-tab view interface | **fieldOrder** | `string[]` | optional | Explicit field display order for this view — the ORDERING of the per-view field composition `columns` x `hiddenFields` x `fieldOrder`: it sorts what survives `columns` minus `hiddenFields` and never adds a field. A surviving column absent from `fieldOrder` sorts LAST, after every listed one, keeping its `columns`-relative order; a name listed here that did not survive orders nothing. | | **rowActions** | `string[]` | optional | Actions available for individual row items | | **bulkActions** | `string[]` | optional | Actions available when multiple rows are selected | -| **bulkActionDefs** | `{ name: string; label?: string; icon?: string; variant?: Enum<'primary' \| 'secondary' \| 'danger' \| 'ghost' \| 'outline'>; … }[]` | optional | Rich bulk action definitions (schema-driven, executed via BulkActionDialog). Use a def for a mass data-plane mutation ('update' with a `patch` / 'delete') that no action expresses, or for an `operation: 'custom'` + `execution: 'aggregate'` entry that dispatches the action it NAMES once for the whole selection — the renderer injects `params._selectedIds: string[]` (read that on the server, not `recordId`) so a single call can produce one aggregate artifact (zip of QR codes, merged PDF, batch print). Aggregate results are all-or-nothing: a handler that cannot cover the whole selection must reject, and per-row retry is replaced by re-running the action. `batchSize` does not apply (the call is never chunked); set `maxRecords` on defs whose server work is expensive. For the PER-RECORD dispatch use `bulkActions: ['']` instead — the bare-string form, promoted with the action's own label, params and `visible`; a 'custom' def without `execution: 'aggregate'` has no dispatcher and is refused at parse time. Toolbar url/api actions can also interpolate the current selection via `${ctx.selection.ids}` / `${ctx.selection.count}`. | +| **bulkActionDefs** | `{ name: string; label?: string; icon?: string; variant?: Enum<'primary' \| 'secondary' \| 'danger' \| 'ghost' \| 'outline'>; … }[]` | optional | Rich bulk action definitions (schema-driven, executed via BulkActionDialog). Use a def for a mass data-plane mutation ('update' with a `patch` / 'delete') that no action expresses, or for an `operation: 'custom'` + `execution: 'aggregate'` entry that dispatches the action it NAMES once for the whole selection — the renderer injects `params._selectedIds: string[]` (read that on the server, not `recordId`) so a single call can produce one aggregate artifact (zip of QR codes, merged PDF, batch print). A rejection is one outcome for the whole selection; a run that moved some rows and refused others resolves with a `BulkActionResult` (`{ succeeded, failed }`), a non-empty `failed` being a legal success answer. Per-row retry is replaced by re-running the action. `batchSize` does not apply (the call is never chunked); set `maxRecords` on defs whose server work is expensive. For the PER-RECORD dispatch use `bulkActions: ['']` instead — the bare-string form, promoted with the action's own label, params and `visible`; a 'custom' def without `execution: 'aggregate'` has no dispatcher and is refused at parse time. Toolbar url/api actions can also interpolate the current selection via `${ctx.selection.ids}` / `${ctx.selection.count}`. | | **conditionalFormatting** | `{ condition: string \| object; style: Record }[]` | optional | Conditional formatting rules for list rows | | **inlineEdit** | `boolean` | optional | Allow inline editing of records directly in the list view | | **exportOptions** | `Enum<'csv' \| 'xlsx' \| 'json'>[] \| { formats?: Enum<'csv' \| 'xlsx' \| 'json'>[]; maxRecords?: integer; includeHeaders?: boolean; fileNamePrefix?: string; … }` | optional | Export configuration for the list toolbar export menu: `{ formats?, maxRecords?, includeHeaders?, fileNamePrefix?, streaming? }`. A bare format array is the legacy spelling and lifts to `{ formats: [...] }` at parse. | @@ -1891,7 +1891,7 @@ Tab configuration for multi-tab view interface | **fieldOrder** | `string[]` | optional | Explicit field display order for this view — the ORDERING of the per-view field composition `columns` x `hiddenFields` x `fieldOrder`: it sorts what survives `columns` minus `hiddenFields` and never adds a field. A surviving column absent from `fieldOrder` sorts LAST, after every listed one, keeping its `columns`-relative order; a name listed here that did not survive orders nothing. | | **rowActions** | `string[]` | optional | Actions available for individual row items | | **bulkActions** | `string[]` | optional | Actions available when multiple rows are selected | -| **bulkActionDefs** | `{ name: string; label?: string; icon?: string; variant?: Enum<'primary' \| 'secondary' \| 'danger' \| 'ghost' \| 'outline'>; … }[]` | optional | Rich bulk action definitions (schema-driven, executed via BulkActionDialog). Use a def for a mass data-plane mutation ('update' with a `patch` / 'delete') that no action expresses, or for an `operation: 'custom'` + `execution: 'aggregate'` entry that dispatches the action it NAMES once for the whole selection — the renderer injects `params._selectedIds: string[]` (read that on the server, not `recordId`) so a single call can produce one aggregate artifact (zip of QR codes, merged PDF, batch print). Aggregate results are all-or-nothing: a handler that cannot cover the whole selection must reject, and per-row retry is replaced by re-running the action. `batchSize` does not apply (the call is never chunked); set `maxRecords` on defs whose server work is expensive. For the PER-RECORD dispatch use `bulkActions: ['']` instead — the bare-string form, promoted with the action's own label, params and `visible`; a 'custom' def without `execution: 'aggregate'` has no dispatcher and is refused at parse time. Toolbar url/api actions can also interpolate the current selection via `${ctx.selection.ids}` / `${ctx.selection.count}`. | +| **bulkActionDefs** | `{ name: string; label?: string; icon?: string; variant?: Enum<'primary' \| 'secondary' \| 'danger' \| 'ghost' \| 'outline'>; … }[]` | optional | Rich bulk action definitions (schema-driven, executed via BulkActionDialog). Use a def for a mass data-plane mutation ('update' with a `patch` / 'delete') that no action expresses, or for an `operation: 'custom'` + `execution: 'aggregate'` entry that dispatches the action it NAMES once for the whole selection — the renderer injects `params._selectedIds: string[]` (read that on the server, not `recordId`) so a single call can produce one aggregate artifact (zip of QR codes, merged PDF, batch print). A rejection is one outcome for the whole selection; a run that moved some rows and refused others resolves with a `BulkActionResult` (`{ succeeded, failed }`), a non-empty `failed` being a legal success answer. Per-row retry is replaced by re-running the action. `batchSize` does not apply (the call is never chunked); set `maxRecords` on defs whose server work is expensive. For the PER-RECORD dispatch use `bulkActions: ['']` instead — the bare-string form, promoted with the action's own label, params and `visible`; a 'custom' def without `execution: 'aggregate'` has no dispatcher and is refused at parse time. Toolbar url/api actions can also interpolate the current selection via `${ctx.selection.ids}` / `${ctx.selection.count}`. | | **conditionalFormatting** | `{ condition: string \| object; style: Record }[]` | optional | Conditional formatting rules for list rows | | **inlineEdit** | `boolean` | optional | Allow inline editing of records directly in the list view | | **exportOptions** | `Enum<'csv' \| 'xlsx' \| 'json'>[] \| { formats?: Enum<'csv' \| 'xlsx' \| 'json'>[]; maxRecords?: integer; includeHeaders?: boolean; fileNamePrefix?: string; … }` | optional | Export configuration for the list toolbar export menu: `{ formats?, maxRecords?, includeHeaders?, fileNamePrefix?, streaming? }`. A bare format array is the legacy spelling and lifts to `{ formats: [...] }` at parse. | @@ -2189,7 +2189,7 @@ This schema accepts one of the following structures: | **fieldOrder** | `string[]` | optional | Explicit field display order for this view — the ORDERING of the per-view field composition `columns` x `hiddenFields` x `fieldOrder`: it sorts what survives `columns` minus `hiddenFields` and never adds a field. A surviving column absent from `fieldOrder` sorts LAST, after every listed one, keeping its `columns`-relative order; a name listed here that did not survive orders nothing. | | **rowActions** | `string[]` | optional | Actions available for individual row items | | **bulkActions** | `string[]` | optional | Actions available when multiple rows are selected | -| **bulkActionDefs** | `{ name: string; label?: string; icon?: string; variant?: Enum<'primary' \| 'secondary' \| 'danger' \| 'ghost' \| 'outline'>; … }[]` | optional | Rich bulk action definitions (schema-driven, executed via BulkActionDialog). Use a def for a mass data-plane mutation ('update' with a `patch` / 'delete') that no action expresses, or for an `operation: 'custom'` + `execution: 'aggregate'` entry that dispatches the action it NAMES once for the whole selection — the renderer injects `params._selectedIds: string[]` (read that on the server, not `recordId`) so a single call can produce one aggregate artifact (zip of QR codes, merged PDF, batch print). Aggregate results are all-or-nothing: a handler that cannot cover the whole selection must reject, and per-row retry is replaced by re-running the action. `batchSize` does not apply (the call is never chunked); set `maxRecords` on defs whose server work is expensive. For the PER-RECORD dispatch use `bulkActions: ['']` instead — the bare-string form, promoted with the action's own label, params and `visible`; a 'custom' def without `execution: 'aggregate'` has no dispatcher and is refused at parse time. Toolbar url/api actions can also interpolate the current selection via `${ctx.selection.ids}` / `${ctx.selection.count}`. | +| **bulkActionDefs** | `{ name: string; label?: string; icon?: string; variant?: Enum<'primary' \| 'secondary' \| 'danger' \| 'ghost' \| 'outline'>; … }[]` | optional | Rich bulk action definitions (schema-driven, executed via BulkActionDialog). Use a def for a mass data-plane mutation ('update' with a `patch` / 'delete') that no action expresses, or for an `operation: 'custom'` + `execution: 'aggregate'` entry that dispatches the action it NAMES once for the whole selection — the renderer injects `params._selectedIds: string[]` (read that on the server, not `recordId`) so a single call can produce one aggregate artifact (zip of QR codes, merged PDF, batch print). A rejection is one outcome for the whole selection; a run that moved some rows and refused others resolves with a `BulkActionResult` (`{ succeeded, failed }`), a non-empty `failed` being a legal success answer. Per-row retry is replaced by re-running the action. `batchSize` does not apply (the call is never chunked); set `maxRecords` on defs whose server work is expensive. For the PER-RECORD dispatch use `bulkActions: ['']` instead — the bare-string form, promoted with the action's own label, params and `visible`; a 'custom' def without `execution: 'aggregate'` has no dispatcher and is refused at parse time. Toolbar url/api actions can also interpolate the current selection via `${ctx.selection.ids}` / `${ctx.selection.count}`. | | **conditionalFormatting** | `{ condition: string \| object; style: Record }[]` | optional | Conditional formatting rules for list rows | | **inlineEdit** | `boolean` | optional | Allow inline editing of records directly in the list view | | **exportOptions** | `Enum<'csv' \| 'xlsx' \| 'json'>[] \| { formats?: Enum<'csv' \| 'xlsx' \| 'json'>[]; maxRecords?: integer; includeHeaders?: boolean; fileNamePrefix?: string; … }` | optional | Export configuration for the list toolbar export menu: `{ formats?, maxRecords?, includeHeaders?, fileNamePrefix?, streaming? }`. A bare format array is the legacy spelling and lifts to `{ formats: [...] }` at parse. | @@ -2378,7 +2378,7 @@ This schema accepts one of the following structures: | **fieldOrder** | `string[]` | optional | Explicit field display order for this view — the ORDERING of the per-view field composition `columns` x `hiddenFields` x `fieldOrder`: it sorts what survives `columns` minus `hiddenFields` and never adds a field. A surviving column absent from `fieldOrder` sorts LAST, after every listed one, keeping its `columns`-relative order; a name listed here that did not survive orders nothing. | | **rowActions** | `string[]` | optional | Actions available for individual row items | | **bulkActions** | `string[]` | optional | Actions available when multiple rows are selected | -| **bulkActionDefs** | `{ name: string; label?: string; icon?: string; variant?: Enum<'primary' \| 'secondary' \| 'danger' \| 'ghost' \| 'outline'>; … }[]` | optional | Rich bulk action definitions (schema-driven, executed via BulkActionDialog). Use a def for a mass data-plane mutation ('update' with a `patch` / 'delete') that no action expresses, or for an `operation: 'custom'` + `execution: 'aggregate'` entry that dispatches the action it NAMES once for the whole selection — the renderer injects `params._selectedIds: string[]` (read that on the server, not `recordId`) so a single call can produce one aggregate artifact (zip of QR codes, merged PDF, batch print). Aggregate results are all-or-nothing: a handler that cannot cover the whole selection must reject, and per-row retry is replaced by re-running the action. `batchSize` does not apply (the call is never chunked); set `maxRecords` on defs whose server work is expensive. For the PER-RECORD dispatch use `bulkActions: ['']` instead — the bare-string form, promoted with the action's own label, params and `visible`; a 'custom' def without `execution: 'aggregate'` has no dispatcher and is refused at parse time. Toolbar url/api actions can also interpolate the current selection via `${ctx.selection.ids}` / `${ctx.selection.count}`. | +| **bulkActionDefs** | `{ name: string; label?: string; icon?: string; variant?: Enum<'primary' \| 'secondary' \| 'danger' \| 'ghost' \| 'outline'>; … }[]` | optional | Rich bulk action definitions (schema-driven, executed via BulkActionDialog). Use a def for a mass data-plane mutation ('update' with a `patch` / 'delete') that no action expresses, or for an `operation: 'custom'` + `execution: 'aggregate'` entry that dispatches the action it NAMES once for the whole selection — the renderer injects `params._selectedIds: string[]` (read that on the server, not `recordId`) so a single call can produce one aggregate artifact (zip of QR codes, merged PDF, batch print). A rejection is one outcome for the whole selection; a run that moved some rows and refused others resolves with a `BulkActionResult` (`{ succeeded, failed }`), a non-empty `failed` being a legal success answer. Per-row retry is replaced by re-running the action. `batchSize` does not apply (the call is never chunked); set `maxRecords` on defs whose server work is expensive. For the PER-RECORD dispatch use `bulkActions: ['']` instead — the bare-string form, promoted with the action's own label, params and `visible`; a 'custom' def without `execution: 'aggregate'` has no dispatcher and is refused at parse time. Toolbar url/api actions can also interpolate the current selection via `${ctx.selection.ids}` / `${ctx.selection.count}`. | | **conditionalFormatting** | `{ condition: string \| object; style: Record }[]` | optional | Conditional formatting rules for list rows | | **inlineEdit** | `boolean` | optional | Allow inline editing of records directly in the list view | | **exportOptions** | `Enum<'csv' \| 'xlsx' \| 'json'>[] \| { formats?: Enum<'csv' \| 'xlsx' \| 'json'>[]; maxRecords?: integer; includeHeaders?: boolean; fileNamePrefix?: string; … }` | optional | Export configuration for the list toolbar export menu: `{ formats?, maxRecords?, includeHeaders?, fileNamePrefix?, streaming? }`. A bare format array is the legacy spelling and lifts to `{ formats: [...] }` at parse. | diff --git a/content/docs/ui/views.mdx b/content/docs/ui/views.mdx index 2a471ef99b4..2e7a969748f 100644 --- a/content/docs/ui/views.mdx +++ b/content/docs/ui/views.mdx @@ -254,11 +254,21 @@ bulkActionDefs: [ ``` An aggregate dispatch delivers the selection to the handler as -`params._selectedIds: string[]` — read that, **not** `recordId`. Results are -all-or-nothing: a handler that cannot cover the whole selection must reject, -and per-row retry is replaced by re-running the action. `batchSize` does not -apply (the call is never chunked); set `maxRecords` when the server work is -expensive. +`params._selectedIds: string[]` — read that, **not** `recordId`. Per-row retry +is replaced by re-running the action. `batchSize` does not apply (the call is +never chunked); set `maxRecords` when the server work is expensive. + +A handler that moved some rows and refused others resolves with a +`BulkActionResult` (`@objectstack/spec/ui`) as its whole return value: +`{ succeeded: string[], failed: { id, message }[] }`. The result dialog then +counts the moved rows, lists each refused row under its record with its +`message`, and lists every selected row named in neither list as **not +confirmed** — never as succeeded. Ids are read against `_selectedIds`: one +outside the selection is dropped, a duplicate counts once, an id in both lists +counts as failed. A return value with neither member (nothing, a summary, a +download link) counts as covering the whole selection; one that carries +`succeeded` or `failed` in any other form (counts, only one list) is reported +as an unreadable result, never as full success. A rejection is reported as **one outcome for the whole selection**: the result dialog says the action did not complete for the selected records and shows the diff --git a/packages/spec/src/ui/bulk-action.zod.ts b/packages/spec/src/ui/bulk-action.zod.ts index 09291dc0c8a..83aa6f19110 100644 --- a/packages/spec/src/ui/bulk-action.zod.ts +++ b/packages/spec/src/ui/bulk-action.zod.ts @@ -124,11 +124,8 @@ export type BulkActionExecution = z.input; * The per-row outcome an `execution: 'aggregate'` handler MAY resolve with * (#34216, seat ruling 6905490575, option A). * - * **[PLANNED — not enforced]** Declared ahead of its reader. The console does - * NOT read this value yet: the grid's bulk reader is #34269. Until that lands - * the grid counts a resolved aggregate call as covering the whole selection, - * so a handler that cannot cover the whole selection must still REJECT. A - * handler that resolves with `failed` rows today is reported as full success. + * Read by the grid's aggregate reader in `@object-ui/plugin-grid` on every + * `execution: 'aggregate'` dispatch, by the rules below. * * An aggregate dispatch is ONE call carrying the whole selection in * `params._selectedIds`, so the call's own success or failure is one outcome @@ -137,8 +134,8 @@ export type BulkActionExecution = z.input; * completed", never which rows changed. This is that answer. * * **Resolve value only — never a rejection.** The object IS the handler's - * whole resolve value (no wrapper key). Once the reader (#34269) lands, a run - * that moved some rows and refused others resolves with it, a non-empty + * whole resolve value (no wrapper key). A run that moved some rows and + * refused others resolves with it, a non-empty * `failed` being a legal success answer. A rejection keeps meaning "the * handler could not produce an outcome" and stays the one-outcome report: the * `/actions` door carries no structured body on a script or flow arm's throw @@ -153,7 +150,7 @@ export type BulkActionExecution = z.input; * `succeeded` and `failed` are the row LISTS themselves and a failure's reason * is `message`. A value shaped like either neighbour does not parse. * - * **How the reader (#34269) will read it** — only on an + * **How the reader reads it** — only on an * `execution: 'aggregate'` dispatch: * - A value with NEITHER a `succeeded` nor a `failed` member (nothing, a * summary, an artifact link) keeps the one-outcome report: the shape is @@ -164,36 +161,37 @@ export type BulkActionExecution = z.input; * written by a handler, not by an author) and carry no meaning, so a * handler may return a summary beside them. * - * **How the reader (#34269) will count ids.** Every id must be one of the + * **How the reader counts ids.** Every id must be one of the * dispatched `params._selectedIds`: * - an id outside the selection is a handler bug: dropped, counted nowhere; * - a duplicate id counts once; * - an id in BOTH lists counts as failed; + * - an id in `failed` twice is reported with its FIRST entry's `message`; * - a selected id in NEITHER list is reported as not confirmed, never as * succeeded. */ export const BulkActionResultSchema = lazySchema(() => z.looseObject({ succeeded: z.array(z.string()).describe( - 'Ids of the selected rows the handler wrote. Each must be one of the dispatched `params._selectedIds`. The planned ' - + 'reader will drop an id outside the selection, count a duplicate once, and count an id that is also in `failed` as failed.', + 'Ids of the selected rows the handler wrote. Each must be one of the dispatched `params._selectedIds`. The ' + + 'reader drops an id outside the selection, counts a duplicate once, and counts an id that is also in `failed` as failed.', ), failed: z.array(z.looseObject({ id: z.string().describe('Id of a selected row the handler did not write: one of the dispatched `params._selectedIds`.'), message: z.string().describe('Why this row was not written, as the person running the action should read it.'), })).describe( - 'One entry per selected row the handler did not write, each with its own reason (`message`, not `error`). The planned ' - + 'reader will drop an id outside `params._selectedIds` and count a duplicate once.', + 'One entry per selected row the handler did not write, each with its own reason (`message`, not `error`). The ' + + 'reader drops an id outside `params._selectedIds` and counts a duplicate once; an id listed twice keeps its first `message`.', ), }).describe( - '[PLANNED — not enforced] The per-row outcome an `execution: \'aggregate\'` bulk action handler MAY resolve with: ' + 'The per-row outcome an `execution: \'aggregate\'` bulk action handler MAY resolve with: ' + '`{ succeeded: [ids], failed: [{ id, message }] }` as its whole resolve value, never attached to a rejection (a ' - + 'rejection stays one outcome for the selection). The console does not read it yet, so until its reader lands a ' - + 'handler that cannot cover the whole selection must still reject: a resolved aggregate call is counted as covering ' - + 'every selected row. Not the data plane\'s batch answer: here `succeeded` and `failed` are row lists, not counts. ' - + 'Once read: a value with neither member keeps the one-outcome report; a value with either member that does not ' + + 'rejection stays one outcome for the selection). The console reads it on every aggregate dispatch. Not the data ' + + 'plane\'s batch answer: here `succeeded` and `failed` are row lists, not counts. ' + + 'A value with neither member keeps the one-outcome report; a value with either member that does not ' + 'parse is reported as unreadable, never as full success; members beyond the two lists carry no meaning. Ids must be ' + 'dispatched `params._selectedIds`: an id outside the selection is dropped, a duplicate counts once, an id in both ' - + 'lists counts as failed, and a selected id in neither list is reported as not confirmed, never as succeeded.', + + 'lists counts as failed, an id in `failed` twice keeps its first message, and a selected id in neither list is ' + + 'reported as not confirmed, never as succeeded.', )); export type BulkActionResult = z.input; /** Post-parse shape of {@link BulkActionResult} — defaults applied, transforms run (ADR-0122). */ diff --git a/packages/spec/src/ui/view.zod.ts b/packages/spec/src/ui/view.zod.ts index f6d14e29cc4..60651f684ff 100644 --- a/packages/spec/src/ui/view.zod.ts +++ b/packages/spec/src/ui/view.zod.ts @@ -3660,9 +3660,10 @@ const ListViewShapeSchema = lazySchema(() => strictObject({ + "an `operation: 'custom'` + `execution: 'aggregate'` entry that dispatches the " + 'action it NAMES once for the whole selection — the renderer injects `params._selectedIds: ' + 'string[]` (read that on the server, not `recordId`) so a single call can produce one aggregate ' - + 'artifact (zip of QR codes, merged PDF, batch print). Aggregate results are all-or-nothing: a ' - + 'handler that cannot cover the whole selection must reject, and per-row retry is replaced by ' - + 're-running the action. `batchSize` does not apply (the call is never chunked); set `maxRecords` ' + + 'artifact (zip of QR codes, merged PDF, batch print). A rejection is one outcome for the whole ' + + 'selection; a run that moved some rows and refused others resolves with a `BulkActionResult` ' + + '(`{ succeeded, failed }`), a non-empty `failed` being a legal success answer. Per-row retry is ' + + 'replaced by re-running the action. `batchSize` does not apply (the call is never chunked); set `maxRecords` ' + "on defs whose server work is expensive. For the PER-RECORD dispatch use `bulkActions: ['']` " + 'instead — the bare-string form, promoted with the action\'s own label, params and `visible`; a ' + "'custom' def without `execution: 'aggregate'` has no dispatcher and is refused at parse time" diff --git a/ui/packages/i18n/src/__tests__/count-families-11445.test.ts b/ui/packages/i18n/src/__tests__/count-families-11445.test.ts index d6eeb2714d6..2d2e94d194d 100644 --- a/ui/packages/i18n/src/__tests__/count-families-11445.test.ts +++ b/ui/packages/i18n/src/__tests__/count-families-11445.test.ts @@ -118,6 +118,7 @@ const COUNT_NEUTRAL = { 'grid.bulk.processedFailed', 'grid.bulk.succeeded', 'grid.bulk.resultFailed', + 'grid.bulk.resultNotConfirmed', 'calendar.moreEvents', 'calendar.unscheduled', 'view.moreViews', diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index eb4d608d04f..e32275a1bd5 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -592,6 +592,9 @@ const ar = { resultFailed: " · فشل {{count}}", succeededRecords: "السجلات الناجحة", aggregateNotCompleted: "لم يكتمل الإجراء للسجلات المحددة. ربما تم تغيير بعض السجلات بالفعل. عند الإغلاق تعرض القائمة قيمها الحالية.", + resultNotConfirmed: " · غير مؤكد {{count}}", + notConfirmedRecords: "لم يُبلغ الإجراء عن نتيجة لهذه السجلات. تحقق من قيمها الحالية:", + aggregateUnreadable: "انتهى الإجراء، لكن تعذرت قراءة نتيجته، لذا لا يُعرف أي السجلات تم تغييرها. عند الإغلاق تعرض القائمة قيمها الحالية.", retry: "إعادة المحاولة", downloadErrorCsv: "تنزيل ملف CSV للأخطاء", cancel: "إلغاء", diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index 3b53507c061..06f90da1dd8 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -546,6 +546,9 @@ const de = { resultFailed: " · Fehlgeschlagen {{count}}", succeededRecords: "Erfolgreiche Datensätze", aggregateNotCompleted: "Die Aktion wurde für die ausgewählten Datensätze nicht abgeschlossen. Einige Datensätze wurden möglicherweise bereits geändert; nach dem Schließen zeigt die Liste ihre aktuellen Werte.", + resultNotConfirmed: " · Nicht bestätigt {{count}}", + notConfirmedRecords: "Die Aktion hat zu diesen Datensätzen nichts gemeldet. Prüfen Sie ihre aktuellen Werte:", + aggregateUnreadable: "Die Aktion wurde beendet, aber ihr Ergebnis konnte nicht gelesen werden, daher ist nicht bekannt, welche Datensätze geändert wurden. Nach dem Schließen zeigt die Liste ihre aktuellen Werte.", retry: "Erneut versuchen", downloadErrorCsv: "Fehler-CSV herunterladen", cancel: "Abbrechen", diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index d4601c37d4b..a6c1b468ada 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -1046,6 +1046,9 @@ const en = { resultFailed: ' \u00b7 Failed {{count}}', succeededRecords: 'Records that succeeded', aggregateNotCompleted: 'The action did not complete for the selected records. Some records may already have been changed; the list shows their current values when you close this.', + resultNotConfirmed: ' \u00b7 Not confirmed {{count}}', + notConfirmedRecords: 'The action did not report on these records. Check their current values:', + aggregateUnreadable: 'The action finished, but its result could not be read, so it is not known which records were changed. The list shows their current values when you close this.', retry: 'Retry', downloadErrorCsv: 'Download error CSV', cancel: 'Cancel', diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index 6c67e3d850a..4329b2efeb5 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -561,6 +561,9 @@ const es = { resultFailed: " · Fallidos {{count}}", succeededRecords: "Registros correctos", aggregateNotCompleted: "La acción no se completó para los registros seleccionados. Es posible que algunos registros ya se hayan modificado; al cerrar, la lista muestra sus valores actuales.", + resultNotConfirmed: " · Sin confirmar {{count}}", + notConfirmedRecords: "La acción no informó sobre estos registros. Compruebe sus valores actuales:", + aggregateUnreadable: "La acción terminó, pero no se pudo leer su resultado, así que no se sabe qué registros se modificaron. Al cerrar, la lista muestra sus valores actuales.", retry: "Reintentar", downloadErrorCsv: "Descargar CSV de errores", cancel: "Cancelar", diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index de61dcffc55..06dc2cd4b0e 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -556,6 +556,9 @@ const fr = { resultFailed: " · Échecs {{count}}", succeededRecords: "Enregistrements réussis", aggregateNotCompleted: "L’action ne s’est pas terminée pour les enregistrements sélectionnés. Certains enregistrements ont peut-être déjà été modifiés. À la fermeture, la liste affiche leurs valeurs actuelles.", + resultNotConfirmed: " · Non confirmés {{count}}", + notConfirmedRecords: "L’action n’a rien indiqué pour ces enregistrements. Vérifiez leurs valeurs actuelles :", + aggregateUnreadable: "L’action s’est terminée, mais son résultat n’a pas pu être lu : on ne sait pas quels enregistrements ont été modifiés. À la fermeture, la liste affiche leurs valeurs actuelles.", retry: "Réessayer", downloadErrorCsv: "Télécharger le CSV d'erreurs", cancel: "Annuler", diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index 017f254f737..88c83711f34 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -546,6 +546,9 @@ const ja = { resultFailed: " · 失敗 {{count}}", succeededRecords: "成功したレコード", aggregateNotCompleted: "選択したレコードに対する操作は完了しませんでした。一部のレコードはすでに変更されている可能性があります。閉じると、一覧に現在の値が表示されます。", + resultNotConfirmed: " · 未確認 {{count}}", + notConfirmedRecords: "これらのレコードについて操作からの報告がありません。現在の値を確認してください:", + aggregateUnreadable: "操作は終了しましたが、結果を読み取れなかったため、どのレコードが変更されたかは不明です。閉じると、一覧に現在の値が表示されます。", retry: "再試行", downloadErrorCsv: "エラー CSV をダウンロード", cancel: "キャンセル", diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index 6b7717f6379..c7e9cda5634 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -546,6 +546,9 @@ const ko = { resultFailed: " · 실패 {{count}}", succeededRecords: "성공한 레코드", aggregateNotCompleted: "선택한 레코드에 대한 작업이 완료되지 않았습니다. 일부 레코드는 이미 변경되었을 수 있습니다. 닫으면 목록에 현재 값이 표시됩니다.", + resultNotConfirmed: " · 미확인 {{count}}", + notConfirmedRecords: "작업이 이 레코드에 대해 결과를 보고하지 않았습니다. 현재 값을 확인하세요:", + aggregateUnreadable: "작업은 끝났지만 결과를 읽을 수 없어 어떤 레코드가 변경되었는지 알 수 없습니다. 닫으면 목록에 현재 값이 표시됩니다.", retry: "다시 시도", downloadErrorCsv: "오류 CSV 다운로드", cancel: "취소", diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index 15888c00576..f079b8daeba 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -556,6 +556,9 @@ const pt = { resultFailed: " · Falhas {{count}}", succeededRecords: "Registros concluídos", aggregateNotCompleted: "A ação não foi concluída para os registros selecionados. Alguns registros podem já ter sido alterados; ao fechar, a lista mostra os valores atuais.", + resultNotConfirmed: " · Não confirmados {{count}}", + notConfirmedRecords: "A ação não informou nada sobre estes registros. Verifique os valores atuais:", + aggregateUnreadable: "A ação terminou, mas o resultado não pôde ser lido, então não se sabe quais registros foram alterados. Ao fechar, a lista mostra os valores atuais.", retry: "Tentar novamente", downloadErrorCsv: "Baixar CSV de erros", cancel: "Cancelar", diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index 2726ff36cac..36c7e64cc65 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -569,6 +569,9 @@ const ru = { resultFailed: " · Ошибок {{count}}", succeededRecords: "Успешные записи", aggregateNotCompleted: "Действие не было выполнено для выбранных записей. Некоторые записи могли уже измениться; после закрытия список покажет их текущие значения.", + resultNotConfirmed: " · Не подтверждено {{count}}", + notConfirmedRecords: "Действие не сообщило о результате для этих записей. Проверьте их текущие значения:", + aggregateUnreadable: "Действие завершилось, но его результат не удалось прочитать, поэтому неизвестно, какие записи были изменены. После закрытия список покажет их текущие значения.", retry: "Повторить", downloadErrorCsv: "Скачать CSV с ошибками", cancel: "Отмена", diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index eb9f5ff7eca..80c52322b3a 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -789,6 +789,9 @@ const zh = { resultFailed: ' · 失败 {{count}}', succeededRecords: '成功的记录', aggregateNotCompleted: '操作未对所选记录全部完成。部分记录可能已被修改;关闭后列表会显示它们的当前值。', + resultNotConfirmed: ' · 未确认 {{count}}', + notConfirmedRecords: '操作未报告这些记录的结果,请检查它们的当前值:', + aggregateUnreadable: '操作已完成,但无法读取其结果,因此不知道哪些记录被修改了。关闭后列表会显示它们的当前值。', retry: '重试', downloadErrorCsv: '下载错误 CSV', cancel: '取消', diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index 51b43ba3913..52938754e0d 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -789,6 +789,9 @@ const zhHant = { resultFailed: ' · 失敗 {{count}}', succeededRecords: '成功的記錄', aggregateNotCompleted: '操作未對所選記錄全部完成。部分記錄可能已被修改;關閉後列表會顯示它們的當前值。', + resultNotConfirmed: ' · 未確認 {{count}}', + notConfirmedRecords: '操作未報告這些記錄的結果,請檢查它們的當前值:', + aggregateUnreadable: '操作已完成,但無法讀取其結果,因此不知道哪些記錄被修改了。關閉後列表會顯示它們的當前值。', retry: '重試', downloadErrorCsv: '下載錯誤 CSV', cancel: '取消', diff --git a/ui/packages/plugin-grid/src/ObjectGrid.tsx b/ui/packages/plugin-grid/src/ObjectGrid.tsx index 4ba6540cfe8..65a9d161079 100644 --- a/ui/packages/plugin-grid/src/ObjectGrid.tsx +++ b/ui/packages/plugin-grid/src/ObjectGrid.tsx @@ -57,7 +57,7 @@ import { toast, cn, } from '@object-ui/components'; -import { resolveConditionalFormatting, declaredNameField, buildExportFileName, resolveAffordance, type SchemaLike, isExpandableFieldType, isUnmaterializedFieldType, readObjectSortability, isPlatformSortableField, filterPlatformSortableSort, filterRefusalSubject, FilterOperatorError, resolveRecordSourceConfig, resolveRecordSourceObjectName, partitionRowsByPredicate, csvBlob } from '@object-ui/core'; +import { resolveConditionalFormatting, declaredNameField, buildExportFileName, resolveAffordance, 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, @@ -2232,9 +2232,9 @@ export const ObjectGrid: React.FC = ({ def: BulkActionDef, rows: Array>, params: Record, - ): Promise => { + ): Promise => { const source = def.actionDef as Record | undefined; - if (!source) return; + if (!source) return undefined; const rest = stripCollectedActionKeys(source); const ids = rows.map((r) => (r.id != null ? String(r.id) : '')).filter(Boolean); // Publish the EXPANDED, eligibility-filtered rows the run actually covers @@ -2256,6 +2256,10 @@ export const ObjectGrid: React.FC = ({ const error = new Error(res?.error || `Action ${def.name} failed`); throw res?.userMessage ? Object.assign(error, { userMessage: res.userMessage }) : error; } + // The handler's own return value, one level below the action envelope: + // the executor reads a `BulkActionResult` (`{ succeeded, failed }`) in it + // per row. + return readActionPayload(res.data); }; const handleBulkDialogClose = (result?: BulkResult | null) => { setActiveBulkDef(null); @@ -2269,11 +2273,11 @@ export const ObjectGrid: React.FC = ({ resetSelection(); // Trigger refresh via the same path used by single-record mutations. setRefreshKey(k => k + 1); - } else if (result?.aggregateRejection) { - // A rejected aggregate run (objectstack#34173) is ONE call that may have - // written some rows before it stopped, so the grid re-reads them by the - // same path. The selection stays: re-running the whole action is the - // retry, as for a total failure. + } else if (result?.aggregateRejection || result?.aggregateUnreadable || result?.aggregateUnconfirmed?.length) { + // A rejected or unreadable aggregate run is ONE call that may have + // written rows nobody counted, as may one that left rows unconfirmed, + // so the grid re-reads them by the same path. The selection stays: + // re-running the whole action is the retry, as for a total failure. setRefreshKey(k => k + 1); } }; diff --git a/ui/packages/plugin-grid/src/__tests__/objectBulkActionDispatch.test.tsx b/ui/packages/plugin-grid/src/__tests__/objectBulkActionDispatch.test.tsx index e8afc398fc8..08a4b0c14d1 100644 --- a/ui/packages/plugin-grid/src/__tests__/objectBulkActionDispatch.test.tsx +++ b/ui/packages/plugin-grid/src/__tests__/objectBulkActionDispatch.test.tsx @@ -674,3 +674,91 @@ describe('a per-record failed row shows the refusal\'s userMessage (objectstack# expect(screen.queryByText(USER_TEXT, { exact: false })).not.toBeInTheDocument(); }); }); + +/** + * An aggregate action that RESOLVES with a per-row answer: the handler's own + * return value, read as a `BulkActionResult` (`{ succeeded, failed }`, + * `@objectstack/spec/ui`) against the dispatched selection. Driven through + * the console's real `script` dispatch and the `/actions` door's success + * envelope, so the pins see the value the grid's dispatcher hands the + * executor, not a value injected below it. + */ +describe('an aggregate run reports its BulkActionResult per row', () => { + const MOVE = { name: 'mass_update_stage', label: 'Update Stage', type: 'script' }; + const AGGREGATE = { bulkActionDefs: [{ name: 'mass_update_stage', operation: 'custom', execution: 'aggregate' }] }; + const resolving = (data?: unknown) => vi.fn(async () => ({ + ok: true, + status: 200, + json: async () => (data === undefined ? { success: true } : { success: true, data }), + })); + + async function runAndClose(actionsFetch: ReturnType) { + const script = createServerActionHandler({ fetch: actionsFetch as any, baseUrl: '' }); + const ds = await renderAndSelectAll({ objectActions: [MOVE], schema: AGGREGATE, handlers: { script } }); + fireEvent.click(await screen.findByTestId('bulk-action-mass_update_stage')); + fireEvent.click(await screen.findByRole('button', { name: 'Run' })); + await screen.findByRole('button', { name: 'Done' }); + expect(actionsFetch).toHaveBeenCalledTimes(1); + return ds; + } + + async function refreshesOnClose(ds: any): Promise { + const before = ds.find.mock.calls.length; + fireEvent.click(screen.getByRole('button', { name: 'Done' })); + await waitFor(() => expect(ds.find.mock.calls.length).toBeGreaterThan(before)); + await new Promise(r => setTimeout(r, 50)); + return ds.find.mock.calls.length - before; + } + + it('lists the moved count and each failed row with the handler\'s message, with no Retry', async () => { + await runAndClose(resolving({ + succeeded: ['r1'], + failed: [{ id: 'r2', message: 'Plan B is Closed Won and was not moved.' }], + })); + + expect(screen.getByText(/Succeeded 1 \/ 2/)).toBeInTheDocument(); + expect(screen.getByText(/Failed 1/)).toBeInTheDocument(); + expect(screen.getByTestId('bulk-error-row-r2')).toHaveTextContent('Plan B is Closed Won and was not moved.'); + expect(screen.queryByTestId('bulk-error-row-r1')).not.toBeInTheDocument(); + expect(screen.queryByTestId('bulk-error-retry-r2')).not.toBeInTheDocument(); + expect(screen.queryByTestId('bulk-aggregate-rejection')).not.toBeInTheDocument(); + expect(screen.queryByTestId('bulk-unconfirmed-records')).not.toBeInTheDocument(); + }); + + it('reports a selected row the result names in neither list as not confirmed, never as succeeded', async () => { + await runAndClose(resolving({ succeeded: ['r1'], failed: [] })); + + expect(screen.getByText(/Succeeded 1 \/ 2/)).toBeInTheDocument(); + expect(screen.getByText(/Not confirmed 1/)).toBeInTheDocument(); + expect(screen.getByTestId('bulk-unconfirmed-records')).toHaveTextContent('Plan B'); + expect(screen.getByTestId('bulk-succeeded-records')).toHaveTextContent('Plan A'); + expect(screen.getByTestId('bulk-succeeded-records')).not.toHaveTextContent('Plan B'); + }); + + it('re-reads the grid once when the dialog closes after a run that left every row unconfirmed', async () => { + const ds = await runAndClose(resolving({ succeeded: [], failed: [] })); + expect(screen.getByText(/Succeeded 0 \/ 2/)).toBeInTheDocument(); + expect(screen.getByText(/Not confirmed 2/)).toBeInTheDocument(); + expect(await refreshesOnClose(ds)).toBe(1); + }); + + it('reports a succeeded/failed value that does not parse as unreadable, never as full success', async () => { + const ds = await runAndClose(resolving({ succeeded: 2, failed: 0 })); + + expect(screen.getByTestId('bulk-aggregate-unreadable')).toHaveTextContent( + 'The action finished, but its result could not be read', + ); + expect(screen.queryByText(/Succeeded/)).not.toBeInTheDocument(); + expect(document.querySelectorAll('[data-testid^="bulk-error-row-"]')).toHaveLength(0); + expect(await refreshesOnClose(ds)).toBe(1); + }); + + it('CONTROL: a handler that returns nothing keeps today\'s report', async () => { + await runAndClose(resolving()); + + expect(screen.getByText(/Succeeded 2 \/ 2/)).toBeInTheDocument(); + expect(screen.queryByText(/Failed/)).not.toBeInTheDocument(); + expect(screen.queryByTestId('bulk-unconfirmed-records')).not.toBeInTheDocument(); + expect(screen.queryByTestId('bulk-aggregate-unreadable')).not.toBeInTheDocument(); + }); +}); diff --git a/ui/packages/plugin-grid/src/__tests__/useBulkExecutor.test.ts b/ui/packages/plugin-grid/src/__tests__/useBulkExecutor.test.ts index 3603c941f40..defd4429642 100644 --- a/ui/packages/plugin-grid/src/__tests__/useBulkExecutor.test.ts +++ b/ui/packages/plugin-grid/src/__tests__/useBulkExecutor.test.ts @@ -658,3 +658,101 @@ describe('useBulkExecutor', () => { }); }); }); + +// An aggregate handler's resolve value is read per row against the ids the +// run dispatched (`readAggregateResult`, `BulkActionResultSchema` in +// `@objectstack/spec/ui`). A rejection stays the one-outcome report above. +describe('useBulkExecutor — an aggregate run reads its BulkActionResult per row', () => { + const agg = (): BulkActionDef => ({ + name: 'mass_update_stage', + operation: 'custom', + execution: 'aggregate', + actionDef: { name: 'mass_update_stage', type: 'script' }, + } as BulkActionDef); + const ds = () => ({ update: vi.fn(), delete: vi.fn() }); + const ROWS = [{ id: 'a' }, { id: 'b' }, { id: 'c' }]; + + async function runResolving(value: unknown) { + const runAggregate = vi.fn( + async ( + _def: BulkActionDef, + _rows: Array>, + _params: Record, + ): Promise => value, + ); + const { result } = renderHook(() => + useBulkExecutor({ resource: 'opportunity', dataSource: ds(), runAggregate })); + await act(async () => { + await result.current.run(agg(), ROWS, {}); + }); + expect(runAggregate).toHaveBeenCalledTimes(1); + return result.current.result!; + } + + it('reports the moved count and each failed row with its message', async () => { + const r = await runResolving({ succeeded: ['a', 'c'], failed: [{ id: 'b', message: 'B is Closed Won' }] }); + expect(r).toMatchObject({ total: 3, succeeded: 2, failed: 1 }); + expect(r.errors).toEqual([{ id: 'b', error: 'B is Closed Won' }]); + expect(r.aggregateUnconfirmed).toBeUndefined(); + expect(r.aggregateUnreadable).toBeUndefined(); + expect(r.aggregateRejection).toBeUndefined(); + }); + + it('drops an id outside the dispatched selection', async () => { + const r = await runResolving({ + succeeded: ['a', 'b', 'c', 'zz'], + failed: [{ id: 'yy', message: 'not selected' }], + }); + expect(r).toMatchObject({ succeeded: 3, failed: 0, errors: [] }); + }); + + it('counts a duplicate id once', async () => { + const r = await runResolving({ succeeded: ['a', 'a', 'b', 'c', 'c'], failed: [] }); + expect(r).toMatchObject({ total: 3, succeeded: 3, failed: 0 }); + }); + + it('counts an id listed in both lists as failed', async () => { + const r = await runResolving({ succeeded: ['a', 'b', 'c'], failed: [{ id: 'b', message: 'refused' }] }); + expect(r).toMatchObject({ succeeded: 2, failed: 1 }); + expect(r.errors).toEqual([{ id: 'b', error: 'refused' }]); + }); + + it('keeps the first entry when one id is in failed twice with different messages', async () => { + const r = await runResolving({ + succeeded: ['a', 'c'], + failed: [{ id: 'b', message: 'first reason' }, { id: 'b', message: 'second reason' }], + }); + expect(r.failed).toBe(1); + expect(r.errors).toEqual([{ id: 'b', error: 'first reason' }]); + }); + + it('reports a selected id in neither list as not confirmed, never as succeeded', async () => { + const r = await runResolving({ succeeded: ['a'], failed: [] }); + expect(r).toMatchObject({ total: 3, succeeded: 1, failed: 0, errors: [] }); + expect(r.aggregateUnconfirmed).toEqual(['b', 'c']); + }); + + it.each([ + ['counts in place of lists (the data plane batch shape)', { succeeded: 2, failed: 1 }], + ['a failed entry spelled with error instead of message', { succeeded: ['a'], failed: [{ id: 'b', error: 'x' }] }], + ['only one of the two members', { succeeded: ['a', 'b', 'c'] }], + ['a numeric id', { succeeded: [1, 2, 3], failed: [] }], + ])('reports a value carrying succeeded/failed that does not parse as unreadable, never as full success: %s', async (_label, value) => { + const r = await runResolving(value); + expect(r.aggregateUnreadable).toBe(true); + expect(r.succeeded).toBe(0); + expect(r.errors).toEqual([]); + expect(r.aggregateRejection).toBeUndefined(); + }); + + it.each([ + ['nothing', undefined], + ['null', null], + ['a summary', { moved: 3 }], + ['an artifact link', { url: 'https://example.test/qr.zip' }], + ['an array', ['a']], + ])('CONTROL: a value with neither member keeps today\'s report: %s', async (_label, value) => { + const r = await runResolving(value); + expect(r).toEqual({ total: 3, succeeded: 3, failed: 0, errors: [] }); + }); +}); diff --git a/ui/packages/plugin-grid/src/components/BulkActionDialog.tsx b/ui/packages/plugin-grid/src/components/BulkActionDialog.tsx index 485ca01f7f8..e426c7caae6 100644 --- a/ui/packages/plugin-grid/src/components/BulkActionDialog.tsx +++ b/ui/packages/plugin-grid/src/components/BulkActionDialog.tsx @@ -405,14 +405,20 @@ export const BulkActionDialog: React.FC = ({ // the rows left over are exactly the ones that succeeded. A failure the // server answered with a count only leaves the successes unknown, and the // result keeps to its count rather than name a record that may have failed. + // Rows an aggregate handler did not confirm are neither landed nor failed. + const unconfirmedIds = new Set(result?.aggregateUnconfirmed ?? []); const succeededRows = (() => { if (!result || result.succeeded === 0) return []; const failedIds = new Set(result.errors.map(e => e.id)); - const landed = rows.filter(r => r.id != null && !failedIds.has(String(r.id))); + const landed = rows.filter(r => r.id != null + && !failedIds.has(String(r.id)) && !unconfirmedIds.has(String(r.id))); return landed.length === result.succeeded ? landed : []; })(); const succeededPreview = succeededRows.slice(0, 5); const succeededRest = succeededRows.length - succeededPreview.length; + const unconfirmedCount = unconfirmedIds.size; + const unconfirmedPreview = [...unconfirmedIds].slice(0, 5); + const unconfirmedRest = unconfirmedCount - unconfirmedPreview.length; return ( { if (!o) onClose(result); }}> @@ -587,10 +593,28 @@ export const BulkActionDialog: React.FC = ({ )} - {step === 'result' && result && !result.aggregateRejection && ( + {step === 'result' && result?.aggregateUnreadable && ( + /* An aggregate run that resolved with a `succeeded` / `failed` member + that does not parse as a BulkActionResult is ONE outcome for the + selection, like a rejection: the answer cannot say which rows the + handler wrote, so the panel prints no per-row count and never + reports full success. */ +
+
+ + + {t('grid.bulk.aggregateUnreadable', { + defaultValue: 'The action finished, but its result could not be read, so it is not known which records were changed. The list shows their current values when you close this.', + })} + +
+
+ )} + + {step === 'result' && result && !result.aggregateRejection && !result.aggregateUnreadable && (
- {result.failed === 0 ? ( + {result.failed === 0 && unconfirmedCount === 0 ? ( ) : ( @@ -603,6 +627,7 @@ export const BulkActionDialog: React.FC = ({ defaultValue: `Succeeded ${result.succeeded} / ${result.total}`, })} {result.failed > 0 && t('grid.bulk.resultFailed', { count: result.failed, defaultValue: ` · Failed ${result.failed}` })} + {unconfirmedCount > 0 && t('grid.bulk.resultNotConfirmed', { count: unconfirmedCount, defaultValue: ` · Not confirmed ${unconfirmedCount}` })}
{succeededPreview.length > 0 && ( @@ -625,6 +650,32 @@ export const BulkActionDialog: React.FC = ({ )} + {unconfirmedCount > 0 && ( + /* Selected rows an aggregate handler's BulkActionResult named in + neither list: not counted as succeeded, because nothing said + they were written. */ +
+

+ {t('grid.bulk.notConfirmedRecords', { + defaultValue: 'The action did not report on these records. Check their current values:', + })} +

+ +
    + {unconfirmedPreview.map(id => ( +
  • + • {refusedRecordName(id)} +
  • + ))} + {unconfirmedRest > 0 && ( +
  • + {t('grid.bulk.andMore', { count: unconfirmedRest, defaultValue: `… and ${unconfirmedRest} more` })} +
  • + )} +
+
+
+ )} {result.errors.length > 0 && ( <> diff --git a/ui/packages/plugin-grid/src/hooks/useBulkExecutor.ts b/ui/packages/plugin-grid/src/hooks/useBulkExecutor.ts index 40bdd59b895..2e939662af9 100644 --- a/ui/packages/plugin-grid/src/hooks/useBulkExecutor.ts +++ b/ui/packages/plugin-grid/src/hooks/useBulkExecutor.ts @@ -11,6 +11,7 @@ import type { BulkActionDef, BulkWriteResult, DataSource } from '@object-ui/type import { RelatedCountStore } from '@object-ui/components'; import { executeBulkBatch } from '@object-ui/core'; import { declaredUserMessage } from '@object-ui/react'; +import { BulkActionResultSchema } from '@objectstack/spec/ui'; import { normalizeMultiValuePatch, type MultiValueFieldDef } from './multiValueFields'; export interface BulkRowError { @@ -51,6 +52,76 @@ export interface BulkResult { * and `succeeded` / `failed` are not a per-row count the dialog may print. */ aggregateRejection?: { message: string }; + /** + * Set only when an `execution: 'aggregate'` run RESOLVED with a value that + * carries a `succeeded` or `failed` member but does not parse as + * `BulkActionResultSchema` (`@objectstack/spec/ui`). The handler finished, + * but its answer cannot say which rows it wrote, so the run has ONE outcome + * for the selection, exactly like {@link BulkResult.aggregateRejection}: + * `errors` carries no per-row entry and `succeeded` / `failed` are not a + * per-row count the dialog may print. Never reported as full success. + */ + aggregateUnreadable?: true; + /** + * Set only when an `execution: 'aggregate'` run RESOLVED with a parsed + * `BulkActionResult` that named some selected ids in NEITHER list: those + * ids, in selection order. They are counted neither as succeeded nor as + * failed — the handler did not confirm them — so + * `succeeded + failed + aggregateUnconfirmed.length === total`. + */ + aggregateUnconfirmed?: string[]; +} + +/** + * How an `execution: 'aggregate'` dispatch's resolve value reads, against the + * ids the run dispatched (`params._selectedIds`). + * + * - `none`: the value has NEITHER a `succeeded` nor a `failed` own member + * (nothing, a summary, an artifact link) — the one call covered every id. + * - `unreadable`: it has one of them but does not parse as + * `BulkActionResultSchema`. + * - `rows`: it parsed. Ids outside the selection are dropped; a duplicate + * counts once; an id in both lists counts as failed; when one id is in + * `failed` twice, the first entry's message wins; a selected id in neither + * list is `unconfirmed`, never succeeded. + */ +export type AggregateResultReading = + | { kind: 'none' } + | { kind: 'unreadable' } + | { + kind: 'rows'; + succeeded: string[]; + failed: Array<{ id: string; message: string }>; + unconfirmed: string[]; + }; + +export function readAggregateResult(value: unknown, selectedIds: readonly string[]): AggregateResultReading { + const carriesMember = value !== null + && typeof value === 'object' + && !Array.isArray(value) + && (Object.prototype.hasOwnProperty.call(value, 'succeeded') + || Object.prototype.hasOwnProperty.call(value, 'failed')); + if (!carriesMember) return { kind: 'none' }; + + const parsed = BulkActionResultSchema.safeParse(value); + if (!parsed.success) return { kind: 'unreadable' }; + + const selected = new Set(selectedIds); + const failedById = new Map(); + for (const entry of parsed.data.failed) { + if (selected.has(entry.id) && !failedById.has(entry.id)) failedById.set(entry.id, entry.message); + } + const succeededIds = new Set(); + for (const id of parsed.data.succeeded) { + if (selected.has(id) && !failedById.has(id)) succeededIds.add(id); + } + const ordered = [...selected]; + return { + kind: 'rows', + succeeded: ordered.filter((id) => succeededIds.has(id)), + failed: [...failedById].map(([id, message]) => ({ id, message })), + unconfirmed: ordered.filter((id) => !succeededIds.has(id) && !failedById.has(id)), + }; } /** @@ -157,12 +228,16 @@ export interface BulkExecutorOptions { * server can produce one aggregate artifact (zip, merged PDF…) for the * whole selection. * - * MUST reject on failure, like `runAction`: resolving on a failed action - * would report the entire selection as succeeded. A rejection is ONE - * outcome for the whole selection (`BulkResult.aggregateRejection`), never - * N row failures: the call cannot say which rows it wrote before it - * stopped (objectstack#34173). Reject with an error that carries the - * producer's `userMessage` when the failure has one — the result shows it. + * MUST resolve with the handler's own return value: the executor reads it + * per row (`readAggregateResult`). A handler that moved some rows and + * refused others resolves with a `BulkActionResult` + * (`{ succeeded, failed }`, `@objectstack/spec/ui`); a value with neither + * member counts as covering the whole selection. MUST reject when the + * handler could not produce an outcome at all. A rejection is ONE outcome + * for the whole selection (`BulkResult.aggregateRejection`), never N row + * failures: the call cannot say which rows it wrote before it stopped. + * Reject with an error that carries the producer's `userMessage` when the + * failure has one — the result shows it. * * When absent, an `execution: 'aggregate'` def FAILS LOUDLY rather than * quietly degrading to per-record fan-out — N dispatches against an @@ -209,10 +284,13 @@ export interface BulkExecutorOptions { * A `custom` def with `execution: 'aggregate'` (objectui#3139) does not ride * the bulk-first decision tree: it is ONE `runAggregate` dispatch for the * entire selection (never chunked, never fanned out per record against a - * single-call endpoint). It settles as a whole — resolved, every row counts as - * covered; rejected, the result carries one `aggregateRejection` for the - * selection instead of the same error attributed to every row, because the - * call cannot say which rows it had already written (objectstack#34173). + * single-call endpoint). Rejected, the result carries one `aggregateRejection` + * for the selection instead of the same error attributed to every row, + * because the call cannot say which rows it had already written. Resolved, + * its value is read by `readAggregateResult`: a `BulkActionResult` reports + * per row (succeeded, failed with the handler's message, or not confirmed); + * a value that carries `succeeded` / `failed` but does not parse is one + * `aggregateUnreadable` outcome; any other value covers every row. */ export function useBulkExecutor({ resource, dataSource, objectFields, runAction, runAggregate }: BulkExecutorOptions) { const [progress, setProgress] = useState({ @@ -276,6 +354,8 @@ export function useBulkExecutor({ resource, dataSource, objectFields, runAction, let succeeded = 0; let failed = 0; let aggregateRejection: BulkResult['aggregateRejection']; + let aggregateUnreadable = false; + let aggregateUnconfirmed: string[] = []; setResult(null); setProgress({ total, done: 0, failed: 0, inFlight: true }); @@ -333,17 +413,28 @@ export function useBulkExecutor({ resource, dataSource, objectFields, runAction, // Aggregate mode: the ONE call for the whole selection — even a // single selected row goes through it, because the target endpoint // reads `_selectedIds`, which the per-record dispatch shape never - // carries. It settles as a whole (objectstack#34173): resolved, it - // covered every id; rejected, the run has one outcome for the - // selection, not the same error attributed to each row — the call - // cannot say which rows it had written before it stopped. + // carries. Rejected, the run has one outcome for the selection, not + // the same error attributed to each row — the call cannot say which + // rows it had written before it stopped. Resolved, its value is read + // per row against the ids it was dispatched with. if (isAggregate) { try { if (!runAggregate) { throw new Error(`Aggregate action ${def.name} has no dispatcher wired`); } - await runAggregate(def, validIds.map((id) => rowById.get(id) ?? { id }), { ...params }); - succeeded += validIds.length; + const resolved = await runAggregate(def, validIds.map((id) => rowById.get(id) ?? { id }), { ...params }); + const reading = readAggregateResult(resolved, validIds); + if (reading.kind === 'none') { + succeeded += validIds.length; + } else if (reading.kind === 'unreadable') { + failed += validIds.length; + aggregateUnreadable = true; + } else { + succeeded += reading.succeeded.length; + failed += reading.failed.length; + errors.push(...reading.failed.map(({ id, message }) => ({ id, error: message }))); + aggregateUnconfirmed = reading.unconfirmed; + } } catch (e) { failed += validIds.length; aggregateRejection = { @@ -415,6 +506,8 @@ export function useBulkExecutor({ resource, dataSource, objectFields, runAction, failed, errors, ...(aggregateRejection ? { aggregateRejection } : {}), + ...(aggregateUnreadable ? { aggregateUnreadable: true as const } : {}), + ...(aggregateUnconfirmed.length > 0 ? { aggregateUnconfirmed } : {}), }; // Only retain the snapshot for rows that actually succeeded — there's // no point trying to "undo" a row whose mutation never landed. @@ -426,9 +519,10 @@ export function useBulkExecutor({ resource, dataSource, objectFields, runAction, // Mutating any row in `resource` may have changed how many records // belong to a parent (e.g. deleting Contacts under an Account). Drop // every cached count for this resource so the next page render - // re-probes. Cheap — counts are 1-int values. A rejected aggregate run - // may have written rows before it stopped, so it invalidates too. - if (succeeded > 0 || aggregateRejection) { + // re-probes. Cheap — counts are 1-int values. A rejected or unreadable + // aggregate run, or one that left rows unconfirmed, may have written + // rows nobody counted, so it invalidates too. + if (succeeded > 0 || aggregateRejection || aggregateUnreadable || aggregateUnconfirmed.length > 0) { RelatedCountStore.invalidate(resource); } return finalResult; diff --git a/ui/packages/types/src/objectql.ts b/ui/packages/types/src/objectql.ts index d38f7b1a96a..1a9556acd99 100644 --- a/ui/packages/types/src/objectql.ts +++ b/ui/packages/types/src/objectql.ts @@ -748,9 +748,12 @@ export interface BulkActionDef { * injects `params._selectedIds: string[]` (every selected record id) and * publishes the full records as `context.selectedRecords`, so the server * can produce a single aggregate artifact (zip of QR codes, merged PDF, - * batch print job…). Result semantics are all-or-nothing: the one call - * covers the whole selection, so per-row retry is unavailable — a total - * failure keeps the selection for a whole-run re-run. + * batch print job…). A rejection is one outcome for the whole + * selection; a run that moved some rows and refused others resolves + * with a `BulkActionResult` (`{ succeeded, failed }`, + * `@objectstack/spec/ui`), a non-empty `failed` being a legal success + * answer. Per-row retry is unavailable — a total failure keeps the + * selection for a whole-run re-run. * * Ignored for `operation: 'update' | 'delete'` (their bulk fast-path already * aggregates per batch) and for a `custom` def without `actionDef` (nothing