diff --git a/.changeset/31494-calendar-reschedule-not-found.md b/.changeset/31494-calendar-reschedule-not-found.md new file mode 100644 index 00000000000..2aea65e7f11 --- /dev/null +++ b/.changeset/31494-calendar-reschedule-not-found.md @@ -0,0 +1,12 @@ +--- +'@object-ui/plugin-calendar': patch +'@object-ui/i18n': patch +--- + +fix(plugin-calendar): a reschedule of a record that is gone for this session toasts a translated sentence naming the object by its label + +Clause-②: yes (widening) +Metadata-protocol: none + +- **`@object-ui/plugin-calendar`:** when a drag-to-reschedule is refused with `404 RECORD_NOT_FOUND` (the record was deleted, or row-level security no longer shows it to this user), the toast used to show the server's own sentence, "Record ID not found in OBJECT_NAME": English in every session, with the record id and the object's machine name. It now says, in the session language, that this record of the object (named by its label) no longer exists or is no longer accessible. The label is the one the object schema serves, else the app's translation of it; with neither, the toast says the existing generic "This record doesn't exist, or you don't have access to it." and never the machine name. The event still snaps back to its day. A refusal the producer marked for the user, an external-source refusal and a permission refusal keep their own messages, ahead of this one. +- **`@object-ui/i18n`:** `calendar.rescheduleNotFound` in all eleven locale packs (zh-Hant generated from zh-Hans). diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index 2a5e1e40915..d5676c076a9 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -864,6 +864,7 @@ const ar = { eventTitlePlaceholder: "ما موضوع هذا الحدث؟", creating: "جارٍ الإنشاء…", titleRequired: "العنوان مطلوب", + rescheduleNotFound: "سجل {{object}} هذا لم يعد موجودًا، أو لم يعد لديك إذن للوصول إليه.", a11y: { region: "التقويم", grid: "شبكة التقويم", diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index 7fa3adc44d5..934cd0578d2 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -778,6 +778,7 @@ const de = { eventTitlePlaceholder: "Worum geht es bei diesem Termin?", creating: "Wird erstellt…", titleRequired: "Titel ist erforderlich", + rescheduleNotFound: "Dieser Datensatz ({{object}}) existiert nicht mehr, oder Sie haben keinen Zugriff mehr darauf.", a11y: { region: "Kalender", grid: "Kalenderraster", diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index 1a6b26ee5f4..e1fc4d65c14 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -1046,6 +1046,10 @@ const en = { eventTitlePlaceholder: 'What\'s this event about?', creating: 'Creating…', titleRequired: 'Title is required', + // A drag-to-reschedule the server refused because the record is gone for + // this session: deleted, or no longer visible to it. `{{object}}` is the + // object's label; with none to show, `form.recordNotFoundOrHidden` is used. + rescheduleNotFound: 'This {{object}} record no longer exists, or you no longer have access to it.', a11y: { region: 'Calendar', grid: 'Calendar grid', diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index 0ad5c204c8d..30e8608b56a 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -803,6 +803,7 @@ const es = { eventTitlePlaceholder: "¿De qué trata este evento?", creating: "Creando…", titleRequired: "El título es obligatorio", + rescheduleNotFound: "Este registro de {{object}} ya no existe o ya no tienes acceso a él.", a11y: { region: "Calendario", grid: "Cuadrícula del calendario", diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index ec485ce478c..5ad365a1520 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -798,6 +798,7 @@ const fr = { eventTitlePlaceholder: "De quoi s'agit-il ?", creating: "Création…", titleRequired: "Le titre est obligatoire", + rescheduleNotFound: "Cet enregistrement ({{object}}) n'existe plus, ou vous n'y avez plus accès.", a11y: { region: "Calendrier", grid: "Grille du calendrier", diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index 88deba5f844..0c8a1888cce 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -778,6 +778,7 @@ const ja = { eventTitlePlaceholder: "この予定の内容は?", creating: "作成中…", titleRequired: "タイトルは必須です", + rescheduleNotFound: "この{{object}}レコードは存在しないか、アクセス権がなくなりました。", a11y: { region: "カレンダー", grid: "カレンダーグリッド", diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index 651ab51f6f6..6008436b3b0 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -778,6 +778,7 @@ const ko = { eventTitlePlaceholder: "이 일정은 어떤 내용인가요?", creating: "생성 중…", titleRequired: "제목을 입력하세요", + rescheduleNotFound: "이 {{object}} 레코드가 더 이상 존재하지 않거나 접근 권한이 없습니다.", a11y: { region: "캘린더", grid: "캘린더 그리드", diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index 67a2db23a4b..c32ace97b3d 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -798,6 +798,7 @@ const pt = { eventTitlePlaceholder: "Sobre o que é este evento?", creating: "Criando…", titleRequired: "O título é obrigatório", + rescheduleNotFound: "Este registro de {{object}} não existe mais ou você não tem mais acesso a ele.", a11y: { region: "Calendário", grid: "Grade do calendário", diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index 4fae4cd6a1b..558f2eddef9 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -821,6 +821,7 @@ const ru = { eventTitlePlaceholder: "О чём это событие?", creating: "Создание…", titleRequired: "Укажите название", + rescheduleNotFound: "Эта запись ({{object}}) больше не существует, или у вас больше нет к ней доступа.", a11y: { region: "Календарь", grid: "Сетка календаря", diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index 9d9bcf763f4..150b5af348f 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -800,6 +800,7 @@ const zh = { eventTitlePlaceholder: '这个事件是关于什么的?', creating: '创建中…', titleRequired: '请填写标题', + rescheduleNotFound: '这条{{object}}记录已不存在,或者您已无权访问它。', a11y: { region: '日历', grid: '日历网格', diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index e6bbf01795f..5d7fa090ee1 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -800,6 +800,7 @@ const zhHant = { eventTitlePlaceholder: '這個事件是關於什麼的?', creating: '建立中…', titleRequired: '請填寫標題', + rescheduleNotFound: '這條{{object}}記錄已不存在,或者您已無權訪問它。', a11y: { region: '日曆', grid: '日曆網格', diff --git a/ui/packages/plugin-calendar/src/ObjectCalendar.markedRefusalToast.test.tsx b/ui/packages/plugin-calendar/src/ObjectCalendar.markedRefusalToast.test.tsx index 84cf3233a97..c95a81f3161 100644 --- a/ui/packages/plugin-calendar/src/ObjectCalendar.markedRefusalToast.test.tsx +++ b/ui/packages/plugin-calendar/src/ObjectCalendar.markedRefusalToast.test.tsx @@ -28,10 +28,11 @@ import React from 'react'; import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; -import { render, screen, fireEvent, cleanup, waitFor } from '@testing-library/react'; +import { render, screen, fireEvent, cleanup, waitFor, within } from '@testing-library/react'; import '@testing-library/jest-dom'; import { toast } from '@object-ui/components'; import { normaliseClientError } from '@object-ui/data-objectstack'; +import { I18nProvider } from '@object-ui/i18n'; import { ObjectCalendar } from './ObjectCalendar'; const MARKED = 'This visit cannot move outside the technician’s on-call window.'; @@ -50,22 +51,17 @@ const SOURCE_DAY = dayInThisMonth(1); const TARGET_DAY = dayInThisMonth(8); /** - * The cell's own aria-label, as THIS render produces it. - * - * ⚠️ Not "the way `MonthView` builds it" any more: `MonthView` formats that name - * with its RESOLVED locale (objectui#10144), which this rebuild does not have in - * hand. The two agree here only for as long as this provider-less render's - * resolved locale and the runtime default render a date identically — mount a - * non-`en` `I18nProvider` in this file and this helper has to be re-derived - * rather than trusted. + * The current-month grid cell of a day, found by its day number rather than + * by its spoken label, so a render under a non-`en` `I18nProvider` (whose + * resolved locale spells the label differently) finds it too. */ -const cellLabel = (d: Date) => - d.toLocaleDateString('default', { - weekday: 'long', - month: 'long', - day: 'numeric', - year: 'numeric', - }); +const monthCell = (d: Date): HTMLElement => { + const cells = screen.getAllByRole('gridcell').filter( + (cell) => !cell.className.includes('opacity-50') && cell.firstElementChild?.textContent === String(d.getDate()), + ); + expect(cells).toHaveLength(1); + return cells[0]; +}; const record = () => ({ id: 'v1', @@ -113,10 +109,11 @@ const forbidden = (userMessage?: string) => }), ); -function makeDataSource(rejectWith: unknown) { +function makeDataSource(rejectWith: unknown, label?: string) { return { getObjectSchema: vi.fn(async () => ({ name: 'visit', + ...(label ? { label } : {}), fields: { name: { type: 'text' }, starts_at: { type: 'datetime' } }, })), find: vi.fn(async () => ({ value: [record()] })), @@ -149,13 +146,16 @@ function performDnd(source: Element, target: Element) { * Mount the calendar on its OWN data (no `data` prop, no `onEventDrop`), drag * the event a week forward, and return the single toast text. */ -async function rescheduleAndReadToast(rejectWith: unknown): Promise { - const ds = makeDataSource(rejectWith); - render(); +async function rescheduleAndReadToast( + rejectWith: unknown, + { label, wrap }: { label?: string; wrap?: (ui: React.ReactElement) => React.ReactElement } = {}, +): Promise { + const ds = makeDataSource(rejectWith, label); + const ui = ; + render(wrap ? wrap(ui) : ui); const pill = await screen.findByLabelText(TITLE); - const targetCell = screen.getByLabelText(new RegExp(`^${cellLabel(TARGET_DAY)}`)); - performDnd(pill, targetCell); + performDnd(pill, monthCell(TARGET_DAY)); await waitFor(() => expect(ds.update).toHaveBeenCalledTimes(1)); await waitFor(() => expect(toast.error).toHaveBeenCalledTimes(1)); @@ -206,3 +206,87 @@ describe('ObjectCalendar — a marked refusal reaches the reschedule toast (#590 expect(String(said)).not.toContain('insufficient privileges'); }); }); + +/** + * A reschedule the server refuses with `404 RECORD_NOT_FOUND` (the record was + * deleted, or row-level security no longer shows it to this user) toasts a + * translated sentence naming the object by its LABEL, never the server's + * `Record ID not found in OBJECT_NAME` (objectstack#31494), and the event still + * snaps back to its day. + */ +const notFound = () => + normaliseClientError( + Object.assign(new Error('Record v1 not found in visit'), { + code: 'RECORD_NOT_FOUND', + httpStatus: 404, + details: { code: 'RECORD_NOT_FOUND', error: 'Record v1 not found in visit' }, + }), + ); + +const externalRefusal = () => + normaliseClientError( + Object.assign(new Error('EXTERNAL_WRITE_FORBIDDEN: visit is read-only'), { + code: 'EXTERNAL_WRITE_FORBIDDEN', + httpStatus: 403, + }), + ); + +/** The server's sentence leaks none of its machine parts: id, object name. */ +function expectNoServerParts(said: unknown) { + expect(String(said)).not.toContain('v1'); + expect(String(said)).not.toMatch(/\bvisit\b/); + expect(String(said)).not.toContain('not found in'); +} + +describe('ObjectCalendar — a reschedule of a record gone for this session (#31494)', () => { + it('names the object by its served label, with no id or machine name, and rolls back', async () => { + const said = await rescheduleAndReadToast(notFound(), { label: 'Appointment' }); + expect(said).toBe('This Appointment record no longer exists, or you no longer have access to it.'); + expectNoServerParts(said); + // The optimistic move is undone: the event is back on its own day. + await waitFor(() => expect(within(monthCell(SOURCE_DAY)).getByLabelText(TITLE)).toBeTruthy()); + expect(within(monthCell(TARGET_DAY)).queryByLabelText(TITLE)).toBeNull(); + }); + + it('speaks the session language: a zh session reads the zh sentence with the zh label', async () => { + const said = await rescheduleAndReadToast(notFound(), { + label: '任务', + wrap: (ui) => ( + + {ui} + + ), + }); + expect(said).toBe('这条任务记录已不存在,或者您已无权访问它。'); + expectNoServerParts(said); + }); + + it('with no label to show, says the generic sentence rather than the machine name', async () => { + const said = await rescheduleAndReadToast(notFound()); + expect(said).toBe("This record doesn't exist, or you don't have access to it."); + expectNoServerParts(said); + }); + + it('a 404 marked for the user still renders the marking', async () => { + const marked = normaliseClientError( + Object.assign(new Error('Record v1 not found in visit'), { + code: 'RECORD_NOT_FOUND', + httpStatus: 404, + userMessage: MARKED, + }), + ); + expect(await rescheduleAndReadToast(marked, { label: 'Appointment' })).toBe(MARKED); + }); + + it('leaves the external-source refusal its own read-only sentence', async () => { + expect(await rescheduleAndReadToast(externalRefusal(), { label: 'Appointment' })).toBe( + 'This table is read-only. Its records come from an external data source that does not accept changes.', + ); + }); + + it('leaves an unmarked 403 its localized permission substitution', async () => { + expect(await rescheduleAndReadToast(forbidden(), { label: 'Appointment' })).toBe( + 'You are not authorized to perform this action.', + ); + }); +}); diff --git a/ui/packages/plugin-calendar/src/ObjectCalendar.tsx b/ui/packages/plugin-calendar/src/ObjectCalendar.tsx index 4ea570d8fdb..8e0352a2bba 100644 --- a/ui/packages/plugin-calendar/src/ObjectCalendar.tsx +++ b/ui/packages/plugin-calendar/src/ObjectCalendar.tsx @@ -24,6 +24,7 @@ import React, { useEffect, useState, useCallback, useMemo, useRef } from 'react'; import type { ObjectCalendarSchema, DataSource, CalendarConfig } from '@object-ui/types'; +import { errorCodeIs } from '@object-ui/types'; import { CalendarView, type CalendarViewEvent } from './CalendarView'; import { getVisibleDateRange } from './visibleDays'; import { @@ -38,6 +39,7 @@ import { useNavigationOverlay, useSafeTranslate, useObjectTranslation, + useSafeFieldLabel, extractWriteErrorMessage, isPermissionError, isExternalWriteRefusal, @@ -496,6 +498,19 @@ interface UnscheduledRecord { title: string; } +/** + * A write the server refused because the record is not there for this + * session: `404 RECORD_NOT_FOUND`, which a deleted row and a row row-level + * security no longer shows this user both answer. Read from the error and its + * `details`, the pair the adapter boundary parks the envelope in. + */ +function isRecordNotFound(err: unknown): boolean { + if (!err || typeof err !== 'object') return false; + const e = err as { httpStatus?: unknown; status?: unknown; statusCode?: unknown; details?: unknown }; + if (errorCodeIs(e, 'RECORD_NOT_FOUND') || errorCodeIs(e.details, 'RECORD_NOT_FOUND')) return true; + return (e.httpStatus ?? e.status ?? e.statusCode) === 404; +} + export const ObjectCalendar: React.FC = ({ schema, dataSource, @@ -519,6 +534,9 @@ export const ObjectCalendar: React.FC = ({ // the provider-less fallback the same way (objectui#6219), so the label is // correct whether or not an `I18nProvider` is mounted. const { t } = useObjectTranslation(); + // The app's translation of the object label, for a refusal toast that names + // the object when the served schema carries no label of its own. + const labels = useSafeFieldLabel(); // The locale the quick-create dialog formats its date and time with: the // month grid's own rule (`CalendarView`'s `effectiveLocale`), so the dialog // never disagrees with the cell it opened from. A set `locale` prop is the @@ -1345,10 +1363,31 @@ export const ObjectCalendar: React.FC = ({ ? tt('form.readOnlyExternalSource', 'This table is read-only. Its records come from an external data source that does not accept changes.') : isPermissionError(err) ? tt('errors.unauthorized', 'You are not authorized to perform this action.') + // The row is gone for this session: deleted, or no longer visible + // to it. The server's sentence carries the record id and the + // object's machine name, so it is never shown; the object is named + // by its label (objectstack#31494). + : isRecordNotFound(err) + ? rescheduleNotFoundMessage() : extractWriteErrorMessage(err) ?? tt('table.saveFailed', 'Save failed')), ); } - }, [calendarConfig, schema.objectName, dataSource, data, tt, objectSchema]); + + function rescheduleNotFoundMessage(): string { + // The label the server serves, already translated (objectstack#30390), + // else the app's translation of it, else no name at all: a machine name + // is never the fallback. + const served = typeof objectSchema?.label === 'string' ? objectSchema.label.trim() : ''; + const object = served + || ('objectLabel' in labels ? labels.objectLabel({ name: schema.objectName as string, label: '' }) : ''); + return object + ? t('calendar.rescheduleNotFound', { + object, + defaultValue: 'This {{object}} record no longer exists, or you no longer have access to it.', + }) + : tt('form.recordNotFoundOrHidden', "This record doesn't exist, or you don't have access to it."); + } + }, [calendarConfig, schema.objectName, dataSource, data, tt, t, labels, objectSchema]); // Quick-create state: clicking an empty day cell opens a small dialog // pre-filled with that date. On submit, dataSource.create() inserts a