Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions .changeset/34173-aggregate-bulk-rejection-one-outcome.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
---
'@object-ui/plugin-grid': patch
'@object-ui/core': patch
'@object-ui/types': patch
'@object-ui/i18n': patch
---

fix(plugin-grid): a rejected aggregate bulk action reports one outcome for the selection and refreshes the list

Clause-②: yes (widening) — optional member userMessage on ActionResult (@object-ui/types) and ActionResponseOutcome (@object-ui/core); nothing removed or renamed
Metadata-protocol: none

An aggregate bulk action (`bulkActionDefs` entry with `execution: 'aggregate'`) is one call for the whole selection. When that call rejected, the result dialog printed the rejection's platform `message` against every selected record, read "Succeeded 0 / N" even when the handler had already changed some of them, and the list kept showing the old values until a manual reload.

A rejected aggregate run is now one outcome for the selection. The dialog says the action did not complete for the selected records and shows the rejection's message once: its `userMessage` when the handler threw one (the text it wrote for the user, already in the request's locale), else its `message`. It shows no per-record count and no per-record failure list, because one call cannot say which records it changed before it stopped, nor whether it kept those changes; it says only that some records may already have been changed. When the dialog is closed at the result step, the list re-reads its rows, whether the action resolved or rejected, and the selection stays after a rejection for a re-run. The per-record dispatch (`bulkActions: ['NAME']`) reports exactly as before.

To carry the text, a failed script/server action dispatch now relays the refusal's `error.userMessage` on `ActionResult.userMessage` (`@object-ui/types`), read by `createServerActionHandler` (`@object-ui/core`); `error` stays the whole text. The new dialog sentence is translated in every locale pack.
12 changes: 12 additions & 0 deletions content/docs/ui/views.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,18 @@ 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.

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
rejection's message once — its `userMessage` when the handler threw one (the
text the handler wrote for the user, in the request's locale), else its
`message`. It shows no per-row count and no per-row failure list, because one
call cannot say which records it had changed before it stopped, nor whether
it kept any of those changes. So the dialog says only that some records may
already have been changed. When you close the dialog at the result step, the
list re-reads its rows, whether the action resolved or rejected, so a record
the handler changed shows its current value; the selection stays after a
rejection, ready for a re-run.

**Pick the right key for the dispatch you mean.** Per-record is
`bulkActions: ['<name>']` — the bare-string form, which has nowhere to carry a
flag and is promoted with the action's own label, params and `visible`.
Expand Down
41 changes: 41 additions & 0 deletions ui/packages/core/src/actions/__tests__/serverActionHandler.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -423,3 +423,44 @@ describe('createServerActionHandler — transport failure', () => {
expect(fetch).toHaveBeenCalledTimes(2);
});
});

/**
* The refusal's producer-marked `userMessage` (objectstack#34173). The
* `/actions` door answers a thrown `userMessage` beside `message` on the
* ADR-0112 `error` object — from a script body and from a server action's
* handler alike. The handler relays it on `ActionResult.userMessage`, so a
* host that reports the failure to the end user (the grid's aggregate bulk
* result) can show it; `error` stays the whole text.
*/
describe('createServerActionHandler — userMessage relay (objectstack#34173)', () => {
const refusing = (error: Record<string, unknown>) => vi.fn(async () => ({
ok: false,
status: 400,
json: async () => ({ success: false, error: { code: 'HOOK_ABORTED', httpStatus: 400, message: 'plan_b is closed_won', ...error } }),
})) as unknown as ServerActionFetch;

it('relays error.userMessage verbatim beside error, which stays the message', async () => {
const handler = createServerActionHandler({ fetch: refusing({ userMessage: ' Plan B is Closed Won.' }) });

const res = await handler({ type: 'script', name: 'mass_update_stage' } as ActionDef);

expect(res).toEqual({ success: false, error: 'plan_b is closed_won', userMessage: ' Plan B is Closed Won.' });
});

it('an unmarked refusal carries no userMessage', async () => {
const handler = createServerActionHandler({ fetch: refusing({}) });

const res = await handler({ type: 'script', name: 'mass_update_stage' } as ActionDef);

expect(res).toEqual({ success: false, error: 'plan_b is closed_won' });
expect('userMessage' in res).toBe(false);
});

it('a blank or non-string userMessage is no marking', async () => {
for (const userMessage of [' ', 42, { text: 'x' }]) {
const handler = createServerActionHandler({ fetch: refusing({ userMessage }) });
const res = await handler({ type: 'script', name: 'mass_update_stage' } as ActionDef);
expect('userMessage' in res).toBe(false);
}
});
});
23 changes: 23 additions & 0 deletions ui/packages/core/src/actions/actionResponse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,11 @@ export interface ActionResponseOutcome {
* any with a usable `field`. Only on a failure.
*/
fieldErrors?: ActionFieldError[];
/**
* The refusal's producer-marked user-facing text (`error.userMessage`),
* when it carried one. Only on a failure; `error` stays the whole text.
*/
userMessage?: string;
/**
* The ACTION ENVELOPE (`body.data`) — `{ success, data }`. Kept as-is
* because `ActionResult.data` has always carried this level and
Expand Down Expand Up @@ -126,18 +131,36 @@ export function interpretActionResponse(
// string — handing that object to `toast.error()` as a React child
// crashes the page, React #31).
const fieldErrors = refusalFieldErrors(innerFailed ? envelope : json);
const userMessage = refusalUserMessage(innerFailed ? envelope : json);
return {
ok: false,
error: innerFailed
? actionErrorDetail(envelope, `${label} failed`)
: actionErrorDetail(json, `${label} failed (HTTP ${res.status})`),
...(fieldErrors ? { fieldErrors } : {}),
...(userMessage !== undefined ? { userMessage } : {}),
};
}

return { ok: true, envelope, payload: readActionPayload(envelope) };
}

/**
* The producer-marked user-facing text of a refusal body
* (`ApiErrorSchema.userMessage`), as `ActionResult.userMessage` carries it.
* The ADR-0112 envelope carries it beside `message` on the `error` object —
* the `/actions` door answers a thrown `userMessage`, from a script body or a
* server action's handler alike, there. Presence is the marking: a blank or
* non-string value is no marking, and nothing else is promoted into it (the
* same predicate `@objectstack/client` applies when it lifts the field).
* Returned verbatim, untrimmed.
*/
export function refusalUserMessage(body: unknown): string | undefined {
const b = body as { error?: { userMessage?: unknown } } | null | undefined;
const raw = b?.error && typeof b.error === 'object' ? b.error.userMessage : undefined;
return typeof raw === 'string' && raw.trim() ? raw : undefined;
}

/**
* The `fields` list of a refusal body, as `ActionResult.fieldErrors` carries
* it. The ADR-0112 envelope carries the list in one of two members, both on
Expand Down
1 change: 1 addition & 0 deletions ui/packages/core/src/actions/serverActionHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -305,6 +305,7 @@ export function createServerActionHandler(config: ServerActionHandlerConfig): Se
success: false,
error: outcome.error,
...(outcome.fieldErrors ? { fieldErrors: outcome.fieldErrors } : {}),
...(outcome.userMessage !== undefined ? { userMessage: outcome.userMessage } : {}),
};
}
// A declared `operation: 'update'` wrote the record it addresses — that
Expand Down
1 change: 1 addition & 0 deletions ui/packages/i18n/src/locales/ar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -589,6 +589,7 @@ const ar = {
succeeded: "نجح {{count}} / {{total}}",
resultFailed: " · فشل {{count}}",
succeededRecords: "السجلات الناجحة",
aggregateNotCompleted: "لم يكتمل الإجراء للسجلات المحددة. ربما تم تغيير بعض السجلات بالفعل. عند الإغلاق تعرض القائمة قيمها الحالية.",
retry: "إعادة المحاولة",
downloadErrorCsv: "تنزيل ملف CSV للأخطاء",
cancel: "إلغاء",
Expand Down
1 change: 1 addition & 0 deletions ui/packages/i18n/src/locales/de.ts
Original file line number Diff line number Diff line change
Expand Up @@ -543,6 +543,7 @@ const de = {
succeeded: "Erfolgreich {{count}} / {{total}}",
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.",
retry: "Erneut versuchen",
downloadErrorCsv: "Fehler-CSV herunterladen",
cancel: "Abbrechen",
Expand Down
1 change: 1 addition & 0 deletions ui/packages/i18n/src/locales/en.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1039,6 +1039,7 @@ const en = {
succeeded: 'Succeeded {{count}} / {{total}}',
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.',
retry: 'Retry',
downloadErrorCsv: 'Download error CSV',
cancel: 'Cancel',
Expand Down
1 change: 1 addition & 0 deletions ui/packages/i18n/src/locales/es.ts
Original file line number Diff line number Diff line change
Expand Up @@ -558,6 +558,7 @@ const es = {
succeeded: "Correctos {{count}} / {{total}}",
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.",
retry: "Reintentar",
downloadErrorCsv: "Descargar CSV de errores",
cancel: "Cancelar",
Expand Down
1 change: 1 addition & 0 deletions ui/packages/i18n/src/locales/fr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -553,6 +553,7 @@ const fr = {
succeeded: "Réussis {{count}} / {{total}}",
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.",
retry: "Réessayer",
downloadErrorCsv: "Télécharger le CSV d'erreurs",
cancel: "Annuler",
Expand Down
1 change: 1 addition & 0 deletions ui/packages/i18n/src/locales/ja.ts
Original file line number Diff line number Diff line change
Expand Up @@ -543,6 +543,7 @@ const ja = {
succeeded: "成功 {{count}} / {{total}}",
resultFailed: " · 失敗 {{count}}",
succeededRecords: "成功したレコード",
aggregateNotCompleted: "選択したレコードに対する操作は完了しませんでした。一部のレコードはすでに変更されている可能性があります。閉じると、一覧に現在の値が表示されます。",
retry: "再試行",
downloadErrorCsv: "エラー CSV をダウンロード",
cancel: "キャンセル",
Expand Down
1 change: 1 addition & 0 deletions ui/packages/i18n/src/locales/ko.ts
Original file line number Diff line number Diff line change
Expand Up @@ -543,6 +543,7 @@ const ko = {
succeeded: "성공 {{count}} / {{total}}",
resultFailed: " · 실패 {{count}}",
succeededRecords: "성공한 레코드",
aggregateNotCompleted: "선택한 레코드에 대한 작업이 완료되지 않았습니다. 일부 레코드는 이미 변경되었을 수 있습니다. 닫으면 목록에 현재 값이 표시됩니다.",
retry: "다시 시도",
downloadErrorCsv: "오류 CSV 다운로드",
cancel: "취소",
Expand Down
1 change: 1 addition & 0 deletions ui/packages/i18n/src/locales/pt-BR.ts
Original file line number Diff line number Diff line change
Expand Up @@ -553,6 +553,7 @@ const pt = {
succeeded: "Concluídos {{count}} / {{total}}",
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.",
retry: "Tentar novamente",
downloadErrorCsv: "Baixar CSV de erros",
cancel: "Cancelar",
Expand Down
1 change: 1 addition & 0 deletions ui/packages/i18n/src/locales/ru.ts
Original file line number Diff line number Diff line change
Expand Up @@ -566,6 +566,7 @@ const ru = {
succeeded: "Успешно {{count}} / {{total}}",
resultFailed: " · Ошибок {{count}}",
succeededRecords: "Успешные записи",
aggregateNotCompleted: "Действие не было выполнено для выбранных записей. Некоторые записи могли уже измениться; после закрытия список покажет их текущие значения.",
retry: "Повторить",
downloadErrorCsv: "Скачать CSV с ошибками",
cancel: "Отмена",
Expand Down
1 change: 1 addition & 0 deletions ui/packages/i18n/src/locales/zh-Hans.ts
Original file line number Diff line number Diff line change
Expand Up @@ -785,6 +785,7 @@ const zh = {
succeeded: '成功 {{count}} / {{total}}',
resultFailed: ' · 失败 {{count}}',
succeededRecords: '成功的记录',
aggregateNotCompleted: '操作未对所选记录全部完成。部分记录可能已被修改;关闭后列表会显示它们的当前值。',
retry: '重试',
downloadErrorCsv: '下载错误 CSV',
cancel: '取消',
Expand Down
1 change: 1 addition & 0 deletions ui/packages/i18n/src/locales/zh-Hant.ts
Original file line number Diff line number Diff line change
Expand Up @@ -785,6 +785,7 @@ const zhHant = {
succeeded: '成功 {{count}} / {{total}}',
resultFailed: ' · 失敗 {{count}}',
succeededRecords: '成功的記錄',
aggregateNotCompleted: '操作未對所選記錄全部完成。部分記錄可能已被修改;關閉後列表會顯示它們的當前值。',
retry: '重試',
downloadErrorCsv: '下載錯誤 CSV',
cancel: '取消',
Expand Down
13 changes: 12 additions & 1 deletion ui/packages/plugin-grid/src/ObjectGrid.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2217,7 +2217,12 @@ export const ObjectGrid: React.FC<ObjectGridComponentProps> = ({
toast: { showOnSuccess: false, showOnError: false },
} as any);
if (!res?.success) {
throw new Error(res?.error || `Action ${def.name} failed`);
// The refusal's producer-marked `userMessage` rides on the rejection,
// so the result reports the ONE outcome for the selection in the words
// the handler wrote for the user (objectstack#34173). `message` stays
// the whole text.
const error = new Error(res?.error || `Action ${def.name} failed`);
throw res?.userMessage ? Object.assign(error, { userMessage: res.userMessage }) : error;
}
};
const handleBulkDialogClose = (result?: BulkResult | null) => {
Expand All @@ -2232,6 +2237,12 @@ export const ObjectGrid: React.FC<ObjectGridComponentProps> = ({
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.
setRefreshKey(k => k + 1);
}
};

Expand Down
Loading
Loading