From 2ccc480bc5a8af068658717ca7eb7de9ec6e610b Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 4 Nov 2026 17:08:19 +0000 Subject: [PATCH] fix(download): localized messages for incomplete file downloads and busy PDF rendering - validateFileResponse now throws a translatable error (ra.notification.file_download_incomplete) instead of raw English "content length mismatch" / "missing keys" text. These usually come from a network content filter blocking or truncating the download, and the message says so. Technical details go to console.error and error.details. - fetchJson maps known server error codes to translation keys; PDF_RENDER_BUSY becomes ra.notification.pdf_render_busy. - Hebrew and English texts for both keys (English extends ra-language-english). Fixes buzz-code/ops#46 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012GTics1vhDVoBFRPcg7nSn --- providers/__tests__/baseDataProvider.test.ts | 50 +++++++++++++++++++- providers/__tests__/i18nProvider.test.js | 10 ++++ providers/baseDataProvider.ts | 21 ++++++-- providers/i18nProvider.js | 14 +++++- utils/__tests__/httpUtil.test.js | 41 ++++++++++++++++ utils/httpUtil.js | 18 ++++++- 6 files changed, 147 insertions(+), 7 deletions(-) create mode 100644 utils/__tests__/httpUtil.test.js diff --git a/providers/__tests__/baseDataProvider.test.ts b/providers/__tests__/baseDataProvider.test.ts index cfd4b685..f889829c 100644 --- a/providers/__tests__/baseDataProvider.test.ts +++ b/providers/__tests__/baseDataProvider.test.ts @@ -1,4 +1,4 @@ -import baseDataProvider from '../baseDataProvider'; +import baseDataProvider, { FILE_DOWNLOAD_INCOMPLETE_KEY } from '../baseDataProvider'; import saveAs from 'file-saver'; import { GetListParams, SortPayload } from 'react-admin'; @@ -184,6 +184,54 @@ describe('baseDataProvider', () => { expect(mockSaveAs).toHaveBeenCalledWith(mockBlob, 'test.json'); }); + + describe('incomplete file responses', () => { + const params: GetListParams = { + pagination: { page: 1, perPage: 10 }, + sort: { field: 'id', order: 'ASC' } as SortPayload, + filter: {}, + }; + let consoleError: jest.SpyInstance; + + beforeEach(() => { + consoleError = jest.spyOn(console, 'error').mockImplementation(() => {}); + }); + + afterEach(() => { + consoleError.mockRestore(); + }); + + it('throws the translatable incomplete-download error on content length mismatch', async () => { + httpClient.mockResolvedValueOnce({ + json: { type: 'application/pdf', data: 'abc', disposition: '', contentLength: 10 }, + }); + + const error = await provider.export('posts', params, 'pdf', 'Posts').catch(e => e); + + expect(error.message).toBe(FILE_DOWNLOAD_INCOMPLETE_KEY); + expect(error.details).toBe('content length mismatch: expected 10, got 3'); + expect(consoleError).toHaveBeenCalled(); + expect(mockSaveAs).not.toHaveBeenCalled(); + }); + + it('throws the same error when response keys are missing', async () => { + httpClient.mockResolvedValueOnce({ json: { type: 'application/pdf' } }); + + const error = await provider.export('posts', params, 'pdf', 'Posts').catch(e => e); + + expect(error.message).toBe(FILE_DOWNLOAD_INCOMPLETE_KEY); + expect(error.details).toBe('missing keys: data, disposition, contentLength'); + }); + + it('throws the same error on an empty response', async () => { + httpClient.mockResolvedValueOnce({ json: null }); + + const error = await provider.export('posts', params, 'pdf', 'Posts').catch(e => e); + + expect(error.message).toBe(FILE_DOWNLOAD_INCOMPLETE_KEY); + expect(error.details).toBe('empty response'); + }); + }); }); describe('getCount', () => { diff --git a/providers/__tests__/i18nProvider.test.js b/providers/__tests__/i18nProvider.test.js index 00b2fc7e..eaca0e8a 100644 --- a/providers/__tests__/i18nProvider.test.js +++ b/providers/__tests__/i18nProvider.test.js @@ -122,6 +122,11 @@ describe('i18nProvider', () => { expect(i18nProvider.translate('ra.auth.organization_name')).toBe('שם המוסד'); }); + it('translates download and PDF busy errors in Hebrew', () => { + expect(i18nProvider.translate('ra.notification.file_download_incomplete')).toContain('סינון האינטרנט'); + expect(i18nProvider.translate('ra.notification.pdf_render_busy')).toBe('המערכת מפיקה כרגע דוחות אחרים. נא לנסות שוב בעוד מספר דקות.'); + }); + it('handles missing translations by returning the key', () => { expect(i18nProvider.translate('ra.action.nonexistent')).toBe('ra.action.nonexistent'); }); @@ -141,6 +146,11 @@ describe('i18nProvider', () => { expect(i18nProvider.translate('ra.action.save')).toBe('Save'); expect(i18nProvider.translate('ra.auth.organization_name')).toBe('Organization Name'); }); + + it('translates download and PDF busy errors in English', () => { + expect(i18nProvider.translate('ra.notification.file_download_incomplete')).toContain('content filter'); + expect(i18nProvider.translate('ra.notification.pdf_render_busy')).toBe('The system is currently generating other reports. Please try again in a few minutes.'); + }); }); }); diff --git a/providers/baseDataProvider.ts b/providers/baseDataProvider.ts index 57bbb684..8213071e 100644 --- a/providers/baseDataProvider.ts +++ b/providers/baseDataProvider.ts @@ -166,19 +166,32 @@ const saveResponseFile = async (res, filename) => { return saveAs(blob, calcFileName(res.json.disposition, filename)); } +// Translation key shown to the user when a file response arrives incomplete or +// malformed. The usual cause is a content filter on the user's network that +// blocks or truncates the download, so the message explains that instead of +// exposing the technical details. +export const FILE_DOWNLOAD_INCOMPLETE_KEY = 'ra.notification.file_download_incomplete'; + +const fileResponseError = (details: string) => { + console.error(`Invalid file response: ${details}`); + const error = new Error(FILE_DOWNLOAD_INCOMPLETE_KEY); + (error as any).details = details; + return error; +} + const validateFileResponse = (response: any) => { if (!response) { - throw new Error('Invalid file response'); + throw fileResponseError('empty response'); } const expectedKeys = ['data', 'type', 'disposition', 'contentLength']; const missingKeys = expectedKeys.filter(key => !(key in response)); if (missingKeys.length > 0) { - throw new Error(`Invalid file response, missing keys: ${missingKeys.join(', ')}`); + throw fileResponseError(`missing keys: ${missingKeys.join(', ')}`); } const { data, contentLength } = response; - const actualLength = data.length; + const actualLength = data?.length; if (actualLength !== contentLength) { - throw new Error(`Invalid file response, content length mismatch: expected ${contentLength}, got ${actualLength}`); + throw fileResponseError(`content length mismatch: expected ${contentLength}, got ${actualLength}`); } } diff --git a/providers/i18nProvider.js b/providers/i18nProvider.js index 738ce38e..fe403ac7 100644 --- a/providers/i18nProvider.js +++ b/providers/i18nProvider.js @@ -103,6 +103,8 @@ const extendedTranslation = { notification: { not_authorized: "אין לך הרשאה לצפות בנתונים אלו.", application_update_available: 'גרסה חדשה זמינה.', + file_download_incomplete: 'הקובץ לא התקבל במלואו. ככל הנראה סינון האינטרנט (למשל נטפרי) חסם או קטע את ההורדה. נא לפנות לספק הסינון ולבקש לאשר את האתר, או לנסות להוריד מרשת אחרת.', + pdf_render_busy: 'המערכת מפיקה כרגע דוחות אחרים. נא לנסות שוב בעוד מספר דקות.', }, validation: { valueConfirm: 'ערך לא תואם', @@ -165,6 +167,16 @@ const extendedTranslation = { } } +// English texts for keys this package adds on top of ra-language-english. +const extendedEnglishTranslation = { + ra: { + notification: { + file_download_incomplete: 'The file was not fully received. An internet content filter (such as NetFree) most likely blocked or cut off the download. Please ask your filter provider to approve this site, or try downloading from another network.', + pdf_render_busy: 'The system is currently generating other reports. Please try again in a few minutes.', + }, + }, +} + export const getI18nProvider = (domainTranslations, isDummy = false) => { if (isDummy) { return { @@ -174,7 +186,7 @@ export const getI18nProvider = (domainTranslations, isDummy = false) => { }; } - const translations = { en, he: deepMerge(he, deepMerge(extendedTranslation, domainTranslations)) }; + const translations = { en: deepMerge(en, extendedEnglishTranslation), he: deepMerge(he, deepMerge(extendedTranslation, domainTranslations)) }; const i18nProvider = polyglotI18nProvider( locale => translations[locale], diff --git a/utils/__tests__/httpUtil.test.js b/utils/__tests__/httpUtil.test.js new file mode 100644 index 00000000..46159dde --- /dev/null +++ b/utils/__tests__/httpUtil.test.js @@ -0,0 +1,41 @@ +import { fetchUtils } from 'react-admin'; +import { fetchJson, translateErrorCode } from '../httpUtil'; + +jest.mock('react-admin', () => ({ + fetchUtils: { fetchJson: jest.fn() }, +})); + +const buildHttpError = (body) => { + const error = new Error(body?.message ?? 'error'); + error.status = body?.statusCode; + error.body = body; + return error; +}; + +describe('translateErrorCode', () => { + it('replaces the message of a known error code with its translation key', () => { + const error = buildHttpError({ statusCode: 503, code: 'PDF_RENDER_BUSY', message: 'busy' }); + expect(translateErrorCode(error).message).toBe('ra.notification.pdf_render_busy'); + }); + + it('leaves errors without a known code untouched', () => { + const error = buildHttpError({ statusCode: 500, message: 'Internal server error' }); + expect(translateErrorCode(error).message).toBe('Internal server error'); + }); + + it('handles errors without a body', () => { + const error = new Error('Network error'); + expect(translateErrorCode(error).message).toBe('Network error'); + }); +}); + +describe('fetchJson', () => { + it('sends credentials and translates known error codes on failure', async () => { + const error = buildHttpError({ statusCode: 503, code: 'PDF_RENDER_BUSY', message: 'busy' }); + fetchUtils.fetchJson.mockRejectedValueOnce(error); + + await expect(fetchJson('/report', {})).rejects.toBe(error); + expect(error.message).toBe('ra.notification.pdf_render_busy'); + expect(fetchUtils.fetchJson).toHaveBeenCalledWith('/report', { credentials: 'include' }); + }); +}); diff --git a/utils/httpUtil.js b/utils/httpUtil.js index 9e9fba65..15e6a9fa 100644 --- a/utils/httpUtil.js +++ b/utils/httpUtil.js @@ -1,6 +1,22 @@ import { fetchUtils } from 'react-admin'; +// Server error codes that have a localized message. The server sends a stable +// `code` with an English fallback `message`; the message is replaced with a +// translation key, which react-admin's notify() translates to the user's locale. +export const ERROR_CODE_TRANSLATION_KEYS = { + PDF_RENDER_BUSY: 'ra.notification.pdf_render_busy', +}; + +export const translateErrorCode = (error) => { + const key = ERROR_CODE_TRANSLATION_KEYS[error?.body?.code]; + if (key) { + error.message = key; + } + return error; +}; + export const fetchJson = (url, options = {}) => { options.credentials = 'include'; - return fetchUtils.fetchJson(url, options); + return fetchUtils.fetchJson(url, options) + .catch((error) => { throw translateErrorCode(error); }); }