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
12 changes: 12 additions & 0 deletions .changeset/31494-calendar-reschedule-not-found.md
Original file line number Diff line number Diff line change
@@ -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).
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 @@ -864,6 +864,7 @@ const ar = {
eventTitlePlaceholder: "ما موضوع هذا الحدث؟",
creating: "جارٍ الإنشاء…",
titleRequired: "العنوان مطلوب",
rescheduleNotFound: "سجل {{object}} هذا لم يعد موجودًا، أو لم يعد لديك إذن للوصول إليه.",
a11y: {
region: "التقويم",
grid: "شبكة التقويم",
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 @@ -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",
Expand Down
4 changes: 4 additions & 0 deletions ui/packages/i18n/src/locales/en.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
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 @@ -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",
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 @@ -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",
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 @@ -778,6 +778,7 @@ const ja = {
eventTitlePlaceholder: "この予定の内容は?",
creating: "作成中…",
titleRequired: "タイトルは必須です",
rescheduleNotFound: "この{{object}}レコードは存在しないか、アクセス権がなくなりました。",
a11y: {
region: "カレンダー",
grid: "カレンダーグリッド",
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 @@ -778,6 +778,7 @@ const ko = {
eventTitlePlaceholder: "이 일정은 어떤 내용인가요?",
creating: "생성 중…",
titleRequired: "제목을 입력하세요",
rescheduleNotFound: "이 {{object}} 레코드가 더 이상 존재하지 않거나 접근 권한이 없습니다.",
a11y: {
region: "캘린더",
grid: "캘린더 그리드",
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 @@ -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",
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 @@ -821,6 +821,7 @@ const ru = {
eventTitlePlaceholder: "О чём это событие?",
creating: "Создание…",
titleRequired: "Укажите название",
rescheduleNotFound: "Эта запись ({{object}}) больше не существует, или у вас больше нет к ней доступа.",
a11y: {
region: "Календарь",
grid: "Сетка календаря",
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 @@ -800,6 +800,7 @@ const zh = {
eventTitlePlaceholder: '这个事件是关于什么的?',
creating: '创建中…',
titleRequired: '请填写标题',
rescheduleNotFound: '这条{{object}}记录已不存在,或者您已无权访问它。',
a11y: {
region: '日历',
grid: '日历网格',
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 @@ -800,6 +800,7 @@ const zhHant = {
eventTitlePlaceholder: '這個事件是關於什麼的?',
creating: '建立中…',
titleRequired: '請填寫標題',
rescheduleNotFound: '這條{{object}}記錄已不存在,或者您已無權訪問它。',
a11y: {
region: '日曆',
grid: '日曆網格',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.';
Expand All @@ -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',
Expand Down Expand Up @@ -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()] })),
Expand Down Expand Up @@ -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<unknown> {
const ds = makeDataSource(rejectWith);
render(<ObjectCalendar schema={schema} dataSource={ds as never} />);
async function rescheduleAndReadToast(
rejectWith: unknown,
{ label, wrap }: { label?: string; wrap?: (ui: React.ReactElement) => React.ReactElement } = {},
): Promise<unknown> {
const ds = makeDataSource(rejectWith, label);
const ui = <ObjectCalendar schema={schema} dataSource={ds as never} />;
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));
Expand Down Expand Up @@ -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) => (
<I18nProvider config={{ defaultLanguage: 'zh', detectBrowserLanguage: false, warnMissingKeys: false }}>
{ui}
</I18nProvider>
),
});
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.',
);
});
});
41 changes: 40 additions & 1 deletion ui/packages/plugin-calendar/src/ObjectCalendar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -38,6 +39,7 @@ import {
useNavigationOverlay,
useSafeTranslate,
useObjectTranslation,
useSafeFieldLabel,
extractWriteErrorMessage,
isPermissionError,
isExternalWriteRefusal,
Expand Down Expand Up @@ -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<ObjectCalendarComponentProps> = ({
schema,
dataSource,
Expand All @@ -519,6 +534,9 @@ export const ObjectCalendar: React.FC<ObjectCalendarComponentProps> = ({
// 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
Expand Down Expand Up @@ -1345,10 +1363,31 @@ export const ObjectCalendar: React.FC<ObjectCalendarComponentProps> = ({
? 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
Expand Down
Loading