@asteby/metacore-runtime-react 49.12.0 → 49.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,11 @@
|
|
|
1
1
|
# @asteby/metacore-runtime-react
|
|
2
2
|
|
|
3
|
+
## 49.13.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 2982fea: DynamicTable: el borrado masivo ahora muestra el motivo de cada rechazo del servidor. El toast de error conserva el conteo y añade como `description` hasta 3 motivos distintos agrupados con su cuenta ("• motivo (×2)", truncados a 200 caracteres, más "y N más"), como string con saltos de línea entregado en `description`; cómo se muestran esos saltos depende del toast del host. Los mensajes técnicos genéricos de axios ("Request failed with status code 500", "Network Error", "timeout of Nms exceeded") no cuentan como motivo. Si no hay motivo, el toast queda igual que antes. Nueva prop opcional `onBulkDeleteResult({ succeeded, failed })` llamada una vez al terminar (si lanza, se registra con `console.error` y la tabla se refresca igual), con `message` y `status` por fila fallida. Clave i18n nueva `dynamic.bulk_delete_error_more`.
|
|
8
|
+
|
|
3
9
|
## 49.12.0
|
|
4
10
|
|
|
5
11
|
### Minor Changes
|
package/dist/dynamic-table.d.ts
CHANGED
|
@@ -127,6 +127,13 @@ export interface DynamicTableProps {
|
|
|
127
127
|
extraBulkActions?: ReactNode | ((ctx: DynamicTableBulkContext) => ReactNode);
|
|
128
128
|
/** Hide the built-in bulk "Eliminar" (e.g. a model whose rows must not be deleted in batch). */
|
|
129
129
|
hideBulkDelete?: boolean;
|
|
130
|
+
/**
|
|
131
|
+
* Called once when a built-in bulk delete finishes, with the ids that were
|
|
132
|
+
* deleted and the ones refused (`message` / `status` come from the server
|
|
133
|
+
* response when available; a cancelled reason prompt has no message). Lets a
|
|
134
|
+
* host persist or log the outcome. The table's own toasts are unaffected.
|
|
135
|
+
*/
|
|
136
|
+
onBulkDeleteResult?: (result: BulkDeleteResult) => void;
|
|
130
137
|
/**
|
|
131
138
|
* First-use content shown instead of "No se encontraron resultados" when the
|
|
132
139
|
* list loaded fine, is empty, and no search/filter is active. Never shown
|
|
@@ -145,5 +152,14 @@ export interface DynamicTableBulkContext {
|
|
|
145
152
|
/** `true` when the user may run `actionKey` on this model; always `true` without a PermissionsProvider. */
|
|
146
153
|
can: (actionKey: string) => boolean;
|
|
147
154
|
}
|
|
148
|
-
|
|
155
|
+
/** Outcome of a built-in bulk delete (see `onBulkDeleteResult`). */
|
|
156
|
+
export interface BulkDeleteResult {
|
|
157
|
+
succeeded: Array<string | number>;
|
|
158
|
+
failed: Array<{
|
|
159
|
+
id: string | number;
|
|
160
|
+
message?: string;
|
|
161
|
+
status?: number;
|
|
162
|
+
}>;
|
|
163
|
+
}
|
|
164
|
+
export declare function DynamicTable({ model, endpoint, mutationEndpoint, enableUrlSync, defaultSort, hideImport, hideExport, hiddenColumns, allowedActionKeys, onAction, onRowClick, isRowActionVisible: rowActionPredicate, refreshTrigger, defaultFilters, extraColumns, getDynamicColumns, timeZone: timeZoneProp, currency: currencyProp, pagination: paginationMode, infiniteScroll: infiniteScrollProp, virtualizeRows, extraBulkActions, hideBulkDelete, onBulkDeleteResult, emptyState, }: DynamicTableProps): import("react").JSX.Element;
|
|
149
165
|
//# sourceMappingURL=dynamic-table.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dynamic-table.d.ts","sourceRoot":"","sources":["../src/dynamic-table.tsx"],"names":[],"mappings":"AAYA,OAAO,EAAsE,KAAK,SAAS,EAAE,MAAM,OAAO,CAAA;AAM1G,OAAO,EAKH,KAAK,SAAS,EAajB,MAAM,uBAAuB,CAAA;AAmC9B,OAAO,KAAK,EAAsB,iBAAiB,EAAE,kBAAkB,EAAE,MAAM,wBAAwB,CAAA;AAavG,OAAO,KAAK,EAAgD,gBAAgB,EAAE,MAAM,SAAS,CAAA;AA6F7F,MAAM,WAAW,iBAAiB;IAC9B,KAAK,EAAE,MAAM,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,cAAc,EACd,YAAiB,EACjB,iBAA4C,EAC5C,QAAQ,EAAE,YAAY,EACtB,QAAQ,EAAE,YAAY,EACtB,UAAU,EAAE,cAAc,EAC1B,cAAc,EAAE,kBAA0B,EAC1C,cAAc,EACd,gBAAgB,EAChB,cAAc,EACd,kBAAkB,EAClB,UAAU,GACb,EAAE,iBAAiB,+BA+pDnB"}
|
package/dist/dynamic-table.js
CHANGED
|
@@ -119,7 +119,48 @@ function isForbiddenError(error) {
|
|
|
119
119
|
const e = error;
|
|
120
120
|
return e?.response?.status === 403 || e?.status === 403;
|
|
121
121
|
}
|
|
122
|
-
|
|
122
|
+
const BULK_REASON_MAX_LEN = 200;
|
|
123
|
+
const BULK_REASON_MAX_GROUPS = 3;
|
|
124
|
+
/** Server text -> trimmed plain string, or undefined when there is nothing usable. */
|
|
125
|
+
function cleanReason(v) {
|
|
126
|
+
if (typeof v !== 'string')
|
|
127
|
+
return undefined;
|
|
128
|
+
const m = v.trim();
|
|
129
|
+
return m ? m : undefined;
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* Axios' own technical messages ("Request failed with status code 500",
|
|
133
|
+
* "Network Error", "timeout of 5000ms exceeded") say nothing the user can act
|
|
134
|
+
* on, so they never count as a refusal reason. Real server text
|
|
135
|
+
* (`response.data.message`) is unaffected and always wins.
|
|
136
|
+
*/
|
|
137
|
+
const GENERIC_TRANSPORT_MESSAGE = /^(request failed with status code \d+|network error|timeout of \d+ms exceeded)$/i;
|
|
138
|
+
function cleanTransportMessage(v) {
|
|
139
|
+
const m = cleanReason(v);
|
|
140
|
+
return m && !GENERIC_TRANSPORT_MESSAGE.test(m) ? m : undefined;
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* Groups refusal reasons ("• reason (×N)", at most 3 distinct, each truncated)
|
|
144
|
+
* plus an "and N more" line, as a string with line breaks. It is delivered as
|
|
145
|
+
* the toast `description`; how line breaks are shown depends on the host's toast.
|
|
146
|
+
*/
|
|
147
|
+
function groupBulkReasons(failed, more) {
|
|
148
|
+
const counts = new Map();
|
|
149
|
+
for (const f of failed) {
|
|
150
|
+
if (!f.message)
|
|
151
|
+
continue;
|
|
152
|
+
const m = f.message.length > BULK_REASON_MAX_LEN ? `${f.message.slice(0, BULK_REASON_MAX_LEN - 1)}…` : f.message;
|
|
153
|
+
counts.set(m, (counts.get(m) ?? 0) + 1);
|
|
154
|
+
}
|
|
155
|
+
if (counts.size === 0)
|
|
156
|
+
return undefined;
|
|
157
|
+
const entries = Array.from(counts.entries());
|
|
158
|
+
const lines = entries.slice(0, BULK_REASON_MAX_GROUPS).map(([m, n]) => (n > 1 ? `• ${m} (×${n})` : `• ${m}`));
|
|
159
|
+
if (entries.length > BULK_REASON_MAX_GROUPS)
|
|
160
|
+
lines.push(more(entries.length - BULK_REASON_MAX_GROUPS));
|
|
161
|
+
return lines.join('\n');
|
|
162
|
+
}
|
|
163
|
+
export function DynamicTable({ model, endpoint, mutationEndpoint, enableUrlSync = true, defaultSort, hideImport, hideExport, hiddenColumns = [], allowedActionKeys, onAction, onRowClick, isRowActionVisible: rowActionPredicate, refreshTrigger, defaultFilters, extraColumns = [], getDynamicColumns = defaultGetDynamicColumns, timeZone: timeZoneProp, currency: currencyProp, pagination: paginationMode, infiniteScroll: infiniteScrollProp = false, virtualizeRows, extraBulkActions, hideBulkDelete, onBulkDeleteResult, emptyState, }) {
|
|
123
164
|
// The org's timezone/currency: an explicit prop wins, else the app-wide
|
|
124
165
|
// OrgRuntimeProvider (without it, money fell back to USD).
|
|
125
166
|
const orgTimeZone = useTimeZone();
|
|
@@ -994,7 +1035,8 @@ export function DynamicTable({ model, endpoint, mutationEndpoint, enableUrlSync
|
|
|
994
1035
|
setIsBulkDeleting(true);
|
|
995
1036
|
setBulkDeleteTotal(selectedRows.length);
|
|
996
1037
|
setBulkDeleteProgress(0);
|
|
997
|
-
|
|
1038
|
+
const succeeded = [];
|
|
1039
|
+
const failed = [];
|
|
998
1040
|
// One reason for the whole batch: asked the first time a row is refused
|
|
999
1041
|
// for lacking it (model declares reason_required.delete), reused after.
|
|
1000
1042
|
let bulkReason;
|
|
@@ -1002,7 +1044,7 @@ export function DynamicTable({ model, endpoint, mutationEndpoint, enableUrlSync
|
|
|
1002
1044
|
for (let i = 0; i < selectedRows.length; i++) {
|
|
1003
1045
|
const row = selectedRows[i];
|
|
1004
1046
|
if (bulkCancelled) {
|
|
1005
|
-
|
|
1047
|
+
failed.push({ id: row.original.id });
|
|
1006
1048
|
setBulkDeleteProgress(i + 1);
|
|
1007
1049
|
continue;
|
|
1008
1050
|
}
|
|
@@ -1022,16 +1064,21 @@ export function DynamicTable({ model, endpoint, mutationEndpoint, enableUrlSync
|
|
|
1022
1064
|
});
|
|
1023
1065
|
if (!res) {
|
|
1024
1066
|
bulkCancelled = true;
|
|
1025
|
-
|
|
1067
|
+
failed.push({ id: row.original.id });
|
|
1026
1068
|
}
|
|
1027
1069
|
else if (res.data.success)
|
|
1028
|
-
|
|
1070
|
+
succeeded.push(row.original.id);
|
|
1029
1071
|
else
|
|
1030
|
-
|
|
1072
|
+
failed.push({ id: row.original.id, message: cleanReason(res.data.message) });
|
|
1031
1073
|
}
|
|
1032
1074
|
catch (e) {
|
|
1033
1075
|
console.error('Error al eliminar', e);
|
|
1034
|
-
|
|
1076
|
+
const err = e;
|
|
1077
|
+
failed.push({
|
|
1078
|
+
id: row.original.id,
|
|
1079
|
+
message: cleanReason(err?.response?.data?.message) ?? cleanTransportMessage(err?.message),
|
|
1080
|
+
status: err?.response?.status,
|
|
1081
|
+
});
|
|
1035
1082
|
}
|
|
1036
1083
|
setBulkDeleteProgress(i + 1);
|
|
1037
1084
|
}
|
|
@@ -1041,10 +1088,20 @@ export function DynamicTable({ model, endpoint, mutationEndpoint, enableUrlSync
|
|
|
1041
1088
|
setBulkDeleteProgress(0);
|
|
1042
1089
|
setBulkDeleteTotal(0);
|
|
1043
1090
|
setRowSelection({});
|
|
1091
|
+
const successCount = succeeded.length, errorCount = failed.length;
|
|
1044
1092
|
if (successCount > 0)
|
|
1045
1093
|
toast.success(t('dynamic.bulk_delete_success', { count: successCount, defaultValue: '{{count}} registro(s) eliminado(s) correctamente' }));
|
|
1046
|
-
if (errorCount > 0)
|
|
1047
|
-
|
|
1094
|
+
if (errorCount > 0) {
|
|
1095
|
+
const reasons = groupBulkReasons(failed, (count) => t('dynamic.bulk_delete_error_more', { count, defaultValue: 'y {{count}} más' }));
|
|
1096
|
+
toast.error(t('dynamic.bulk_delete_error', { count: errorCount, defaultValue: '{{count}} registro(s) no pudieron ser eliminados' }), reasons ? { description: reasons, style: { whiteSpace: 'pre-line' } } : undefined);
|
|
1097
|
+
}
|
|
1098
|
+
// A throwing host callback must not skip the refresh nor leave a rejected promise.
|
|
1099
|
+
try {
|
|
1100
|
+
onBulkDeleteResult?.({ succeeded, failed });
|
|
1101
|
+
}
|
|
1102
|
+
catch (e) {
|
|
1103
|
+
console.error('onBulkDeleteResult lanzó un error', e);
|
|
1104
|
+
}
|
|
1048
1105
|
handleRefresh();
|
|
1049
1106
|
};
|
|
1050
1107
|
const handleDynamicFilterChange = useCallback((filterKey, values) => {
|
package/package.json
CHANGED
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
// @vitest-environment happy-dom
|
|
2
|
+
//
|
|
3
|
+
// DynamicTable bulk delete: the error toast keeps the count and adds the
|
|
4
|
+
// server's refusal reasons (grouped, truncated, as a string with line breaks) as `description`;
|
|
5
|
+
// `onBulkDeleteResult` reports the outcome per id.
|
|
6
|
+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
|
7
|
+
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
|
|
8
|
+
|
|
9
|
+
const toastMock = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn() }))
|
|
10
|
+
vi.mock('sonner', () => ({ toast: toastMock }))
|
|
11
|
+
vi.mock('@tanstack/react-router', () => ({ useNavigate: () => () => {} }))
|
|
12
|
+
const I18N = {
|
|
13
|
+
t: (_k: string, o?: { defaultValue?: string; count?: number }) => {
|
|
14
|
+
if (o?.defaultValue && o.count != null) return o.defaultValue.replace('{{count}}', String(o.count))
|
|
15
|
+
return o?.defaultValue ?? _k
|
|
16
|
+
},
|
|
17
|
+
i18n: { language: 'es' },
|
|
18
|
+
}
|
|
19
|
+
vi.mock('react-i18next', () => ({ useTranslation: () => I18N }))
|
|
20
|
+
|
|
21
|
+
import { DynamicTable } from '../dynamic-table'
|
|
22
|
+
import { makeDefaultGetDynamicColumns } from '../dynamic-columns'
|
|
23
|
+
import { ApiProvider, type ApiClient } from '../api-context'
|
|
24
|
+
import { useMetadataCache } from '../metadata-cache'
|
|
25
|
+
import type { TableMetadata } from '../types'
|
|
26
|
+
|
|
27
|
+
afterEach(cleanup)
|
|
28
|
+
const getDynamicColumns = makeDefaultGetDynamicColumns()
|
|
29
|
+
|
|
30
|
+
function meta(): TableMetadata {
|
|
31
|
+
return {
|
|
32
|
+
title: 'Patients',
|
|
33
|
+
endpoint: '/data/patient',
|
|
34
|
+
columns: [{ key: 'title', label: 'Title', type: 'text', sortable: true, filterable: false, searchable: true }],
|
|
35
|
+
actions: [],
|
|
36
|
+
perPageOptions: [10],
|
|
37
|
+
defaultPerPage: 10,
|
|
38
|
+
searchPlaceholder: 'Buscar...',
|
|
39
|
+
enableCRUDActions: false,
|
|
40
|
+
hasActions: false,
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
type Outcome = { ok: true } | { status: number; message?: string } | { softFail: string }
|
|
45
|
+
|
|
46
|
+
function fakeApi(outcomes: Record<number, Outcome>): ApiClient {
|
|
47
|
+
const ok = (data: unknown) => ({ data: { success: true, data, meta: { total: 5 } } })
|
|
48
|
+
return {
|
|
49
|
+
get: vi.fn(async (url: string) => {
|
|
50
|
+
if (url.startsWith('/metadata/table/')) return ok(meta())
|
|
51
|
+
if (url.endsWith('/facets')) return ok([])
|
|
52
|
+
return ok([1, 2, 3, 4, 5].map((id) => ({ id, title: `Row ${id}` })))
|
|
53
|
+
}),
|
|
54
|
+
post: vi.fn(async () => ok(null)),
|
|
55
|
+
put: vi.fn(async () => ok(null)),
|
|
56
|
+
delete: vi.fn(async (url: string) => {
|
|
57
|
+
const id = Number(url.split('/').pop())
|
|
58
|
+
const o = outcomes[id] ?? { ok: true }
|
|
59
|
+
if ('softFail' in o) return { data: { success: false, message: o.softFail } }
|
|
60
|
+
if ('status' in o) {
|
|
61
|
+
throw Object.assign(new Error('Request failed'), {
|
|
62
|
+
response: { status: o.status, data: o.message ? { message: o.message } : {} },
|
|
63
|
+
})
|
|
64
|
+
}
|
|
65
|
+
return { data: { success: true } }
|
|
66
|
+
}),
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
async function runBulkDelete(api: ApiClient, onResult?: (r: any) => void) {
|
|
71
|
+
render(
|
|
72
|
+
<ApiProvider client={api}>
|
|
73
|
+
<DynamicTable model="patient" enableUrlSync={false} getDynamicColumns={getDynamicColumns} onBulkDeleteResult={onResult} />
|
|
74
|
+
</ApiProvider>,
|
|
75
|
+
)
|
|
76
|
+
await screen.findAllByText('Row 1')
|
|
77
|
+
fireEvent.click(screen.getAllByRole('checkbox')[0]) // select all
|
|
78
|
+
fireEvent.click(await screen.findByText('Eliminar'))
|
|
79
|
+
fireEvent.click(await screen.findByText('Eliminar todos'))
|
|
80
|
+
await waitFor(() => expect(toastMock.error.mock.calls.length + toastMock.success.mock.calls.length).toBeGreaterThan(0), { timeout: 5000 })
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const MSG = 'El registro forma parte del expediente, que debe conservarse al menos 5 años'
|
|
84
|
+
|
|
85
|
+
describe('DynamicTable bulk delete reasons', () => {
|
|
86
|
+
beforeEach(() => {
|
|
87
|
+
localStorage.clear()
|
|
88
|
+
sessionStorage.clear()
|
|
89
|
+
toastMock.success.mockClear()
|
|
90
|
+
toastMock.error.mockClear()
|
|
91
|
+
useMetadataCache.getState().setMetadata('patient', meta())
|
|
92
|
+
})
|
|
93
|
+
|
|
94
|
+
it('groups the same reason with its count and keeps the success toast', async () => {
|
|
95
|
+
const onResult = vi.fn()
|
|
96
|
+
await runBulkDelete(fakeApi({ 2: { status: 409, message: MSG }, 4: { status: 409, message: MSG } }), onResult)
|
|
97
|
+
expect(toastMock.success).toHaveBeenCalledWith('3 registro(s) eliminado(s) correctamente')
|
|
98
|
+
expect(toastMock.error).toHaveBeenCalledTimes(1)
|
|
99
|
+
const [title, opts] = toastMock.error.mock.calls[0]
|
|
100
|
+
expect(title).toBe('2 registro(s) no pudieron ser eliminados')
|
|
101
|
+
expect(opts.description).toBe(`• ${MSG} (×2)`)
|
|
102
|
+
expect(onResult).toHaveBeenCalledTimes(1)
|
|
103
|
+
expect(onResult).toHaveBeenCalledWith({
|
|
104
|
+
succeeded: [1, 3, 5],
|
|
105
|
+
failed: [{ id: 2, message: MSG, status: 409 }, { id: 4, message: MSG, status: 409 }],
|
|
106
|
+
})
|
|
107
|
+
})
|
|
108
|
+
|
|
109
|
+
it('lists distinct reasons, including a soft failure message', async () => {
|
|
110
|
+
await runBulkDelete(fakeApi({ 1: { status: 409, message: 'Motivo A' }, 2: { softFail: 'Motivo B' } }))
|
|
111
|
+
expect(toastMock.error.mock.calls[0][1].description).toBe('• Motivo A\n• Motivo B')
|
|
112
|
+
})
|
|
113
|
+
|
|
114
|
+
it('shows "y N más" past three distinct reasons', async () => {
|
|
115
|
+
await runBulkDelete(fakeApi({
|
|
116
|
+
1: { status: 409, message: 'R1' }, 2: { status: 409, message: 'R2' },
|
|
117
|
+
3: { status: 409, message: 'R3' }, 4: { status: 409, message: 'R4' }, 5: { status: 409, message: 'R5' },
|
|
118
|
+
}))
|
|
119
|
+
expect(toastMock.error.mock.calls[0][1].description).toBe('• R1\n• R2\n• R3\ny 2 más')
|
|
120
|
+
})
|
|
121
|
+
|
|
122
|
+
it('truncates long reasons', async () => {
|
|
123
|
+
await runBulkDelete(fakeApi({ 1: { status: 409, message: 'x'.repeat(500) } }))
|
|
124
|
+
const d: string = toastMock.error.mock.calls[0][1].description
|
|
125
|
+
expect(d.length).toBeLessThanOrEqual(2 + 200)
|
|
126
|
+
expect(d.endsWith('…')).toBe(true)
|
|
127
|
+
})
|
|
128
|
+
|
|
129
|
+
it('leaves the toast exactly as before when the server gave no message', async () => {
|
|
130
|
+
const onResult = vi.fn()
|
|
131
|
+
const api = fakeApi({ 1: { status: 500 } })
|
|
132
|
+
;(api.delete as any).mockImplementationOnce(async () => { throw new Error('') })
|
|
133
|
+
await runBulkDelete(api, onResult)
|
|
134
|
+
expect(toastMock.error).toHaveBeenCalledTimes(1)
|
|
135
|
+
expect(toastMock.error.mock.calls[0].length).toBe(2)
|
|
136
|
+
expect(toastMock.error.mock.calls[0][1]).toBeUndefined()
|
|
137
|
+
expect(onResult.mock.calls[0][0].failed[0]).toMatchObject({ id: 1 })
|
|
138
|
+
expect(onResult.mock.calls[0][0].failed[0].message).toBeUndefined()
|
|
139
|
+
})
|
|
140
|
+
|
|
141
|
+
it('works without onBulkDeleteResult', async () => {
|
|
142
|
+
await runBulkDelete(fakeApi({ 2: { status: 409, message: MSG } }))
|
|
143
|
+
expect(toastMock.error).toHaveBeenCalledTimes(1)
|
|
144
|
+
})
|
|
145
|
+
|
|
146
|
+
it('passes server HTML through as plain text', async () => {
|
|
147
|
+
const evil = '<img src=x onerror=alert(1)>'
|
|
148
|
+
await runBulkDelete(fakeApi({ 1: { status: 409, message: evil } }))
|
|
149
|
+
const d = toastMock.error.mock.calls[0][1].description
|
|
150
|
+
expect(typeof d).toBe('string')
|
|
151
|
+
expect(d).toBe(`• ${evil}`)
|
|
152
|
+
})
|
|
153
|
+
|
|
154
|
+
it('ignores generic axios messages as a reason', async () => {
|
|
155
|
+
const onResult = vi.fn()
|
|
156
|
+
const api = fakeApi({})
|
|
157
|
+
;(api.delete as any).mockImplementationOnce(async () => { throw new Error('Request failed with status code 500') })
|
|
158
|
+
;(api.delete as any).mockImplementationOnce(async () => { throw new Error('Network Error') })
|
|
159
|
+
;(api.delete as any).mockImplementationOnce(async () => { throw new Error('timeout of 5000ms exceeded') })
|
|
160
|
+
await runBulkDelete(api, onResult)
|
|
161
|
+
expect(toastMock.error.mock.calls[0][1]).toBeUndefined()
|
|
162
|
+
for (const f of onResult.mock.calls[0][0].failed) expect(f.message).toBeUndefined()
|
|
163
|
+
})
|
|
164
|
+
|
|
165
|
+
it('prefers the server message over the generic axios one', async () => {
|
|
166
|
+
const api = fakeApi({})
|
|
167
|
+
;(api.delete as any).mockImplementationOnce(async () => {
|
|
168
|
+
throw Object.assign(new Error('Request failed with status code 409'), { response: { status: 409, data: { message: 'Motivo real' } } })
|
|
169
|
+
})
|
|
170
|
+
await runBulkDelete(api)
|
|
171
|
+
expect(toastMock.error.mock.calls[0][1].description).toBe('• Motivo real')
|
|
172
|
+
})
|
|
173
|
+
|
|
174
|
+
it('counts a cancelled reason prompt as a failure without message or description', async () => {
|
|
175
|
+
const onResult = vi.fn()
|
|
176
|
+
const api = fakeApi({})
|
|
177
|
+
;(api.delete as any).mockImplementationOnce(async () => {
|
|
178
|
+
throw Object.assign(new Error('x'), {
|
|
179
|
+
response: { status: 422, data: { errors: { reason: [{ code: 'required', params: { min: 3 } }] } } },
|
|
180
|
+
})
|
|
181
|
+
})
|
|
182
|
+
render(
|
|
183
|
+
<ApiProvider client={api}>
|
|
184
|
+
<DynamicTable model="patient" enableUrlSync={false} getDynamicColumns={getDynamicColumns} onBulkDeleteResult={onResult} />
|
|
185
|
+
</ApiProvider>,
|
|
186
|
+
)
|
|
187
|
+
await screen.findAllByText('Row 1')
|
|
188
|
+
fireEvent.click(screen.getAllByRole('checkbox')[0])
|
|
189
|
+
fireEvent.click(await screen.findByText('Eliminar'))
|
|
190
|
+
fireEvent.click(await screen.findByText('Eliminar todos'))
|
|
191
|
+
const cancel = await screen.findByPlaceholderText('Explica por qué. Queda en la bitácora.')
|
|
192
|
+
expect(cancel).toBeTruthy()
|
|
193
|
+
const dialog = cancel.closest('[role="dialog"]') as HTMLElement
|
|
194
|
+
fireEvent.click(Array.from(dialog.querySelectorAll('button')).find((b) => b.textContent === 'Cancelar')!)
|
|
195
|
+
await waitFor(() => expect(toastMock.error).toHaveBeenCalled(), { timeout: 5000 })
|
|
196
|
+
expect(toastMock.error.mock.calls[0][0]).toBe('5 registro(s) no pudieron ser eliminados')
|
|
197
|
+
expect(toastMock.error.mock.calls[0][1]).toBeUndefined()
|
|
198
|
+
const { succeeded, failed } = onResult.mock.calls[0][0]
|
|
199
|
+
expect(succeeded).toEqual([])
|
|
200
|
+
expect(failed.map((f: any) => f.id)).toEqual([1, 2, 3, 4, 5])
|
|
201
|
+
for (const f of failed) expect(f.message).toBeUndefined()
|
|
202
|
+
expect(api.delete).toHaveBeenCalledTimes(1)
|
|
203
|
+
})
|
|
204
|
+
|
|
205
|
+
it('still refreshes the table when onBulkDeleteResult throws, with no unhandled rejection', async () => {
|
|
206
|
+
const unhandled = vi.fn()
|
|
207
|
+
process.on('unhandledRejection', unhandled)
|
|
208
|
+
const api = fakeApi({ 2: { status: 409, message: MSG } })
|
|
209
|
+
const listCalls = () => (api.get as any).mock.calls.filter(([u]: [string]) => !u.startsWith('/metadata/') && !u.endsWith('/facets')).length
|
|
210
|
+
const err = vi.spyOn(console, 'error').mockImplementation(() => {})
|
|
211
|
+
try {
|
|
212
|
+
let before = -1
|
|
213
|
+
await runBulkDelete(api, () => { before = listCalls(); throw new Error('boom') })
|
|
214
|
+
expect(before).toBeGreaterThan(0)
|
|
215
|
+
await waitFor(() => expect(listCalls()).toBeGreaterThan(before), { timeout: 5000 })
|
|
216
|
+
await new Promise((r) => setTimeout(r, 50))
|
|
217
|
+
expect(unhandled).not.toHaveBeenCalled()
|
|
218
|
+
expect(err.mock.calls.some((c) => String(c[0]).includes('onBulkDeleteResult'))).toBe(true)
|
|
219
|
+
} finally {
|
|
220
|
+
process.off('unhandledRejection', unhandled)
|
|
221
|
+
err.mockRestore()
|
|
222
|
+
}
|
|
223
|
+
})
|
|
224
|
+
})
|
package/src/dynamic-table.tsx
CHANGED
|
@@ -297,6 +297,13 @@ export interface DynamicTableProps {
|
|
|
297
297
|
extraBulkActions?: ReactNode | ((ctx: DynamicTableBulkContext) => ReactNode)
|
|
298
298
|
/** Hide the built-in bulk "Eliminar" (e.g. a model whose rows must not be deleted in batch). */
|
|
299
299
|
hideBulkDelete?: boolean
|
|
300
|
+
/**
|
|
301
|
+
* Called once when a built-in bulk delete finishes, with the ids that were
|
|
302
|
+
* deleted and the ones refused (`message` / `status` come from the server
|
|
303
|
+
* response when available; a cancelled reason prompt has no message). Lets a
|
|
304
|
+
* host persist or log the outcome. The table's own toasts are unaffected.
|
|
305
|
+
*/
|
|
306
|
+
onBulkDeleteResult?: (result: BulkDeleteResult) => void
|
|
300
307
|
/**
|
|
301
308
|
* First-use content shown instead of "No se encontraron resultados" when the
|
|
302
309
|
* list loaded fine, is empty, and no search/filter is active. Never shown
|
|
@@ -323,6 +330,53 @@ function isForbiddenError(error: unknown): boolean {
|
|
|
323
330
|
return e?.response?.status === 403 || e?.status === 403
|
|
324
331
|
}
|
|
325
332
|
|
|
333
|
+
/** Outcome of a built-in bulk delete (see `onBulkDeleteResult`). */
|
|
334
|
+
export interface BulkDeleteResult {
|
|
335
|
+
succeeded: Array<string | number>
|
|
336
|
+
failed: Array<{ id: string | number; message?: string; status?: number }>
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
const BULK_REASON_MAX_LEN = 200
|
|
340
|
+
const BULK_REASON_MAX_GROUPS = 3
|
|
341
|
+
|
|
342
|
+
/** Server text -> trimmed plain string, or undefined when there is nothing usable. */
|
|
343
|
+
function cleanReason(v: unknown): string | undefined {
|
|
344
|
+
if (typeof v !== 'string') return undefined
|
|
345
|
+
const m = v.trim()
|
|
346
|
+
return m ? m : undefined
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
/**
|
|
350
|
+
* Axios' own technical messages ("Request failed with status code 500",
|
|
351
|
+
* "Network Error", "timeout of 5000ms exceeded") say nothing the user can act
|
|
352
|
+
* on, so they never count as a refusal reason. Real server text
|
|
353
|
+
* (`response.data.message`) is unaffected and always wins.
|
|
354
|
+
*/
|
|
355
|
+
const GENERIC_TRANSPORT_MESSAGE = /^(request failed with status code \d+|network error|timeout of \d+ms exceeded)$/i
|
|
356
|
+
function cleanTransportMessage(v: unknown): string | undefined {
|
|
357
|
+
const m = cleanReason(v)
|
|
358
|
+
return m && !GENERIC_TRANSPORT_MESSAGE.test(m) ? m : undefined
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
/**
|
|
362
|
+
* Groups refusal reasons ("• reason (×N)", at most 3 distinct, each truncated)
|
|
363
|
+
* plus an "and N more" line, as a string with line breaks. It is delivered as
|
|
364
|
+
* the toast `description`; how line breaks are shown depends on the host's toast.
|
|
365
|
+
*/
|
|
366
|
+
function groupBulkReasons(failed: BulkDeleteResult['failed'], more: (count: number) => string): string | undefined {
|
|
367
|
+
const counts = new Map<string, number>()
|
|
368
|
+
for (const f of failed) {
|
|
369
|
+
if (!f.message) continue
|
|
370
|
+
const m = f.message.length > BULK_REASON_MAX_LEN ? `${f.message.slice(0, BULK_REASON_MAX_LEN - 1)}…` : f.message
|
|
371
|
+
counts.set(m, (counts.get(m) ?? 0) + 1)
|
|
372
|
+
}
|
|
373
|
+
if (counts.size === 0) return undefined
|
|
374
|
+
const entries = Array.from(counts.entries())
|
|
375
|
+
const lines = entries.slice(0, BULK_REASON_MAX_GROUPS).map(([m, n]) => (n > 1 ? `• ${m} (×${n})` : `• ${m}`))
|
|
376
|
+
if (entries.length > BULK_REASON_MAX_GROUPS) lines.push(more(entries.length - BULK_REASON_MAX_GROUPS))
|
|
377
|
+
return lines.join('\n')
|
|
378
|
+
}
|
|
379
|
+
|
|
326
380
|
export function DynamicTable({
|
|
327
381
|
model,
|
|
328
382
|
endpoint,
|
|
@@ -347,6 +401,7 @@ export function DynamicTable({
|
|
|
347
401
|
virtualizeRows,
|
|
348
402
|
extraBulkActions,
|
|
349
403
|
hideBulkDelete,
|
|
404
|
+
onBulkDeleteResult,
|
|
350
405
|
emptyState,
|
|
351
406
|
}: DynamicTableProps) {
|
|
352
407
|
// The org's timezone/currency: an explicit prop wins, else the app-wide
|
|
@@ -1207,14 +1262,15 @@ export function DynamicTable({
|
|
|
1207
1262
|
setIsBulkDeleting(true)
|
|
1208
1263
|
setBulkDeleteTotal(selectedRows.length)
|
|
1209
1264
|
setBulkDeleteProgress(0)
|
|
1210
|
-
|
|
1265
|
+
const succeeded: BulkDeleteResult['succeeded'] = []
|
|
1266
|
+
const failed: BulkDeleteResult['failed'] = []
|
|
1211
1267
|
// One reason for the whole batch: asked the first time a row is refused
|
|
1212
1268
|
// for lacking it (model declares reason_required.delete), reused after.
|
|
1213
1269
|
let bulkReason: string | undefined
|
|
1214
1270
|
let bulkCancelled = false
|
|
1215
1271
|
for (let i = 0; i < selectedRows.length; i++) {
|
|
1216
1272
|
const row = selectedRows[i]
|
|
1217
|
-
if (bulkCancelled) {
|
|
1273
|
+
if (bulkCancelled) { failed.push({ id: row.original.id }); setBulkDeleteProgress(i + 1); continue }
|
|
1218
1274
|
try {
|
|
1219
1275
|
const writeBase = mutationEndpoint ?? endpoint
|
|
1220
1276
|
const deleteEndpoint = writeBase ? `${writeBase}/${row.original.id}` : `/data/${model}/${row.original.id}`
|
|
@@ -1228,10 +1284,18 @@ export function DynamicTable({
|
|
|
1228
1284
|
return api.delete(deleteEndpoint, reason ? { params: { reason } } : undefined)
|
|
1229
1285
|
},
|
|
1230
1286
|
})
|
|
1231
|
-
if (!res) { bulkCancelled = true;
|
|
1232
|
-
else if (res.data.success)
|
|
1233
|
-
else
|
|
1234
|
-
} catch (e) {
|
|
1287
|
+
if (!res) { bulkCancelled = true; failed.push({ id: row.original.id }) }
|
|
1288
|
+
else if (res.data.success) succeeded.push(row.original.id)
|
|
1289
|
+
else failed.push({ id: row.original.id, message: cleanReason(res.data.message) })
|
|
1290
|
+
} catch (e) {
|
|
1291
|
+
console.error('Error al eliminar', e)
|
|
1292
|
+
const err = e as { response?: { data?: { message?: unknown }; status?: number }; message?: unknown }
|
|
1293
|
+
failed.push({
|
|
1294
|
+
id: row.original.id,
|
|
1295
|
+
message: cleanReason(err?.response?.data?.message) ?? cleanTransportMessage(err?.message),
|
|
1296
|
+
status: err?.response?.status,
|
|
1297
|
+
})
|
|
1298
|
+
}
|
|
1235
1299
|
setBulkDeleteProgress(i + 1)
|
|
1236
1300
|
}
|
|
1237
1301
|
await new Promise(resolve => setTimeout(resolve, 500))
|
|
@@ -1240,8 +1304,21 @@ export function DynamicTable({
|
|
|
1240
1304
|
setBulkDeleteProgress(0)
|
|
1241
1305
|
setBulkDeleteTotal(0)
|
|
1242
1306
|
setRowSelection({})
|
|
1307
|
+
const successCount = succeeded.length, errorCount = failed.length
|
|
1243
1308
|
if (successCount > 0) toast.success(t('dynamic.bulk_delete_success', { count: successCount, defaultValue: '{{count}} registro(s) eliminado(s) correctamente' }))
|
|
1244
|
-
if (errorCount > 0)
|
|
1309
|
+
if (errorCount > 0) {
|
|
1310
|
+
const reasons = groupBulkReasons(failed, (count) => t('dynamic.bulk_delete_error_more', { count, defaultValue: 'y {{count}} más' }))
|
|
1311
|
+
toast.error(
|
|
1312
|
+
t('dynamic.bulk_delete_error', { count: errorCount, defaultValue: '{{count}} registro(s) no pudieron ser eliminados' }),
|
|
1313
|
+
reasons ? { description: reasons, style: { whiteSpace: 'pre-line' } } : undefined,
|
|
1314
|
+
)
|
|
1315
|
+
}
|
|
1316
|
+
// A throwing host callback must not skip the refresh nor leave a rejected promise.
|
|
1317
|
+
try {
|
|
1318
|
+
onBulkDeleteResult?.({ succeeded, failed })
|
|
1319
|
+
} catch (e) {
|
|
1320
|
+
console.error('onBulkDeleteResult lanzó un error', e)
|
|
1321
|
+
}
|
|
1245
1322
|
handleRefresh()
|
|
1246
1323
|
}
|
|
1247
1324
|
|