From a502b8c57587148051a1305db808c4ee2a9476fe Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 12:29:11 +0000 Subject: [PATCH 1/6] =?UTF-8?q?feat(setup):=20Setup=20=E2=86=92=20Configur?= =?UTF-8?q?ation=20=E2=86=92=20Public=20forms=20lists=20and=20switches=20e?= =?UTF-8?q?very=20public=20form?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Clause-②: no Metadata-protocol: none A system administrator's page for the operations half of public forms: every public form of the environment with its object and address, a switch to turn it on or off, copy its address, open it in a new tab. An installed app's form is switched as this environment's customization (an override in the app's .custom package, ADR-0146), never in the app. Claude-Session: https://claude.ai/code/session_01JQwxbWoxCrkYwcqxxENvmn Co-authored-by: Claude --- .changeset/36444-setup-public-forms.md | 19 ++ ...connect-agent-both-halves-wire.pin.test.ts | 10 +- .../src/apps/setup-nav.contributions.ts | 5 + .../src/apps/translations/ar.source-hashes.ts | 1 + .../src/apps/translations/ar.ts | 1 + .../src/apps/translations/de.source-hashes.ts | 1 + .../src/apps/translations/de.ts | 1 + .../src/apps/translations/en.ts | 1 + .../apps/translations/es-ES.source-hashes.ts | 1 + .../src/apps/translations/es-ES.ts | 1 + .../src/apps/translations/fr.source-hashes.ts | 1 + .../src/apps/translations/fr.ts | 1 + .../apps/translations/ja-JP.source-hashes.ts | 1 + .../src/apps/translations/ja-JP.ts | 1 + .../src/apps/translations/ko.source-hashes.ts | 1 + .../src/apps/translations/ko.ts | 1 + .../apps/translations/pt-BR.source-hashes.ts | 1 + .../src/apps/translations/pt-BR.ts | 1 + .../src/apps/translations/ru.source-hashes.ts | 1 + .../src/apps/translations/ru.ts | 1 + .../apps/translations/zh-CN.source-hashes.ts | 1 + .../src/apps/translations/zh-CN.ts | 1 + .../translations/zh-Hant.source-hashes.ts | 1 + .../src/apps/translations/zh-Hant.ts | 1 + .../src/services/builtinComponents.tsx | 17 + ...licFormsSetupPage.navContribution.test.tsx | 57 ++++ .../src/views/setup/PublicFormsSetupPage.tsx | 291 ++++++++++++++++++ .../src/views/setup/publicForms.test.ts | 241 +++++++++++++++ .../app-shell/src/views/setup/publicForms.ts | 260 ++++++++++++++++ .../src/views/setup/publicFormsRef.ts | 25 ++ ui/packages/i18n/src/locales/ar.ts | 30 ++ ui/packages/i18n/src/locales/de.ts | 30 ++ ui/packages/i18n/src/locales/en.ts | 30 ++ ui/packages/i18n/src/locales/es.ts | 30 ++ ui/packages/i18n/src/locales/fr.ts | 30 ++ ui/packages/i18n/src/locales/ja.ts | 30 ++ ui/packages/i18n/src/locales/ko.ts | 30 ++ ui/packages/i18n/src/locales/pt-BR.ts | 30 ++ ui/packages/i18n/src/locales/ru.ts | 30 ++ ui/packages/i18n/src/locales/zh-Hans.ts | 30 ++ ui/packages/i18n/src/locales/zh-Hant.ts | 30 ++ 41 files changed, 1272 insertions(+), 4 deletions(-) create mode 100644 .changeset/36444-setup-public-forms.md create mode 100644 ui/packages/app-shell/src/views/setup/PublicFormsSetupPage.navContribution.test.tsx create mode 100644 ui/packages/app-shell/src/views/setup/PublicFormsSetupPage.tsx create mode 100644 ui/packages/app-shell/src/views/setup/publicForms.test.ts create mode 100644 ui/packages/app-shell/src/views/setup/publicForms.ts create mode 100644 ui/packages/app-shell/src/views/setup/publicFormsRef.ts diff --git a/.changeset/36444-setup-public-forms.md b/.changeset/36444-setup-public-forms.md new file mode 100644 index 00000000000..dbfbea7ffd2 --- /dev/null +++ b/.changeset/36444-setup-public-forms.md @@ -0,0 +1,19 @@ +--- +'@object-ui/app-shell': patch +'@object-ui/i18n': patch +'@objectstack/platform-objects': patch +--- + +feat(setup): Setup → Configuration → Public forms lists every public form of the environment and switches it on or off + +Clause-②: no +Metadata-protocol: none + +A system administrator (`manage_platform_settings`, the capability the Setup entry asks) now has one page for the operations side of public forms. It lists every public form of the environment: its name, the object a submission creates a record of, its address, and whether it is on. Per row: switch it on or off, copy its address, or open it in a new tab. A form is designed (created, deleted, its fields and title changed) in Studio, not here. + +- **Which forms are listed.** A form view whose `sharing` opens it to anonymous intake once switched on (`allowAnonymous: true` and a `publicLink`), read by the same rule the anonymous form routes use (`anonymousFormIntakeCandidates`). A switched-off form stays listed and can be switched back on. A form with no public address or no anonymous access is an internal form and is not listed. The list is the effective one (`GET /meta/view`), so an installed app's form switched off in this environment lists as off. +- **Where a switch is saved.** The switch is the form's `sharing.enabled`, saved and published at once. A form of a writable package is saved in that package. A form of an installed (read-only) app is saved as this environment's customization, an override in the app's `.custom` package (ADR-0146), never an edit of the app's own package, so the app upgrades as before. Switching such a form back on removes the override when it held nothing but the switch, so the app's own form is served again; an override that also carries design changes keeps them, with the switch on. +- A switch over a draft already pending where it would save writes nothing and says so: that draft is its saver's and is never published on their behalf. +- A switched-off form keeps answering as it does today: `404 FORM_NOT_FOUND` at its address. No route, error code or stored key is added. + +New Setup navigation entry `nav_public_forms` in `group_configuration` (label "Public Forms", in every shipped locale) opening the component `forms:public-forms`; the Setup navigation now carries 35 entries. New locale block `publicFormsSetup` in every console locale. Not shown: when a form last took a submission, since a submission is an ordinary record of the form's object and records no form. diff --git a/packages/cli/test/connect-agent-both-halves-wire.pin.test.ts b/packages/cli/test/connect-agent-both-halves-wire.pin.test.ts index ac747f610fe..639691f771c 100644 --- a/packages/cli/test/connect-agent-both-halves-wire.pin.test.ts +++ b/packages/cli/test/connect-agent-both-halves-wire.pin.test.ts @@ -277,13 +277,15 @@ describe('#17647 — Connect-an-Agent visibility: BOTH halves, over the wire', ( // `group_apps` held here, so that group collapses too; 31 until the // Units of Measure entry, `nav_units_of_measure`, joined Configuration // (#35488); 32 until the working-calendar pair, `nav_work_calendars` - // and `nav_work_calendar_exceptions`, joined it, ADR-0157.) + // and `nav_work_calendar_exceptions`, joined it, ADR-0157; 34 until + // the public forms entry, `nav_public_forms`, joined it, #36444.) // `nav_settings_branding` is not among them, and not because of a // tenancy wall (this harness boots none): since #24766 it is // contributed by `@objectstack/service-settings` together with the // `branding` namespace, offered only where no organization wall stands, // and this harness composes platform-objects and the MCP bundle alone. - expect(allowedIds).toHaveLength(34); + expect(allowedIds).toHaveLength(35); + expect(allowedIds).toContain('nav_public_forms'); expect(allowedIds).toContain('nav_work_calendars'); expect(allowedIds).toContain('nav_work_calendar_exceptions'); expect(allowedIds).not.toContain('nav_packaged_actions'); @@ -312,8 +314,8 @@ describe('#17647 — Connect-an-Agent visibility: BOTH halves, over the wire', ( expect(withAccountHalf.statusCode).toBe(200); expect(withoutAccountHalf.statusCode).toBe(200); expect(navIds(withAccountHalf.body?.item)).toEqual(navIds(withoutAccountHalf.body?.item)); - // 34: the composition the count in the test above states. - expect(navIds(withAccountHalf.body?.item)).toHaveLength(34); + // 35: the composition the count in the test above states. + expect(navIds(withAccountHalf.body?.item)).toHaveLength(35); // The mechanism behind the invariance, asserted rather than assumed: // the bundle aims exactly one contribution at `setup` and one at diff --git a/packages/platform-objects/src/apps/setup-nav.contributions.ts b/packages/platform-objects/src/apps/setup-nav.contributions.ts index 2cd8fc1768e..0a80c083cd2 100644 --- a/packages/platform-objects/src/apps/setup-nav.contributions.ts +++ b/packages/platform-objects/src/apps/setup-nav.contributions.ts @@ -180,6 +180,11 @@ export const SETUP_NAV_CONTRIBUTIONS: NavigationContribution[] = [ // per object (`manageRecycleBin`), and the page lists only the objects // whose bin the caller manages. { id: 'nav_recycle_bin', type: 'component', label: 'Recycle Bin', componentRef: 'data:recycle-bin', icon: 'trash-2' }, + // objectstack#36444 — every public form of the environment (a form anyone + // fills in without signing in): switch one on or off, copy its address, + // open it. Operations only; Studio designs the forms. For system + // administrators: the page asks the same capability. + { id: 'nav_public_forms', type: 'component', label: 'Public Forms', componentRef: 'forms:public-forms', icon: 'file-text', requiredPermissions: ['manage_platform_settings'] }, ], }, { diff --git a/packages/platform-objects/src/apps/translations/ar.source-hashes.ts b/packages/platform-objects/src/apps/translations/ar.source-hashes.ts index e78465f76d6..454966cef1d 100644 --- a/packages/platform-objects/src/apps/translations/ar.source-hashes.ts +++ b/packages/platform-objects/src/apps/translations/ar.source-hashes.ts @@ -118,6 +118,7 @@ export const arSourceHashes: Readonly> = { 'apps.setup.navigation.nav_settings_knowledge.label': '140348539a50d9d5', 'apps.setup.navigation.nav_settings_lifecycle.label': 'cd9fe9c930afed06', 'apps.setup.navigation.nav_recycle_bin.label': '2f5aefe2be221196', + 'apps.setup.navigation.nav_public_forms.label': '4592e97959994e86', 'apps.setup.navigation.nav_notification_preferences.label': '8869f324c1bd545a', 'apps.setup.navigation.nav_notification_templates.label': '9e270c87ef2578df', 'apps.setup.navigation.nav_sessions.label': '673bde6e0c8a3ef9', diff --git a/packages/platform-objects/src/apps/translations/ar.ts b/packages/platform-objects/src/apps/translations/ar.ts index 0c2b2cbd2d3..408b5762b7f 100644 --- a/packages/platform-objects/src/apps/translations/ar.ts +++ b/packages/platform-objects/src/apps/translations/ar.ts @@ -108,6 +108,7 @@ export const ar: TranslationData = { nav_settings_knowledge: { label: 'المعرفة' }, nav_settings_lifecycle: { label: 'دورة حياة البيانات' }, nav_recycle_bin: { label: 'سلة المحذوفات' }, + nav_public_forms: { label: 'النماذج العامة' }, nav_notification_preferences: { label: 'تفضيلات الإشعارات' }, nav_notification_templates: { label: 'قوالب الإشعارات' }, diff --git a/packages/platform-objects/src/apps/translations/de.source-hashes.ts b/packages/platform-objects/src/apps/translations/de.source-hashes.ts index 91a326ba4c7..b9658f39303 100644 --- a/packages/platform-objects/src/apps/translations/de.source-hashes.ts +++ b/packages/platform-objects/src/apps/translations/de.source-hashes.ts @@ -119,6 +119,7 @@ export const deSourceHashes: Readonly> = { 'apps.setup.navigation.nav_settings_knowledge.label': '140348539a50d9d5', 'apps.setup.navigation.nav_settings_lifecycle.label': 'cd9fe9c930afed06', 'apps.setup.navigation.nav_recycle_bin.label': '2f5aefe2be221196', + 'apps.setup.navigation.nav_public_forms.label': '4592e97959994e86', 'apps.setup.navigation.nav_notification_preferences.label': '8869f324c1bd545a', 'apps.setup.navigation.nav_notification_templates.label': '9e270c87ef2578df', 'apps.setup.navigation.nav_sessions.label': '673bde6e0c8a3ef9', diff --git a/packages/platform-objects/src/apps/translations/de.ts b/packages/platform-objects/src/apps/translations/de.ts index 68868cfa17e..d902ee0ea08 100644 --- a/packages/platform-objects/src/apps/translations/de.ts +++ b/packages/platform-objects/src/apps/translations/de.ts @@ -110,6 +110,7 @@ export const de: TranslationData = { nav_settings_knowledge: { label: 'Wissen' }, nav_settings_lifecycle: { label: 'Datenlebenszyklus' }, nav_recycle_bin: { label: 'Papierkorb' }, + nav_public_forms: { label: 'Öffentliche Formulare' }, nav_notification_preferences: { label: 'Benachrichtigungseinstellungen' }, nav_notification_templates: { label: 'Benachrichtigungsvorlagen' }, diff --git a/packages/platform-objects/src/apps/translations/en.ts b/packages/platform-objects/src/apps/translations/en.ts index c9967e11236..f838799bb91 100644 --- a/packages/platform-objects/src/apps/translations/en.ts +++ b/packages/platform-objects/src/apps/translations/en.ts @@ -144,6 +144,7 @@ export const en: TranslationData = { nav_settings_knowledge: { label: 'Knowledge' }, nav_settings_lifecycle: { label: 'Data Lifecycle' }, nav_recycle_bin: { label: 'Recycle Bin' }, + nav_public_forms: { label: 'Public Forms' }, // Notifications (contributed by @objectstack/service-messaging) nav_notification_preferences: { label: 'Notification Preferences' }, nav_notification_templates: { label: 'Notification Templates' }, diff --git a/packages/platform-objects/src/apps/translations/es-ES.source-hashes.ts b/packages/platform-objects/src/apps/translations/es-ES.source-hashes.ts index 023e221da6a..d2bd3649a8a 100644 --- a/packages/platform-objects/src/apps/translations/es-ES.source-hashes.ts +++ b/packages/platform-objects/src/apps/translations/es-ES.source-hashes.ts @@ -113,6 +113,7 @@ export const esESSourceHashes: Readonly> = { 'apps.setup.navigation.nav_settings_knowledge.label': '140348539a50d9d5', 'apps.setup.navigation.nav_settings_lifecycle.label': 'cd9fe9c930afed06', 'apps.setup.navigation.nav_recycle_bin.label': '2f5aefe2be221196', + 'apps.setup.navigation.nav_public_forms.label': '4592e97959994e86', 'apps.setup.navigation.nav_notification_preferences.label': '8869f324c1bd545a', 'apps.setup.navigation.nav_notification_templates.label': '9e270c87ef2578df', 'apps.setup.navigation.nav_sessions.label': '673bde6e0c8a3ef9', diff --git a/packages/platform-objects/src/apps/translations/es-ES.ts b/packages/platform-objects/src/apps/translations/es-ES.ts index 94f2fe549ff..631862b7ebd 100644 --- a/packages/platform-objects/src/apps/translations/es-ES.ts +++ b/packages/platform-objects/src/apps/translations/es-ES.ts @@ -99,6 +99,7 @@ export const esES: TranslationData = { nav_settings_knowledge: { label: 'Conocimiento' }, nav_settings_lifecycle: { label: 'Ciclo de vida de los datos' }, nav_recycle_bin: { label: 'Papelera' }, + nav_public_forms: { label: 'Formularios públicos' }, nav_notification_preferences: { label: 'Preferencias de Notificación' }, nav_notification_templates: { label: 'Plantillas de Notificación' }, diff --git a/packages/platform-objects/src/apps/translations/fr.source-hashes.ts b/packages/platform-objects/src/apps/translations/fr.source-hashes.ts index 95bbcde6467..4542ee66937 100644 --- a/packages/platform-objects/src/apps/translations/fr.source-hashes.ts +++ b/packages/platform-objects/src/apps/translations/fr.source-hashes.ts @@ -119,6 +119,7 @@ export const frSourceHashes: Readonly> = { 'apps.setup.navigation.nav_settings_knowledge.label': '140348539a50d9d5', 'apps.setup.navigation.nav_settings_lifecycle.label': 'cd9fe9c930afed06', 'apps.setup.navigation.nav_recycle_bin.label': '2f5aefe2be221196', + 'apps.setup.navigation.nav_public_forms.label': '4592e97959994e86', 'apps.setup.navigation.nav_notification_preferences.label': '8869f324c1bd545a', 'apps.setup.navigation.nav_notification_templates.label': '9e270c87ef2578df', 'apps.setup.navigation.nav_sessions.label': '673bde6e0c8a3ef9', diff --git a/packages/platform-objects/src/apps/translations/fr.ts b/packages/platform-objects/src/apps/translations/fr.ts index bf54af71032..31a72a9e4fe 100644 --- a/packages/platform-objects/src/apps/translations/fr.ts +++ b/packages/platform-objects/src/apps/translations/fr.ts @@ -110,6 +110,7 @@ export const fr: TranslationData = { nav_settings_knowledge: { label: 'Connaissances' }, nav_settings_lifecycle: { label: 'Cycle de vie des données' }, nav_recycle_bin: { label: 'Corbeille' }, + nav_public_forms: { label: 'Formulaires publics' }, nav_notification_preferences: { label: 'Préférences de notification' }, nav_notification_templates: { label: 'Modèles de notification' }, diff --git a/packages/platform-objects/src/apps/translations/ja-JP.source-hashes.ts b/packages/platform-objects/src/apps/translations/ja-JP.source-hashes.ts index 76deb492423..b1b14df8e66 100644 --- a/packages/platform-objects/src/apps/translations/ja-JP.source-hashes.ts +++ b/packages/platform-objects/src/apps/translations/ja-JP.source-hashes.ts @@ -113,6 +113,7 @@ export const jaJPSourceHashes: Readonly> = { 'apps.setup.navigation.nav_settings_knowledge.label': '140348539a50d9d5', 'apps.setup.navigation.nav_settings_lifecycle.label': 'cd9fe9c930afed06', 'apps.setup.navigation.nav_recycle_bin.label': '2f5aefe2be221196', + 'apps.setup.navigation.nav_public_forms.label': '4592e97959994e86', 'apps.setup.navigation.nav_notification_preferences.label': '8869f324c1bd545a', 'apps.setup.navigation.nav_notification_templates.label': '9e270c87ef2578df', 'apps.setup.navigation.nav_sessions.label': '673bde6e0c8a3ef9', diff --git a/packages/platform-objects/src/apps/translations/ja-JP.ts b/packages/platform-objects/src/apps/translations/ja-JP.ts index a47aab85a20..ca95254d362 100644 --- a/packages/platform-objects/src/apps/translations/ja-JP.ts +++ b/packages/platform-objects/src/apps/translations/ja-JP.ts @@ -99,6 +99,7 @@ export const jaJP: TranslationData = { nav_settings_knowledge: { label: 'ナレッジ' }, nav_settings_lifecycle: { label: 'データライフサイクル' }, nav_recycle_bin: { label: 'ごみ箱' }, + nav_public_forms: { label: '公開フォーム' }, nav_notification_preferences: { label: '通知設定' }, nav_notification_templates: { label: '通知テンプレート' }, diff --git a/packages/platform-objects/src/apps/translations/ko.source-hashes.ts b/packages/platform-objects/src/apps/translations/ko.source-hashes.ts index 7733c67416e..4082cd352bf 100644 --- a/packages/platform-objects/src/apps/translations/ko.source-hashes.ts +++ b/packages/platform-objects/src/apps/translations/ko.source-hashes.ts @@ -119,6 +119,7 @@ export const koSourceHashes: Readonly> = { 'apps.setup.navigation.nav_settings_knowledge.label': '140348539a50d9d5', 'apps.setup.navigation.nav_settings_lifecycle.label': 'cd9fe9c930afed06', 'apps.setup.navigation.nav_recycle_bin.label': '2f5aefe2be221196', + 'apps.setup.navigation.nav_public_forms.label': '4592e97959994e86', 'apps.setup.navigation.nav_notification_preferences.label': '8869f324c1bd545a', 'apps.setup.navigation.nav_notification_templates.label': '9e270c87ef2578df', 'apps.setup.navigation.nav_sessions.label': '673bde6e0c8a3ef9', diff --git a/packages/platform-objects/src/apps/translations/ko.ts b/packages/platform-objects/src/apps/translations/ko.ts index 66f39ddb906..d559c18d6b3 100644 --- a/packages/platform-objects/src/apps/translations/ko.ts +++ b/packages/platform-objects/src/apps/translations/ko.ts @@ -109,6 +109,7 @@ export const ko: TranslationData = { nav_settings_knowledge: { label: '지식' }, nav_settings_lifecycle: { label: '데이터 수명 주기' }, nav_recycle_bin: { label: '휴지통' }, + nav_public_forms: { label: '공개 양식' }, nav_notification_preferences: { label: '알림 기본 설정' }, nav_notification_templates: { label: '알림 템플릿' }, diff --git a/packages/platform-objects/src/apps/translations/pt-BR.source-hashes.ts b/packages/platform-objects/src/apps/translations/pt-BR.source-hashes.ts index 28d50b41e88..f473168c46c 100644 --- a/packages/platform-objects/src/apps/translations/pt-BR.source-hashes.ts +++ b/packages/platform-objects/src/apps/translations/pt-BR.source-hashes.ts @@ -119,6 +119,7 @@ export const ptBRSourceHashes: Readonly> = { 'apps.setup.navigation.nav_settings_knowledge.label': '140348539a50d9d5', 'apps.setup.navigation.nav_settings_lifecycle.label': 'cd9fe9c930afed06', 'apps.setup.navigation.nav_recycle_bin.label': '2f5aefe2be221196', + 'apps.setup.navigation.nav_public_forms.label': '4592e97959994e86', 'apps.setup.navigation.nav_notification_preferences.label': '8869f324c1bd545a', 'apps.setup.navigation.nav_notification_templates.label': '9e270c87ef2578df', 'apps.setup.navigation.nav_sessions.label': '673bde6e0c8a3ef9', diff --git a/packages/platform-objects/src/apps/translations/pt-BR.ts b/packages/platform-objects/src/apps/translations/pt-BR.ts index 6599e9845c5..14c272900e1 100644 --- a/packages/platform-objects/src/apps/translations/pt-BR.ts +++ b/packages/platform-objects/src/apps/translations/pt-BR.ts @@ -110,6 +110,7 @@ export const ptBR: TranslationData = { nav_settings_knowledge: { label: 'Conhecimento' }, nav_settings_lifecycle: { label: 'Ciclo de vida dos dados' }, nav_recycle_bin: { label: 'Lixeira' }, + nav_public_forms: { label: 'Formulários públicos' }, nav_notification_preferences: { label: 'Preferências de notificação' }, nav_notification_templates: { label: 'Modelos de notificação' }, diff --git a/packages/platform-objects/src/apps/translations/ru.source-hashes.ts b/packages/platform-objects/src/apps/translations/ru.source-hashes.ts index d0c1b7036ec..61a2f439e25 100644 --- a/packages/platform-objects/src/apps/translations/ru.source-hashes.ts +++ b/packages/platform-objects/src/apps/translations/ru.source-hashes.ts @@ -119,6 +119,7 @@ export const ruSourceHashes: Readonly> = { 'apps.setup.navigation.nav_settings_knowledge.label': '140348539a50d9d5', 'apps.setup.navigation.nav_settings_lifecycle.label': 'cd9fe9c930afed06', 'apps.setup.navigation.nav_recycle_bin.label': '2f5aefe2be221196', + 'apps.setup.navigation.nav_public_forms.label': '4592e97959994e86', 'apps.setup.navigation.nav_notification_preferences.label': '8869f324c1bd545a', 'apps.setup.navigation.nav_notification_templates.label': '9e270c87ef2578df', 'apps.setup.navigation.nav_sessions.label': '673bde6e0c8a3ef9', diff --git a/packages/platform-objects/src/apps/translations/ru.ts b/packages/platform-objects/src/apps/translations/ru.ts index 410c388a5a7..081243f4562 100644 --- a/packages/platform-objects/src/apps/translations/ru.ts +++ b/packages/platform-objects/src/apps/translations/ru.ts @@ -110,6 +110,7 @@ export const ru: TranslationData = { nav_settings_knowledge: { label: 'Знания' }, nav_settings_lifecycle: { label: 'Жизненный цикл данных' }, nav_recycle_bin: { label: 'Корзина' }, + nav_public_forms: { label: 'Публичные формы' }, nav_notification_preferences: { label: 'Настройки уведомлений' }, nav_notification_templates: { label: 'Шаблоны уведомлений' }, diff --git a/packages/platform-objects/src/apps/translations/zh-CN.source-hashes.ts b/packages/platform-objects/src/apps/translations/zh-CN.source-hashes.ts index 30c92c6e58b..6edb761ef47 100644 --- a/packages/platform-objects/src/apps/translations/zh-CN.source-hashes.ts +++ b/packages/platform-objects/src/apps/translations/zh-CN.source-hashes.ts @@ -113,6 +113,7 @@ export const zhCNSourceHashes: Readonly> = { 'apps.setup.navigation.nav_settings_knowledge.label': '140348539a50d9d5', 'apps.setup.navigation.nav_settings_lifecycle.label': 'cd9fe9c930afed06', 'apps.setup.navigation.nav_recycle_bin.label': '2f5aefe2be221196', + 'apps.setup.navigation.nav_public_forms.label': '4592e97959994e86', 'apps.setup.navigation.nav_notification_preferences.label': '8869f324c1bd545a', 'apps.setup.navigation.nav_notification_templates.label': '9e270c87ef2578df', 'apps.setup.navigation.nav_sessions.label': '673bde6e0c8a3ef9', diff --git a/packages/platform-objects/src/apps/translations/zh-CN.ts b/packages/platform-objects/src/apps/translations/zh-CN.ts index b95b2ac04ca..f1bf96552fe 100644 --- a/packages/platform-objects/src/apps/translations/zh-CN.ts +++ b/packages/platform-objects/src/apps/translations/zh-CN.ts @@ -103,6 +103,7 @@ export const zhCN: TranslationData = { nav_settings_knowledge: { label: '知识库' }, nav_settings_lifecycle: { label: '数据生命周期' }, nav_recycle_bin: { label: '回收站' }, + nav_public_forms: { label: '对外表单' }, nav_notification_preferences: { label: '通知偏好' }, nav_notification_templates: { label: '通知模板' }, diff --git a/packages/platform-objects/src/apps/translations/zh-Hant.source-hashes.ts b/packages/platform-objects/src/apps/translations/zh-Hant.source-hashes.ts index 519f7384c29..f56886ef799 100644 --- a/packages/platform-objects/src/apps/translations/zh-Hant.source-hashes.ts +++ b/packages/platform-objects/src/apps/translations/zh-Hant.source-hashes.ts @@ -118,6 +118,7 @@ export const zhHantSourceHashes: Readonly> = { 'apps.setup.navigation.nav_settings_knowledge.label': '140348539a50d9d5', 'apps.setup.navigation.nav_settings_lifecycle.label': 'cd9fe9c930afed06', 'apps.setup.navigation.nav_recycle_bin.label': '2f5aefe2be221196', + 'apps.setup.navigation.nav_public_forms.label': '4592e97959994e86', 'apps.setup.navigation.nav_notification_preferences.label': '8869f324c1bd545a', 'apps.setup.navigation.nav_notification_templates.label': '9e270c87ef2578df', 'apps.setup.navigation.nav_sessions.label': '673bde6e0c8a3ef9', diff --git a/packages/platform-objects/src/apps/translations/zh-Hant.ts b/packages/platform-objects/src/apps/translations/zh-Hant.ts index b55762e124b..e8a5c44c13b 100644 --- a/packages/platform-objects/src/apps/translations/zh-Hant.ts +++ b/packages/platform-objects/src/apps/translations/zh-Hant.ts @@ -108,6 +108,7 @@ export const zhHant: TranslationData = { nav_settings_knowledge: { label: '知識庫' }, nav_settings_lifecycle: { label: '資料生命週期' }, nav_recycle_bin: { label: '回收站' }, + nav_public_forms: { label: '對外表單' }, nav_notification_preferences: { label: '通知偏好設定' }, nav_notification_templates: { label: '通知範本' }, diff --git a/ui/packages/app-shell/src/services/builtinComponents.tsx b/ui/packages/app-shell/src/services/builtinComponents.tsx index 898e84ebe15..d986c460349 100644 --- a/ui/packages/app-shell/src/services/builtinComponents.tsx +++ b/ui/packages/app-shell/src/services/builtinComponents.tsx @@ -23,6 +23,7 @@ import { CONNECTOR_CREDENTIALS_REF } from '../views/setup/connectorCredentials.j import { CONNECTOR_CONNECTIONS_REF } from '../views/setup/connectorConnections.js'; import { PERMISSION_SET_ASSIGNMENT_REF, POSITION_HOLDERS_REF } from '../views/setup/peopleAssignments.js'; import { RECYCLE_BIN_REF } from '../views/setup/recycleBin.js'; +import { PUBLIC_FORMS_REF } from '../views/setup/publicFormsRef.js'; import { isAggregatedViewContainer, viewDisplayType, @@ -136,6 +137,9 @@ const PermissionSetAssignmentPage = lazyPage('permission set assignments', () => const RecycleBinPage = lazyPage('recycle bin', () => import('../views/setup/RecycleBinPage.js').then((m) => m.RecycleBinPage), ); +const PublicFormsSetupPage = lazyPage('public forms', () => + import('../views/setup/PublicFormsSetupPage.js').then((m) => m.PublicFormsSetupPage), +); const SlackSetupPage = lazyPage('slack', () => import('../views/setup/SlackSetupPage.js').then((m) => m.SlackSetupPage), ); @@ -278,6 +282,19 @@ registerAppComponent({ component: RecycleBinPage, }); +/** + * Setup → Configuration → Public forms (objectstack#36444): every public form + * of the environment, switched on or off, its address copied or opened; for + * system administrators. Studio designs the forms. The entry naming this ref is + * `@objectstack/platform-objects`' Setup navigation contribution. + */ +registerAppComponent({ + ref: PUBLIC_FORMS_REF, + label: 'Public Forms', + source: '@object-ui/app-shell', + component: PublicFormsSetupPage, +}); + /** * Setup's Slack page (ADR-0013 addendum, step 3 of objectstack#34730): an * organization administrator installs the organization's Slack app and manages diff --git a/ui/packages/app-shell/src/views/setup/PublicFormsSetupPage.navContribution.test.tsx b/ui/packages/app-shell/src/views/setup/PublicFormsSetupPage.navContribution.test.tsx new file mode 100644 index 00000000000..70864b02d22 --- /dev/null +++ b/ui/packages/app-shell/src/views/setup/PublicFormsSetupPage.navContribution.test.tsx @@ -0,0 +1,57 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * `forms:public-forms` — the component-registry key the Setup → Configuration + * → Public forms entry names (objectstack#36444). The same three properties as + * the other Setup pages' files: + * + * 1. the key is registered by the production registration module, imported + * the way `index.ts` does; + * 2. it addresses `component/forms/public-forms`, the URL its entry opens, + * built from the ref by the same helper; + * 3. the page mounts through that route. + * + * ⛔ No bespoke ``: the Setup nav contribution is the one way in. + */ + +import '@testing-library/jest-dom/vitest'; +import { afterEach, describe, expect, it } from 'vitest'; +import { cleanup, render, screen } from '@testing-library/react'; +import React from 'react'; +import { MemoryRouter, Route, Routes } from 'react-router-dom'; + +// Paid at collection, not inside a clocked case: the registration reaches +// `celAuthoring.ts`, which loads the linter on first use. +import '@objectstack/lint'; +// Side effect: the production registration, imported the way `index.ts` does. +import '../../services/builtinComponents.js'; +import { componentRefToUrlSegments, getAppComponent } from '../../services/componentRegistry.js'; +import { ComponentNavView } from '../ComponentNavView.js'; +import { PUBLIC_FORMS_CAPABILITY, PUBLIC_FORMS_REF, publicFormsPagePath } from './publicFormsRef.js'; + +afterEach(cleanup); + +describe('the Public forms page as a Setup nav contribution (objectstack#36444)', () => { + it('registers forms:public-forms, owned by app-shell, asking the Setup entry\'s capability', () => { + expect(PUBLIC_FORMS_REF).toBe('forms:public-forms'); + expect(PUBLIC_FORMS_CAPABILITY).toBe('manage_platform_settings'); + expect(getAppComponent(PUBLIC_FORMS_REF)?.source).toBe('@object-ui/app-shell'); + }); + + it('addresses component/forms/public-forms', () => { + expect(componentRefToUrlSegments(PUBLIC_FORMS_REF)).toEqual(['forms', 'public-forms']); + expect(publicFormsPagePath()).toBe('/apps/setup/component/forms/public-forms'); + }); + + it('mounts through the component route its ref builds', async () => { + render( + + + } /> + + , + ); + expect(await screen.findByTestId('public-forms-setup-page')).toBeInTheDocument(); + expect(screen.queryByText('Component not registered')).toBeNull(); + }); +}); diff --git a/ui/packages/app-shell/src/views/setup/PublicFormsSetupPage.tsx b/ui/packages/app-shell/src/views/setup/PublicFormsSetupPage.tsx new file mode 100644 index 00000000000..da1f32b9829 --- /dev/null +++ b/ui/packages/app-shell/src/views/setup/PublicFormsSetupPage.tsx @@ -0,0 +1,291 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * Setup → Configuration → Public forms (objectstack#36444): every public form + * of the environment, with its object and address; switch it on or off, copy + * its address, open it in a new tab. For system administrators only: the page + * asks the capability its Setup entry asks ({@link PUBLIC_FORMS_CAPABILITY}). + * + * Operations only: a form is designed (created, deleted, its fields and title + * changed) in Studio. Which forms are listed and where a switch is saved are + * `publicForms.ts`'s. + * + * The address is the router's answer for the anonymous form route `/f/:slug` + * (`useHref`, which prefixes the console's basename), as Studio's page builds + * it (objectui#11769), so it follows the mount the console runs under. + */ + +import * as React from 'react'; +import { useHref } from 'react-router-dom'; +import { toast } from 'sonner'; +import { AlertCircle, ExternalLink, FormInput, Link2, Loader2, RefreshCw } from 'lucide-react'; +import { + Alert, + AlertDescription, + Badge, + Button, + Skeleton, + Switch, + Table, + TableBody, + TableCell, + TableHead, + TableHeader, + TableRow, +} from '@object-ui/components'; +import { useObjectTranslation } from '@object-ui/i18n'; +import { usePermissions } from '@object-ui/permissions'; +import { useMetadata } from '@object-ui/react'; +import { useAdapter } from '../../providers/AdapterProvider.js'; +import { PageHeader } from '../../layout/PageHeader.js'; +import { useMetadataClient } from '../metadata-admin/useMetadata.js'; +import { formatMetadataError } from '@object-ui/data-objectstack'; +import { PUBLIC_FORMS_CAPABILITY } from './publicFormsRef.js'; +import { + PublicFormSwitchRefusal, + publicFormRowsOf, + switchPublicForm, + type PublicFormRow, +} from './publicForms.js'; + +/** The anonymous form route, as the console's router declares it (`/f/:slug`). */ +const PUBLIC_FORM_ROUTE = '/f'; + +type Translate = (key: string, options?: Record) => string; + +/** The sentence for a switch the console refused before writing. */ +function refusalText(t: Translate, err: PublicFormSwitchRefusal): string { + switch (err.reason) { + case 'no-package': + return t('publicFormsSetup.refusalNoPackage'); + case 'no-version': + return t('publicFormsSetup.refusalNoVersion'); + default: + return t('publicFormsSetup.refusalLoadFailed'); + } +} + +type Read = { kind: 'loading' } | { kind: 'failed'; message: string } | { kind: 'ready'; rows: PublicFormRow[] }; + +export function PublicFormsSetupPage() { + const { t } = useObjectTranslation(); + const { hasCapabilities } = usePermissions(); + const allowed = hasCapabilities([PUBLIC_FORMS_CAPABILITY]); + return ( +
+
+ ); +} + +function PublicFormsSetupBody() { + const { t } = useObjectTranslation(); + const adapter = useAdapter(); + const metadata = useMetadata(); + const metadataClient = useMetadataClient(); + const [read, setRead] = React.useState({ kind: 'loading' }); + const [busy, setBusy] = React.useState(null); + const [nonce, setNonce] = React.useState(0); + + React.useEffect(() => { + let live = true; + const client: any = (adapter as any)?.getClient?.(); + setRead({ kind: 'loading' }); + (async () => { + try { + if (!client?.meta?.getItems) throw new Error('meta.getItems is not available on this client'); + const answer = await client.meta.getItems('view'); + if (live) setRead({ kind: 'ready', rows: publicFormRowsOf(answer) }); + } catch (err) { + if (live) setRead({ kind: 'failed', message: formatMetadataError(err) }); + } + })(); + return () => { + live = false; + }; + }, [adapter, nonce]); + + const objectLabel = React.useCallback( + (name: string | undefined) => { + if (!name) return null; + const found = (metadata.objects ?? []).find((o: { name?: unknown } | null) => o?.name === name) as + | { label?: unknown } + | undefined; + return typeof found?.label === 'string' && found.label ? found.label : name; + }, + [metadata.objects], + ); + + const origin = typeof window !== 'undefined' ? window.location.origin : ''; + const formPath = useHref(PUBLIC_FORM_ROUTE); + const addressOf = (slug: string) => `${origin}${formPath}/${slug}`; + + const copy = async (address: string) => { + try { + await navigator.clipboard.writeText(address); + toast.success(t('publicFormsSetup.copied')); + } catch { + toast.error(t('publicFormsSetup.clipboardUnavailable')); + } + }; + + const flip = async (row: PublicFormRow, on: boolean) => { + setBusy(row.name); + try { + const outcome = await switchPublicForm(row, on, metadataClient as any, { dataSource: adapter as any }); + if (outcome === 'pending-draft') { + toast.error(t('publicFormsSetup.pendingDraft', { name: row.title })); + return; + } + toast.success(t(on ? 'publicFormsSetup.switchedOn' : 'publicFormsSetup.switchedOff', { name: row.title })); + // The row reads back as the server now serves it. + setRead((prev) => + prev.kind === 'ready' + ? { kind: 'ready', rows: prev.rows.map((r) => (r.name === row.name ? { ...r, on } : r)) } + : prev, + ); + setNonce((n) => n + 1); + } catch (err) { + const message = err instanceof PublicFormSwitchRefusal ? refusalText(t, err) : formatMetadataError(err); + toast.error(t('publicFormsSetup.switchFailed', { name: row.title, message })); + } finally { + setBusy(null); + } + }; + + const refresh = ( + + ); + + if (read.kind === 'loading') { + return ( +
+ + +
+ ); + } + if (read.kind === 'failed') { + return ( + + + + {t('publicFormsSetup.loadFailed', { message: read.message })} + {refresh} + + + ); + } + return ( +
+
+

{t('publicFormsSetup.designHint')}

+ {refresh} +
+ {read.rows.length === 0 ? ( +
+

{t('publicFormsSetup.emptyTitle')}

+

{t('publicFormsSetup.emptyBody')}

+
+ ) : ( +
+ + + + {t('publicFormsSetup.columnName')} + {t('publicFormsSetup.columnObject')} + {t('publicFormsSetup.columnAddress')} + {t('publicFormsSetup.columnStatus')} + {t('publicFormsSetup.columnActions')} + + + + {read.rows.map((row) => { + const address = addressOf(row.slug); + const label = objectLabel(row.object); + return ( + + {row.title} + {label ? {label} : null} + + {address} + + +
+ void flip(row, next)} + aria-label={t(row.on ? 'publicFormsSetup.switchOffLabel' : 'publicFormsSetup.switchOnLabel', { + name: row.title, + })} + data-testid={`public-form-switch-${row.name}`} + /> + + {busy === row.name ? ( + +
+
+ +
+ + +
+
+
+ ); + })} +
+
+
+ )} +
+ ); +} diff --git a/ui/packages/app-shell/src/views/setup/publicForms.test.ts b/ui/packages/app-shell/src/views/setup/publicForms.test.ts new file mode 100644 index 00000000000..a5adbb169e6 --- /dev/null +++ b/ui/packages/app-shell/src/views/setup/publicForms.test.ts @@ -0,0 +1,241 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { describe, it, expect, vi } from 'vitest'; +import { + PublicFormSwitchRefusal, + overrideHoldsOnlySwitch, + publicFormRowOf, + publicFormRowsOf, + switchPublicForm, +} from './publicForms'; + +/** + * objectstack#36444 — Setup → Public forms: which forms are listed and on, and + * where a switch is saved (a writable package, or an installed app's + * customization package, ADR-0146). + */ + +const sharing = (enabled: boolean, extra: Record = {}) => ({ + enabled, + allowAnonymous: true, + publicLink: 'contact-us', + ...extra, +}); + +const formItem = (overrides: Record = {}, enabled = true) => ({ + name: 'web_to_lead', + object: 'crm_lead', + viewKind: 'form', + label: 'Contact us', + _packageId: 'crm', + config: { title: 'Contact us', data: { object: 'crm_lead' }, sharing: sharing(enabled), sections: [] }, + ...overrides, +}); + +describe('publicFormRowOf', () => { + it('lists a form open to anonymous intake as on', () => { + expect(publicFormRowOf(formItem())).toEqual({ + name: 'web_to_lead', + title: 'Contact us', + object: 'crm_lead', + slug: 'contact-us', + on: true, + packageId: 'crm', + }); + }); + + it('keeps a switched-off form listed, as off', () => { + expect(publicFormRowOf(formItem({}, false))).toMatchObject({ name: 'web_to_lead', on: false, slug: 'contact-us' }); + }); + + it('does not list an internal form: not anonymous, or no address', () => { + const notAnonymous = formItem({ config: { title: 'x', sharing: { enabled: true, allowAnonymous: false, publicLink: 'x' } } }); + const noLink = formItem({ config: { title: 'x', sharing: { enabled: true, allowAnonymous: true } } }); + const noSharing = formItem({ config: { title: 'x' } }); + expect(publicFormRowOf(notAnonymous)).toBeNull(); + expect(publicFormRowOf(noLink)).toBeNull(); + expect(publicFormRowOf(noSharing)).toBeNull(); + }); + + it('does not list a view that is not a form, or one with no config', () => { + expect(publicFormRowOf(formItem({ viewKind: 'list' }))).toBeNull(); + expect(publicFormRowOf(formItem({ config: null }))).toBeNull(); + expect(publicFormRowOf(null)).toBeNull(); + }); + + it('names a form by its served label, else its title, else its first section, else its name; a package-less item has none', () => { + expect(publicFormRowOf(formItem({ label: undefined }))?.title).toBe('Contact us'); + const sectioned = { sharing: sharing(true), sections: [{ name: 'contact_us', label: 'Get in touch', fields: [] }] }; + expect(publicFormRowOf(formItem({ label: undefined, config: sectioned }))?.title).toBe('Get in touch'); + expect(publicFormRowOf(formItem({ label: '', config: { sharing: sharing(true) } }))?.title).toBe('web_to_lead'); + expect(publicFormRowOf(formItem({ name: 'crm_lead.web_to_lead', label: '', config: { sharing: sharing(true) } }))?.title).toBe( + 'web_to_lead', + ); + expect(publicFormRowOf(formItem({ _packageId: undefined }))?.packageId).toBeNull(); + }); +}); + +describe('publicFormRowsOf', () => { + it('reads `{ items }` or a bare array, drops internal forms and sorts by the name shown', () => { + const b = formItem({ name: 'b_form', label: 'Beta' }); + const a = formItem({ name: 'a_form', label: 'Alpha' }); + const list = formItem({ name: 'all', viewKind: 'list' }); + expect(publicFormRowsOf({ items: [b, list, a] }).map((r) => r.name)).toEqual(['a_form', 'b_form']); + expect(publicFormRowsOf([b, a]).map((r) => r.name)).toEqual(['a_form', 'b_form']); + expect(publicFormRowsOf(undefined)).toEqual([]); + }); +}); + +describe('overrideHoldsOnlySwitch', () => { + const base = formItem(); + it('is true when the override differs from the base only by the switch, its declaration and the decorations', () => { + const override = { ...formItem({}, false), _layer: 'custom', overrides: { package: 'crm', basedOn: '3.0.0' } }; + expect(overrideHoldsOnlySwitch(override, base)).toBe(true); + }); + it('is false when the override also changes the design', () => { + const override = { + ...formItem({ label: 'Talk to us' }, false), + overrides: { package: 'crm', basedOn: '3.0.0' }, + }; + expect(overrideHoldsOnlySwitch(override, base)).toBe(false); + }); +}); + +const listed = (entries: Record) => ({ + listPackages: vi.fn(async () => + new Map(Object.entries(entries).map(([id, e]) => [id, { writable: e.writable, manifest: { id, version: e.version } } as any])), + ), + ensureCustomization: vi.fn(async (base: string) => ({ packageId: `${base}.custom`, writable: true })), +}); + +const clientOf = (layered: (name: string, packageId?: string) => { code?: unknown; effective?: unknown; draft?: unknown }) => ({ + layered: vi.fn(async (_type: string, name: string, options?: { packageId?: string }) => layered(name, options?.packageId)), + save: vi.fn(async () => ({})), + publish: vi.fn(async () => ({})), + reset: vi.fn(async () => ({})), +}); + +const row = { name: 'web_to_lead', packageId: 'crm', object: 'crm_lead' }; +const stripped = (doc: Record) => + Object.fromEntries(Object.entries(doc).filter(([k]) => !k.startsWith('_'))); + +describe('switchPublicForm', () => { + it('saves and publishes the switch in a writable package, changing nothing else', async () => { + const doc = formItem(); + const client = clientOf(() => ({ code: doc, effective: doc })); + const invalidateViewKeys = vi.fn(); + const out = await switchPublicForm(row, false, client, { dataSource: { invalidateViewKeys } as any }, listed({ crm: { writable: true } })); + expect(out).toBe('published'); + expect(client.save).toHaveBeenCalledTimes(1); + const [type, name, body, options] = client.save.mock.calls[0] as unknown as [string, string, any, any]; + expect([type, name]).toEqual(['view', 'web_to_lead']); + expect(options).toMatchObject({ mode: 'draft', ifNoneMatch: '*', packageId: 'crm' }); + expect(body).toEqual({ ...stripped(doc), config: { ...doc.config, sharing: sharing(false) } }); + expect(client.publish).toHaveBeenCalledWith('view', 'web_to_lead', { packageId: 'crm' }); + expect(invalidateViewKeys).toHaveBeenCalledWith('crm_lead', 'web_to_lead'); + }); + + it('switches an installed app\'s form off as an override in its customization package, never in the app', async () => { + const doc = formItem(); + const client = clientOf((_n, pkg) => (pkg === 'crm' ? { code: doc, effective: doc } : { code: null, effective: null })); + const doors = listed({ crm: { writable: false, version: '3.0.0' } }); + const out = await switchPublicForm(row, false, client, {}, doors); + expect(out).toBe('published'); + expect(doors.ensureCustomization).toHaveBeenCalledWith('crm'); + const [, , body, options] = client.save.mock.calls[0] as unknown as [string, string, any, any]; + expect(options).toMatchObject({ packageId: 'crm.custom' }); + expect(body.overrides).toEqual({ package: 'crm', basedOn: '3.0.0' }); + expect(body.config.sharing).toEqual(sharing(false)); + expect(body._packageId).toBeUndefined(); + expect(client.publish).toHaveBeenCalledWith('view', 'web_to_lead', { packageId: 'crm.custom' }); + expect(client.reset).not.toHaveBeenCalled(); + }); + + it('reads the base when the listed pair does not hold the form yet', async () => { + const doc = formItem(); + const client = clientOf((_n, pkg) => (pkg === 'crm' ? { code: doc, effective: doc } : { code: null, effective: null })); + const doors = listed({ crm: { writable: false, version: '3.0.0' }, 'crm.custom': { writable: true, version: '0.0.0' } }); + await switchPublicForm(row, false, client, {}, doors); + expect(client.layered).toHaveBeenNthCalledWith(1, 'view', 'web_to_lead', { packageId: 'crm.custom' }); + expect(client.layered).toHaveBeenNthCalledWith(2, 'view', 'web_to_lead', { packageId: 'crm' }); + const [, , body] = client.save.mock.calls[0] as unknown as [string, string, any]; + expect(body.config.sharing).toEqual(sharing(false)); + }); + + it('switching back on restores the app\'s own form when the override held nothing but the switch', async () => { + const base = formItem(); + const override = { ...stripped(formItem({}, false)), overrides: { package: 'crm', basedOn: '3.0.0' }, _packageId: 'crm.custom' }; + const client = clientOf(() => ({ code: base, effective: override, draft: null })); + const doors = listed({ crm: { writable: false, version: '3.0.0' }, 'crm.custom': { writable: true, version: '0.0.0' } }); + const invalidateViewKeys = vi.fn(); + const out = await switchPublicForm(row, true, client, { dataSource: { invalidateViewKeys } as any }, doors); + expect(out).toBe('restored'); + expect(client.reset).toHaveBeenCalledTimes(1); + expect(client.reset).toHaveBeenCalledWith('view', 'web_to_lead', { packageId: 'crm.custom' }); + expect(client.save).not.toHaveBeenCalled(); + expect(invalidateViewKeys).toHaveBeenCalledWith('crm_lead', 'web_to_lead'); + }); + + it('switching back on keeps an override that also carries design changes, with the switch on', async () => { + const base = formItem(); + const override = { ...stripped(formItem({ label: 'Talk to us' }, false)), overrides: { package: 'crm', basedOn: '2.0.0' } }; + const client = clientOf(() => ({ code: base, effective: override })); + const doors = listed({ crm: { writable: false, version: '3.0.0' }, 'crm.custom': { writable: true, version: '0.0.0' } }); + const out = await switchPublicForm(row, true, client, {}, doors); + expect(out).toBe('published'); + expect(client.reset).not.toHaveBeenCalled(); + const [, , body, options] = client.save.mock.calls[0] as unknown as [string, string, any, any]; + expect(options).toMatchObject({ packageId: 'crm.custom' }); + expect(body.label).toBe('Talk to us'); + expect(body.config.sharing).toEqual(sharing(true)); + // The override keeps the version it declared: re-basing is a person's call. + expect(body.overrides).toEqual({ package: 'crm', basedOn: '2.0.0' }); + }); + + it('writes nothing over a draft pending in the pair: neither the restore nor a save', async () => { + const base = formItem(); + const override = { ...stripped(formItem({}, false)), overrides: { package: 'crm', basedOn: '3.0.0' } }; + const client = clientOf(() => ({ code: base, effective: override, draft: { ...override, label: 'WIP' } })); + const doors = listed({ crm: { writable: false, version: '3.0.0' }, 'crm.custom': { writable: true, version: '0.0.0' } }); + await expect(switchPublicForm(row, true, client, {}, doors)).resolves.toBe('pending-draft'); + expect(client.reset).not.toHaveBeenCalled(); + expect(client.save).not.toHaveBeenCalled(); + }); + + it('answers a pending draft the server refuses the save over, publishing nothing', async () => { + const doc = formItem(); + const client = clientOf(() => ({ code: doc, effective: doc })); + client.save.mockRejectedValueOnce(Object.assign(new Error('conflict'), { status: 409, code: 'METADATA_CONFLICT' })); + await expect(switchPublicForm(row, false, client, {}, listed({ crm: { writable: true } }))).resolves.toBe('pending-draft'); + expect(client.publish).not.toHaveBeenCalled(); + }); + + it('refuses, writing nothing, when the package is not listed, the form cannot be read, or no version can be declared', async () => { + const doc = formItem(); + const ok = clientOf(() => ({ code: doc, effective: doc })); + await expect(switchPublicForm(row, false, ok, {}, listed({}))).rejects.toMatchObject({ + name: 'PublicFormSwitchRefusal', + reason: 'no-package', + }); + + const unreadable = clientOf(() => ({ code: null, effective: null })); + await expect(switchPublicForm(row, false, unreadable, {}, listed({ crm: { writable: true } }))).rejects.toBeInstanceOf( + PublicFormSwitchRefusal, + ); + + const noVersion = listed({ crm: { writable: false } }); + await expect(switchPublicForm(row, false, ok, {}, noVersion)).rejects.toMatchObject({ reason: 'no-version' }); + expect(noVersion.ensureCustomization).not.toHaveBeenCalled(); + for (const c of [ok, unreadable]) expect(c.save).not.toHaveBeenCalled(); + }); + + it('saves a form that names no package where it lives', async () => { + const doc = formItem({ _packageId: undefined }); + const client = clientOf(() => ({ code: doc, effective: doc })); + const out = await switchPublicForm({ ...row, packageId: null }, false, client, {}, listed({})); + expect(out).toBe('published'); + expect(client.layered).toHaveBeenCalledWith('view', 'web_to_lead', {}); + const [, , , options] = client.save.mock.calls[0] as unknown as [string, string, any, any]; + expect(options).toEqual({ mode: 'draft', ifNoneMatch: '*' }); + }); +}); diff --git a/ui/packages/app-shell/src/views/setup/publicForms.ts b/ui/packages/app-shell/src/views/setup/publicForms.ts new file mode 100644 index 00000000000..c377c987882 --- /dev/null +++ b/ui/packages/app-shell/src/views/setup/publicForms.ts @@ -0,0 +1,260 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * Setup → Configuration → Public forms (objectstack#36444): the operations + * half of public forms. Studio designs a public form; Setup lists every public + * form of the environment and switches it on or off, copies its address and + * opens it. + * + * ## Which forms are listed, and which are on + * + * A public form is a form view item whose form the server's one rule + * (`anonymousFormIntakeCandidates`, `@objectstack/spec/ui`) opens to anonymous + * intake. The rule reads three keys of its `sharing`: the switch `enabled`, + * `allowAnonymous` and the `publicLink` slug. This module reads none of them + * itself (the routes and this page must never disagree, objectui#11545): + * + * - a form is ON when the rule opens it as served; + * - a form is LISTED when the rule would open it with its switch on, so a + * switched-off form stays in the list and can be switched back on. A form + * whose author never made it anonymous or gave it no address is an internal + * form, and is not listed. + * + * The list read is the effective one (`GET /meta/view`, ADR-0146 D8): an + * installed app's form switched off in its customization package is served + * switched off, so it lists as off. + * + * ## Where a switch is saved + * + * The switch is the form's `sharing.enabled`, saved and published at once, + * where the console's other in-place edits save (the dashboard editor's + * targets, `runtime-metadata-persistence.ts`): + * + * - a form of a writable package is saved in that package; + * - a form of an installed (read-only) app is saved as this environment's + * customization: an override in the app's `.custom` package (ADR-0146 D2/D3), + * never an edit of the app's own package, so the app upgrades as before. + * Switching such a form back on removes the override when the override held + * nothing but the switch ("Restore package original"), so the app's own form, + * upgrades included, is served again. An override that also carries design + * changes keeps them, with the switch turned on. + * + * A switch is refused, and nothing is written, over a draft already pending + * where it would save: that draft is its saver's and is never published on + * their behalf. + * + * Not listed here: when a form last took a submission. A submission is an + * ordinary record of the form's object and records no form, so there is + * nothing to read. + */ + +import { anonymousFormIntakeCandidates, anonymousFormObjectName } from '@objectstack/spec/ui'; +import { emitMetadataRefresh } from '../../assistant/assistantBus.js'; +import { + resolveDashboardEditTarget, + ensureDashboardSaveTarget, + saveAndPublishInPackage, + saveAndPublishRuntimeMetadata, + type DashboardSaveTargetDoors, + type RuntimePersistCtx, + type SaveAndPublishOutcome, +} from '../runtime-metadata-persistence.js'; +import { declaredOverrideOf, overrideDraftBody } from '../studio-design/StudioCustomizeControls.js'; + +type Doc = Record; + +const isDoc = (v: unknown): v is Doc => !!v && typeof v === 'object' && !Array.isArray(v); + +/** One public form, as the list read serves it. */ +export interface PublicFormRow { + /** The form view item's name: the metadata address every write names. */ + name: string; + /** What the page shows as its name ({@link shownName}). */ + title: string; + /** The object a submission creates a record of. */ + object?: string; + /** The slug of its address (`/forms/`). */ + slug: string; + /** Whether the anonymous routes serve it now. */ + on: boolean; + /** The package that serves the item (`_packageId`), or `null` when it names none. */ + packageId: string | null; +} + +/** `form` with its switch set to `on`: the only key a switch writes. */ +function withSwitch(form: Doc, on: boolean): Doc { + return { ...form, sharing: { ...(isDoc(form.sharing) ? form.sharing : {}), enabled: on } }; +} + +const text = (v: unknown): string | undefined => (typeof v === 'string' && v.trim() ? v : undefined); + +/** + * The name a form is shown by, in the words its author gave it: the served + * (translated) label, else the form's title or label, else the label of its + * first section (what the form's own page heads it with), else its name + * without the object prefix (`crm_lead.web_to_lead` → `web_to_lead`). + */ +function shownName(item: Doc): string { + const config: Doc = isDoc(item.config) ? item.config : {}; + const first = Array.isArray(config.sections) ? config.sections.find(isDoc) : undefined; + const dot = item.name.lastIndexOf('.'); + return ( + text(item.label) ?? + text(config.title) ?? + text(config.label) ?? + text(first?.label) ?? + (dot >= 0 && dot < item.name.length - 1 ? item.name.slice(dot + 1) : item.name) + ); +} + +/** + * The public form a served view item carries, or `null` (module header): a + * `viewKind: 'form'` item whose `config` the rule opens once its switch is on. + * The list serves view ITEMS only, so a form is its item's `config`. + */ +export function publicFormRowOf(item: unknown): PublicFormRow | null { + if (!isDoc(item) || item.viewKind !== 'form' || !isDoc(item.config) || typeof item.name !== 'string') return null; + const switchedOn = anonymousFormIntakeCandidates({ ...item, config: withSwitch(item.config, true) }); + const listed = switchedOn.find((c) => c.key === item.name); + if (!listed) return null; + const on = anonymousFormIntakeCandidates(item).some((c) => c.key === item.name); + const packageId = typeof item._packageId === 'string' && item._packageId ? item._packageId : null; + return { + name: item.name, + title: shownName(item), + object: anonymousFormObjectName(item, item.config), + slug: listed.slug, + on, + packageId, + }; +} + +/** Every public form of a `GET /meta/view` answer (`{ items }`, or a bare array), sorted by name shown. */ +export function publicFormRowsOf(answer: unknown): PublicFormRow[] { + const items: unknown[] = Array.isArray(answer) ? answer : isDoc(answer) && Array.isArray(answer.items) ? answer.items : []; + const rows: PublicFormRow[] = []; + for (const item of items) { + const row = publicFormRowOf(item); + if (row) rows.push(row); + } + return rows.sort((a, b) => a.title.localeCompare(b.title) || a.name.localeCompare(b.name)); +} + +/** The metadata client calls {@link switchPublicForm} makes. */ +export interface PublicFormSwitchClient { + layered( + type: string, + name: string, + options?: { packageId?: string }, + ): Promise<{ code?: unknown; effective?: unknown; draft?: unknown }>; + save(type: string, name: string, body: unknown, options?: Record): Promise; + publish(type: string, name: string, options?: Record): Promise; + reset(type: string, name: string, options?: Record): Promise; +} + +/** What a switch did. */ +export type PublicFormSwitchOutcome = SaveAndPublishOutcome | 'restored'; + +/** A switch the console refuses before writing anything. */ +export class PublicFormSwitchRefusal extends Error { + constructor( + readonly reason: 'no-package' | 'no-version' | 'load-failed', + detail?: string, + ) { + super(detail ?? reason); + this.name = 'PublicFormSwitchRefusal'; + } +} + +/** A document without the read's `_` decorations. */ +function authored(doc: Doc): Doc { + const out: Doc = {}; + for (const [key, value] of Object.entries(doc)) if (!key.startsWith('_')) out[key] = value; + return out; +} + +/** `JSON.stringify` with sorted keys: two documents that say the same thing compare equal. */ +function canonical(value: unknown): string { + return JSON.stringify(value, (_key, v) => + isDoc(v) ? Object.fromEntries(Object.keys(v).sort().map((k) => [k, v[k]])) : v, + ); +} + +/** + * Whether the override `override` of `base`'s form says nothing but the switch: + * the two are the same once the declaration, the read's decorations and the + * switch are set aside. + */ +export function overrideHoldsOnlySwitch(override: Doc, base: Doc): boolean { + const strip = (doc: Doc) => { + const out = authored(doc); + delete out.overrides; + if (isDoc(out.config)) out.config = withSwitch(out.config, true); + return out; + }; + return canonical(strip(override)) === canonical(strip(base)); +} + +/** + * Switch the public form `row` on or off for everyone at once (module header). + * Resolves what was done; rejects with the server's refusal, or with a + * {@link PublicFormSwitchRefusal} when nothing could be written. + */ +export async function switchPublicForm( + row: Pick, + on: boolean, + client: PublicFormSwitchClient, + ctx: Omit, + doors?: DashboardSaveTargetDoors, +): Promise { + const target = await resolveDashboardEditTarget(row.packageId, doors); + if (target.kind === 'refused') throw new PublicFormSwitchRefusal('no-package', target.reason); + const persist: RuntimePersistCtx = { ...ctx, metadataClient: client, objectName: row.object ?? null }; + + // The address the form is read at: its package, the app's pair when the + // package list lists one (it then serves the override, if any, and the + // base's own document as `code`), else the base. + const at = + target.kind === 'unbound' + ? {} + : target.kind === 'package' + ? { packageId: target.packageId } + : { packageId: target.pair ?? target.base }; + let layers: { code?: unknown; effective?: unknown; draft?: unknown }; + try { + layers = await client.layered('view', row.name, at); + // A listed pair that does not hold the form yet holds nothing: its base's document is read. + if (target.kind === 'customization' && target.pair && !isDoc(layers.effective) && !isDoc(layers.code)) { + layers = await client.layered('view', row.name, { packageId: target.base }); + } + } catch (err) { + throw new PublicFormSwitchRefusal('load-failed', err instanceof Error ? err.message : String(err)); + } + const effective = isDoc(layers.effective) ? layers.effective : isDoc(layers.code) ? layers.code : null; + if (!effective || !isDoc(effective.config)) throw new PublicFormSwitchRefusal('load-failed', row.name); + const switched = { ...authored(effective), config: withSwitch(effective.config, on) }; + + if (target.kind === 'unbound') return saveAndPublishRuntimeMetadata('view', row.name, switched, persist); + if (target.kind === 'package') return saveAndPublishInPackage('view', row.name, switched, target.packageId, persist); + + // An installed app: this environment's customization, in the app's pair. + const override = declaredOverrideOf(effective, target.base) ? effective : null; + const base = isDoc(layers.code) ? layers.code : null; + if (on && override && base && isDoc(base.config)) { + const baseOn = anonymousFormIntakeCandidates(base).some((c) => c.key === row.name); + if (baseOn && overrideHoldsOnlySwitch(override, base) && target.pair) { + // A draft pending over the override is its saver's: nothing is removed under it. + if (isDoc(layers.draft)) return 'pending-draft'; + // "Restore package original": the pair's row of the form is removed. + await client.reset('view', row.name, { packageId: target.pair }); + if (row.object) persist.dataSource?.invalidateViewKeys?.(row.object, row.name); + emitMetadataRefresh(); + return 'restored'; + } + } + const body = overrideDraftBody(switched, target.base, target.basedOn); + if (body === null) throw new PublicFormSwitchRefusal('no-version', target.base); + const saveTarget = await ensureDashboardSaveTarget(target, doors); + if (saveTarget.kind !== 'customization') throw new PublicFormSwitchRefusal('no-package', target.base); + return saveAndPublishInPackage('view', row.name, body, saveTarget.packageId, persist); +} diff --git a/ui/packages/app-shell/src/views/setup/publicFormsRef.ts b/ui/packages/app-shell/src/views/setup/publicFormsRef.ts new file mode 100644 index 00000000000..289c89fe6d3 --- /dev/null +++ b/ui/packages/app-shell/src/views/setup/publicFormsRef.ts @@ -0,0 +1,25 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * Setup → Configuration → Public forms (objectstack#36444): the page's ref, + * kept apart from `publicForms.ts` so the eager registry (`builtinComponents`) + * imports a constant, never the page's writers. + * + * The entry that opens the page is a Setup navigation contribution + * (`@objectstack/platform-objects`, `group_configuration`); this ref is what + * that entry names, and its `requiredPermissions` is + * {@link PUBLIC_FORMS_CAPABILITY}. + */ + +import { componentRefToUrlSegments } from '../../services/componentRegistry.js'; + +/** The component ref of the Setup page. */ +export const PUBLIC_FORMS_REF = 'forms:public-forms'; + +/** The capability the page and its Setup entry ask: a system administrator's. */ +export const PUBLIC_FORMS_CAPABILITY = 'manage_platform_settings'; + +/** Where the page opens inside the Setup app. */ +export function publicFormsPagePath(): string { + return `/apps/setup/component/${componentRefToUrlSegments(PUBLIC_FORMS_REF).join('/')}`; +} diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index dadee092e52..f584f6c6a28 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -6524,6 +6524,36 @@ const ar = { linkedAt: "تم الربط {{at}}", disconnect: "إلغاء الربط", }, + publicFormsSetup: { + title: "النماذج العامة", + subtitle: "نماذج يمكن لأي شخص تعبئتها دون تسجيل الدخول، مثل نموذج الاتصال على موقعك. يصبح كل إرسال سجلًا.", + notAllowed: "يمكن لمسؤولي النظام فقط إدارة النماذج العامة.", + designHint: "أوقف تشغيل نموذج للتوقف عن تلقي الإرسالات؛ عندها لن يفتح عنوانه شيئًا. تُصمَّم النماذج في Studio.", + refresh: "تحديث", + emptyTitle: "لا توجد نماذج عامة بعد", + emptyBody: "تُصمَّم النماذج العامة في Studio. عندما يحتوي تطبيق على نموذج عام، يظهر هنا.", + loadFailed: "تعذّر تحميل النماذج العامة: {{message}}", + columnName: "الاسم", + columnObject: "ينشئ سجلًا في", + columnAddress: "العنوان", + columnStatus: "الحالة", + columnActions: "الإجراءات", + on: "مُشغَّل", + off: "متوقف", + switchOnLabel: "تشغيل {{name}}", + switchOffLabel: "إيقاف {{name}}", + copy: "نسخ العنوان", + copied: "تم نسخ العنوان", + clipboardUnavailable: "الحافظة غير متاحة", + open: "فتح في علامة تبويب جديدة", + switchedOn: "{{name}} مُشغَّل: يمكن للزوار تعبئته.", + switchedOff: "{{name}} متوقف: لم يعد عنوانه يفتح.", + pendingDraft: "لدى {{name}} تغييرات غير منشورة في Studio. انشرها أو تجاهلها هناك أولًا.", + switchFailed: "تعذّر تبديل {{name}}: {{message}}", + refusalNoPackage: "تعذّر العثور على التطبيق الذي ينتمي إليه هذا النموذج.", + refusalNoVersion: "التطبيق الذي ينتمي إليه هذا النموذج لا يعلن عن إصدار، لذا لا يمكن حفظ التخصيص.", + refusalLoadFailed: "تعذّرت قراءة النموذج.", + }, slackSetup: { title: "رسائل Slack المباشرة", subtitle: "ثبّت تطبيق Slack الخاص بمؤسستك لتصل الإشعارات إلى الأشخاص كرسائل Slack مباشرة، وأدِر من هم مرتبطون.", diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index 937e9e96f75..008e3cf1ec6 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -5873,6 +5873,36 @@ const de = { linkedAt: "Verbunden {{at}}", disconnect: "Trennen", }, + publicFormsSetup: { + title: "Öffentliche Formulare", + subtitle: "Formulare, die jeder ohne Anmeldung ausfüllen kann, etwa ein Kontaktformular auf Ihrer Website. Jede Übermittlung wird zu einem Datensatz.", + notAllowed: "Nur Systemadministratoren können öffentliche Formulare verwalten.", + designHint: "Schalten Sie ein Formular aus, um keine Übermittlungen mehr anzunehmen; seine Adresse öffnet dann nichts mehr. Formulare werden in Studio gestaltet.", + refresh: "Aktualisieren", + emptyTitle: "Noch keine öffentlichen Formulare", + emptyBody: "Öffentliche Formulare werden in Studio gestaltet. Sobald eine App eines hat, wird es hier aufgeführt.", + loadFailed: "Die öffentlichen Formulare konnten nicht geladen werden: {{message}}", + columnName: "Name", + columnObject: "Erstellt einen Datensatz von", + columnAddress: "Adresse", + columnStatus: "Status", + columnActions: "Aktionen", + on: "Ein", + off: "Aus", + switchOnLabel: "{{name}} einschalten", + switchOffLabel: "{{name}} ausschalten", + copy: "Adresse kopieren", + copied: "Adresse kopiert", + clipboardUnavailable: "Zwischenablage nicht verfügbar", + open: "In neuem Tab öffnen", + switchedOn: "{{name}} ist eingeschaltet: Besucher können es ausfüllen.", + switchedOff: "{{name}} ist ausgeschaltet: Seine Adresse öffnet nichts mehr.", + pendingDraft: "{{name}} hat unveröffentlichte Änderungen in Studio. Veröffentlichen oder verwerfen Sie sie dort zuerst.", + switchFailed: "{{name}} konnte nicht umgeschaltet werden: {{message}}", + refusalNoPackage: "die App, zu der dieses Formular gehört, wurde nicht gefunden.", + refusalNoVersion: "die App, zu der dieses Formular gehört, gibt keine Version an, daher kann die Anpassung nicht gespeichert werden.", + refusalLoadFailed: "das Formular konnte nicht gelesen werden.", + }, slackSetup: { title: "Slack-Direktnachrichten", subtitle: "Installieren Sie die Slack-App Ihrer Organisation, damit Benachrichtigungen Personen als Slack-Direktnachrichten erreichen, und verwalten Sie, wer verbunden ist.", diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index 41934b72b7a..a2f9e6d4b22 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -6807,6 +6807,36 @@ const en = { linkedAt: "Connected {{at}}", disconnect: "Disconnect", }, + publicFormsSetup: { + title: "Public forms", + subtitle: "Forms anyone can fill in without signing in, such as a contact form on your website. Each submission becomes a record.", + notAllowed: "Only system administrators can manage public forms.", + designHint: "Switch a form off to stop taking submissions; its address then opens nothing. Forms are designed in Studio.", + refresh: "Refresh", + emptyTitle: "No public forms yet", + emptyBody: "Public forms are designed in Studio. Once an app has one, it is listed here.", + loadFailed: "Couldn't load the public forms: {{message}}", + columnName: "Name", + columnObject: "Creates a record of", + columnAddress: "Address", + columnStatus: "Status", + columnActions: "Actions", + on: "On", + off: "Off", + switchOnLabel: "Switch {{name}} on", + switchOffLabel: "Switch {{name}} off", + copy: "Copy address", + copied: "Address copied", + clipboardUnavailable: "Clipboard unavailable", + open: "Open in a new tab", + switchedOn: "{{name}} is on: visitors can fill it in.", + switchedOff: "{{name}} is off: its address no longer opens.", + pendingDraft: "{{name}} has unpublished changes in Studio. Publish or discard them there first.", + switchFailed: "Couldn't switch {{name}}: {{message}}", + refusalNoPackage: "the app this form belongs to could not be found.", + refusalNoVersion: "the app this form belongs to declares no version, so its customization cannot be saved.", + refusalLoadFailed: "the form could not be read.", + }, slackSetup: { title: "Slack direct messages", subtitle: "Install your organization's Slack app so notifications reach people as Slack direct messages, and manage who is connected.", diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index af8de32d7ec..992440c3649 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -6035,6 +6035,36 @@ const es = { linkedAt: "Conectado {{at}}", disconnect: "Desconectar", }, + publicFormsSetup: { + title: "Formularios públicos", + subtitle: "Formularios que cualquiera puede rellenar sin iniciar sesión, como un formulario de contacto en su sitio web. Cada envío se convierte en un registro.", + notAllowed: "Solo los administradores del sistema pueden gestionar los formularios públicos.", + designHint: "Desactive un formulario para dejar de recibir envíos; su dirección ya no abrirá nada. Los formularios se diseñan en Studio.", + refresh: "Actualizar", + emptyTitle: "Aún no hay formularios públicos", + emptyBody: "Los formularios públicos se diseñan en Studio. Cuando una aplicación tenga uno, aparecerá aquí.", + loadFailed: "No se pudieron cargar los formularios públicos: {{message}}", + columnName: "Nombre", + columnObject: "Crea un registro de", + columnAddress: "Dirección", + columnStatus: "Estado", + columnActions: "Acciones", + on: "Activado", + off: "Desactivado", + switchOnLabel: "Activar {{name}}", + switchOffLabel: "Desactivar {{name}}", + copy: "Copiar dirección", + copied: "Dirección copiada", + clipboardUnavailable: "Portapapeles no disponible", + open: "Abrir en una pestaña nueva", + switchedOn: "{{name}} está activado: los visitantes pueden rellenarlo.", + switchedOff: "{{name}} está desactivado: su dirección ya no se abre.", + pendingDraft: "{{name}} tiene cambios sin publicar en Studio. Publíquelos o descártelos allí primero.", + switchFailed: "No se pudo cambiar {{name}}: {{message}}", + refusalNoPackage: "no se encontró la aplicación a la que pertenece este formulario.", + refusalNoVersion: "la aplicación a la que pertenece este formulario no declara versión, así que no se puede guardar la personalización.", + refusalLoadFailed: "no se pudo leer el formulario.", + }, slackSetup: { title: "Mensajes directos de Slack", subtitle: "Instale la aplicación de Slack de su organización para que las notificaciones lleguen a las personas como mensajes directos de Slack, y gestione quién está conectado.", diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index 4f7ee4f0cf9..1f21f417532 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -6031,6 +6031,36 @@ const fr = { linkedAt: "Connecté {{at}}", disconnect: "Déconnecter", }, + publicFormsSetup: { + title: "Formulaires publics", + subtitle: "Formulaires que chacun peut remplir sans se connecter, comme un formulaire de contact sur votre site web. Chaque envoi devient un enregistrement.", + notAllowed: "Seuls les administrateurs système peuvent gérer les formulaires publics.", + designHint: "Désactivez un formulaire pour ne plus recevoir d'envois ; son adresse n'ouvre alors plus rien. Les formulaires se conçoivent dans Studio.", + refresh: "Actualiser", + emptyTitle: "Aucun formulaire public pour l'instant", + emptyBody: "Les formulaires publics se conçoivent dans Studio. Dès qu'une application en a un, il apparaît ici.", + loadFailed: "Impossible de charger les formulaires publics : {{message}}", + columnName: "Nom", + columnObject: "Crée un enregistrement de", + columnAddress: "Adresse", + columnStatus: "Statut", + columnActions: "Actions", + on: "Activé", + off: "Désactivé", + switchOnLabel: "Activer {{name}}", + switchOffLabel: "Désactiver {{name}}", + copy: "Copier l'adresse", + copied: "Adresse copiée", + clipboardUnavailable: "Presse-papiers indisponible", + open: "Ouvrir dans un nouvel onglet", + switchedOn: "{{name}} est activé : les visiteurs peuvent le remplir.", + switchedOff: "{{name}} est désactivé : son adresse ne s'ouvre plus.", + pendingDraft: "{{name}} a des modifications non publiées dans Studio. Publiez-les ou abandonnez-les d'abord.", + switchFailed: "Impossible de basculer {{name}} : {{message}}", + refusalNoPackage: "l'application à laquelle appartient ce formulaire est introuvable.", + refusalNoVersion: "l'application à laquelle appartient ce formulaire ne déclare aucune version : la personnalisation ne peut pas être enregistrée.", + refusalLoadFailed: "le formulaire n'a pas pu être lu.", + }, slackSetup: { title: "Messages directs Slack", subtitle: "Installez l’application Slack de votre organisation pour que les notifications parviennent aux personnes en messages directs Slack, et gérez qui est connecté.", diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index e40dccd1dc8..88ef7c74831 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -5874,6 +5874,36 @@ const ja = { linkedAt: "連携日時 {{at}}", disconnect: "連携を解除", }, + publicFormsSetup: { + title: "公開フォーム", + subtitle: "サインインせずに誰でも入力できるフォーム(Web サイトのお問い合わせフォームなど)。送信ごとにレコードが作成されます。", + notAllowed: "公開フォームを管理できるのはシステム管理者のみです。", + designHint: "フォームをオフにすると送信を受け付けなくなり、そのアドレスは開けなくなります。フォームの設計は Studio で行います。", + refresh: "更新", + emptyTitle: "公開フォームはまだありません", + emptyBody: "公開フォームは Studio で設計します。アプリに公開フォームがあると、ここに表示されます。", + loadFailed: "公開フォームを読み込めませんでした: {{message}}", + columnName: "名前", + columnObject: "作成されるレコード", + columnAddress: "アドレス", + columnStatus: "状態", + columnActions: "操作", + on: "オン", + off: "オフ", + switchOnLabel: "{{name}} をオンにする", + switchOffLabel: "{{name}} をオフにする", + copy: "アドレスをコピー", + copied: "アドレスをコピーしました", + clipboardUnavailable: "クリップボードを使用できません", + open: "新しいタブで開く", + switchedOn: "{{name}} をオンにしました。訪問者が入力できます。", + switchedOff: "{{name}} をオフにしました。アドレスは開けなくなります。", + pendingDraft: "{{name}} には Studio で未公開の変更があります。先に Studio で公開するか破棄してください。", + switchFailed: "{{name}} を切り替えられませんでした: {{message}}", + refusalNoPackage: "このフォームが属するアプリが見つかりません。", + refusalNoVersion: "このフォームが属するアプリはバージョンを宣言していないため、カスタマイズを保存できません。", + refusalLoadFailed: "フォームを読み込めませんでした。", + }, slackSetup: { title: "Slack のダイレクトメッセージ", subtitle: "組織の Slack アプリをインストールして通知を Slack のダイレクトメッセージで届け、連携しているユーザーを管理します。", diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index 31da75274af..2f3b5abb6ba 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -5871,6 +5871,36 @@ const ko = { linkedAt: "연결 시각 {{at}}", disconnect: "연결 해제", }, + publicFormsSetup: { + title: "공개 양식", + subtitle: "로그인하지 않고 누구나 작성할 수 있는 양식(예: 웹사이트의 문의 양식). 제출할 때마다 레코드가 생성됩니다.", + notAllowed: "시스템 관리자만 공개 양식을 관리할 수 있습니다.", + designHint: "양식을 끄면 더 이상 제출을 받지 않으며 해당 주소도 열리지 않습니다. 양식 디자인은 Studio에서 합니다.", + refresh: "새로 고침", + emptyTitle: "아직 공개 양식이 없습니다", + emptyBody: "공개 양식은 Studio에서 디자인합니다. 앱에 공개 양식이 있으면 여기에 표시됩니다.", + loadFailed: "공개 양식을 불러오지 못했습니다: {{message}}", + columnName: "이름", + columnObject: "생성되는 레코드", + columnAddress: "주소", + columnStatus: "상태", + columnActions: "작업", + on: "켜짐", + off: "꺼짐", + switchOnLabel: "{{name}} 켜기", + switchOffLabel: "{{name}} 끄기", + copy: "주소 복사", + copied: "주소를 복사했습니다", + clipboardUnavailable: "클립보드를 사용할 수 없습니다", + open: "새 탭에서 열기", + switchedOn: "{{name}}을(를) 켰습니다. 방문자가 작성할 수 있습니다.", + switchedOff: "{{name}}을(를) 껐습니다. 주소가 더 이상 열리지 않습니다.", + pendingDraft: "{{name}}에 Studio에서 게시하지 않은 변경 사항이 있습니다. 먼저 그곳에서 게시하거나 취소하세요.", + switchFailed: "{{name}}을(를) 전환하지 못했습니다: {{message}}", + refusalNoPackage: "이 양식이 속한 앱을 찾을 수 없습니다.", + refusalNoVersion: "이 양식이 속한 앱이 버전을 선언하지 않아 사용자 지정을 저장할 수 없습니다.", + refusalLoadFailed: "양식을 읽지 못했습니다.", + }, slackSetup: { title: "Slack 다이렉트 메시지", subtitle: "조직의 Slack 앱을 설치하여 알림이 Slack 다이렉트 메시지로 전달되도록 하고, 연결된 사용자를 관리합니다.", diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index ecc9f0ee6e1..a4fc25fc5dc 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -6030,6 +6030,36 @@ const pt = { linkedAt: "Conectado {{at}}", disconnect: "Desconectar", }, + publicFormsSetup: { + title: "Formulários públicos", + subtitle: "Formulários que qualquer pessoa pode preencher sem entrar, como um formulário de contato no seu site. Cada envio vira um registro.", + notAllowed: "Somente administradores do sistema podem gerenciar formulários públicos.", + designHint: "Desative um formulário para parar de receber envios; o endereço dele deixa de abrir. Os formulários são criados no Studio.", + refresh: "Atualizar", + emptyTitle: "Ainda não há formulários públicos", + emptyBody: "Os formulários públicos são criados no Studio. Quando um aplicativo tiver um, ele aparecerá aqui.", + loadFailed: "Não foi possível carregar os formulários públicos: {{message}}", + columnName: "Nome", + columnObject: "Cria um registro de", + columnAddress: "Endereço", + columnStatus: "Status", + columnActions: "Ações", + on: "Ativado", + off: "Desativado", + switchOnLabel: "Ativar {{name}}", + switchOffLabel: "Desativar {{name}}", + copy: "Copiar endereço", + copied: "Endereço copiado", + clipboardUnavailable: "Área de transferência indisponível", + open: "Abrir em uma nova guia", + switchedOn: "{{name}} está ativado: os visitantes podem preenchê-lo.", + switchedOff: "{{name}} está desativado: o endereço não abre mais.", + pendingDraft: "{{name}} tem alterações não publicadas no Studio. Publique ou descarte-as lá primeiro.", + switchFailed: "Não foi possível alternar {{name}}: {{message}}", + refusalNoPackage: "o aplicativo ao qual este formulário pertence não foi encontrado.", + refusalNoVersion: "o aplicativo ao qual este formulário pertence não declara versão, então a personalização não pode ser salva.", + refusalLoadFailed: "não foi possível ler o formulário.", + }, slackSetup: { title: "Mensagens diretas do Slack", subtitle: "Instale o aplicativo do Slack da sua organização para que as notificações cheguem às pessoas como mensagens diretas do Slack, e gerencie quem está conectado.", diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index 21a26bae268..5cd5c27b647 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -6206,6 +6206,36 @@ const ru = { linkedAt: "Подключено {{at}}", disconnect: "Отключить", }, + publicFormsSetup: { + title: "Публичные формы", + subtitle: "Формы, которые любой может заполнить без входа, например форма обратной связи на вашем сайте. Каждая отправка создаёт запись.", + notAllowed: "Управлять публичными формами могут только системные администраторы.", + designHint: "Выключите форму, чтобы перестать принимать отправки; её адрес перестанет открываться. Формы проектируются в Studio.", + refresh: "Обновить", + emptyTitle: "Публичных форм пока нет", + emptyBody: "Публичные формы проектируются в Studio. Как только в приложении появится такая форма, она будет показана здесь.", + loadFailed: "Не удалось загрузить публичные формы: {{message}}", + columnName: "Название", + columnObject: "Создаёт запись в", + columnAddress: "Адрес", + columnStatus: "Состояние", + columnActions: "Действия", + on: "Вкл.", + off: "Выкл.", + switchOnLabel: "Включить {{name}}", + switchOffLabel: "Выключить {{name}}", + copy: "Копировать адрес", + copied: "Адрес скопирован", + clipboardUnavailable: "Буфер обмена недоступен", + open: "Открыть в новой вкладке", + switchedOn: "{{name}} включена: посетители могут её заполнить.", + switchedOff: "{{name}} выключена: её адрес больше не открывается.", + pendingDraft: "В {{name}} есть неопубликованные изменения в Studio. Сначала опубликуйте или отмените их там.", + switchFailed: "Не удалось переключить {{name}}: {{message}}", + refusalNoPackage: "приложение, к которому относится форма, не найдено.", + refusalNoVersion: "приложение, к которому относится форма, не объявляет версию, поэтому настройку нельзя сохранить.", + refusalLoadFailed: "не удалось прочитать форму.", + }, slackSetup: { title: "Личные сообщения в Slack", subtitle: "Установите приложение Slack вашей организации, чтобы уведомления доходили до людей личными сообщениями в Slack, и управляйте тем, кто подключён.", diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index c6fbdc36957..d69e01454ae 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -5932,6 +5932,36 @@ const zh = { linkedAt: "关联于 {{at}}", disconnect: "解除关联", }, + publicFormsSetup: { + title: "对外表单", + subtitle: "访客不用登录就能填写的表单,比如网站上的「联系我们」。每提交一次就新增一条记录。", + notAllowed: "只有系统管理员可以管理对外表单。", + designHint: "关掉一个表单就不再接收提交,它的地址也打不开了。表单的设计在 Studio 里做。", + refresh: "刷新", + emptyTitle: "还没有对外表单", + emptyBody: "对外表单在 Studio 里设计。应用里有了对外表单,就会列在这里。", + loadFailed: "对外表单加载失败:{{message}}", + columnName: "名称", + columnObject: "提交后新增", + columnAddress: "地址", + columnStatus: "状态", + columnActions: "操作", + on: "开", + off: "关", + switchOnLabel: "打开 {{name}}", + switchOffLabel: "关闭 {{name}}", + copy: "复制地址", + copied: "地址已复制", + clipboardUnavailable: "无法使用剪贴板", + open: "在新标签页打开", + switchedOn: "{{name}} 已打开:访客可以填写。", + switchedOff: "{{name}} 已关闭:地址不再能打开。", + pendingDraft: "{{name}} 在 Studio 里有未发布的修改,请先在那里发布或放弃。", + switchFailed: "无法切换 {{name}}:{{message}}", + refusalNoPackage: "找不到这个表单所属的应用。", + refusalNoVersion: "这个表单所属的应用没有声明版本,无法保存本环境的定制。", + refusalLoadFailed: "读取表单失败。", + }, slackSetup: { title: "Slack 私信", subtitle: "安装组织自己的 Slack 应用,让通知以 Slack 私信送达成员,并管理已关联的人员。", diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index cff81f25653..3fc378985eb 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -5932,6 +5932,36 @@ const zhHant = { linkedAt: "關聯於 {{at}}", disconnect: "解除關聯", }, + publicFormsSetup: { + title: "對外表單", + subtitle: "訪客不用登入就能填寫的表單,例如網站上的「聯絡我們」。每提交一次就新增一筆記錄。", + notAllowed: "只有系統管理員可以管理對外表單。", + designHint: "關閉一個表單就不再接收提交,它的網址也打不開了。表單的設計在 Studio 裡進行。", + refresh: "重新整理", + emptyTitle: "還沒有對外表單", + emptyBody: "對外表單在 Studio 裡設計。應用程式中有了對外表單,就會列在這裡。", + loadFailed: "對外表單載入失敗:{{message}}", + columnName: "名稱", + columnObject: "提交後新增", + columnAddress: "網址", + columnStatus: "狀態", + columnActions: "操作", + on: "開", + off: "關", + switchOnLabel: "開啟 {{name}}", + switchOffLabel: "關閉 {{name}}", + copy: "複製網址", + copied: "網址已複製", + clipboardUnavailable: "無法使用剪貼簿", + open: "在新分頁開啟", + switchedOn: "{{name}} 已開啟:訪客可以填寫。", + switchedOff: "{{name}} 已關閉:網址不再能開啟。", + pendingDraft: "{{name}} 在 Studio 裡有未發布的修改,請先在那裡發布或捨棄。", + switchFailed: "無法切換 {{name}}:{{message}}", + refusalNoPackage: "找不到這個表單所屬的應用程式。", + refusalNoVersion: "這個表單所屬的應用程式沒有宣告版本,無法儲存本環境的自訂。", + refusalLoadFailed: "讀取表單失敗。", + }, slackSetup: { title: "Slack 私信", subtitle: "安裝組織自己的 Slack 應用,讓通知以 Slack 私信送達成員,並管理已關聯的人員。", From d3b3b09d3360ebe51212024ded700c17370acd2b Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 13:26:25 +0000 Subject: [PATCH 2/6] fix(setup): name the public forms page's local document type apart from the spec's, and classify its object-list read The Type Check UI job's spec-symbol guard refuses a local `Doc` because `@objectstack/spec/system` exports one; the page module's type is now `FormDoc`. The census of `useMetadata().objects` readers lists the new Setup page as `off` (not mounted on an app's object-list open). Claude-Session: https://claude.ai/code/session_01JQwxbWoxCrkYwcqxxENvmn Co-authored-by: Claude --- .../openPathObjectReaders-12811.test.ts | 1 + .../app-shell/src/views/setup/publicForms.ts | 18 +++++++++--------- 2 files changed, 10 insertions(+), 9 deletions(-) diff --git a/ui/packages/app-shell/src/console/__tests__/openPathObjectReaders-12811.test.ts b/ui/packages/app-shell/src/console/__tests__/openPathObjectReaders-12811.test.ts index f39f650b07c..fef866e0d03 100644 --- a/ui/packages/app-shell/src/console/__tests__/openPathObjectReaders-12811.test.ts +++ b/ui/packages/app-shell/src/console/__tests__/openPathObjectReaders-12811.test.ts @@ -121,6 +121,7 @@ const OBJECTS_READERS: Record = { 'packages/app-shell/src/views/metadata-admin/PositionHoldersSection.tsx': { kind: 'off', why: 'the metadata admin' }, 'packages/app-shell/src/views/metadata-admin/AssignedUsersSection.tsx': { kind: 'off', why: 'the metadata admin' }, 'packages/app-shell/src/views/setup/RecycleBinPage.tsx': { kind: 'off', why: 'Setup → Recycle Bin, not mounted on an app object-list open' }, + 'packages/app-shell/src/views/setup/PublicFormsSetupPage.tsx': { kind: 'off', why: 'Setup → Public forms, not mounted on an app object-list open (objectstack#36444)' }, 'packages/app-shell/src/views/metadata-admin/previews/ScreenPreview.tsx': { kind: 'off', why: "the metadata admin's form-screen preview" }, 'packages/app-shell/src/views/studio-design/ObjectListViewInspector.tsx': { kind: 'off', why: 'Studio' }, 'packages/app-shell/src/views/studio-design/ObjectListViewTitle.tsx': { diff --git a/ui/packages/app-shell/src/views/setup/publicForms.ts b/ui/packages/app-shell/src/views/setup/publicForms.ts index c377c987882..548e055da47 100644 --- a/ui/packages/app-shell/src/views/setup/publicForms.ts +++ b/ui/packages/app-shell/src/views/setup/publicForms.ts @@ -61,9 +61,9 @@ import { } from '../runtime-metadata-persistence.js'; import { declaredOverrideOf, overrideDraftBody } from '../studio-design/StudioCustomizeControls.js'; -type Doc = Record; +type FormDoc = Record; -const isDoc = (v: unknown): v is Doc => !!v && typeof v === 'object' && !Array.isArray(v); +const isDoc = (v: unknown): v is FormDoc => !!v && typeof v === 'object' && !Array.isArray(v); /** One public form, as the list read serves it. */ export interface PublicFormRow { @@ -82,7 +82,7 @@ export interface PublicFormRow { } /** `form` with its switch set to `on`: the only key a switch writes. */ -function withSwitch(form: Doc, on: boolean): Doc { +function withSwitch(form: FormDoc, on: boolean): FormDoc { return { ...form, sharing: { ...(isDoc(form.sharing) ? form.sharing : {}), enabled: on } }; } @@ -94,8 +94,8 @@ const text = (v: unknown): string | undefined => (typeof v === 'string' && v.tri * first section (what the form's own page heads it with), else its name * without the object prefix (`crm_lead.web_to_lead` → `web_to_lead`). */ -function shownName(item: Doc): string { - const config: Doc = isDoc(item.config) ? item.config : {}; +function shownName(item: FormDoc): string { + const config: FormDoc = isDoc(item.config) ? item.config : {}; const first = Array.isArray(config.sections) ? config.sections.find(isDoc) : undefined; const dot = item.name.lastIndexOf('.'); return ( @@ -167,8 +167,8 @@ export class PublicFormSwitchRefusal extends Error { } /** A document without the read's `_` decorations. */ -function authored(doc: Doc): Doc { - const out: Doc = {}; +function authored(doc: FormDoc): FormDoc { + const out: FormDoc = {}; for (const [key, value] of Object.entries(doc)) if (!key.startsWith('_')) out[key] = value; return out; } @@ -185,8 +185,8 @@ function canonical(value: unknown): string { * the two are the same once the declaration, the read's decorations and the * switch are set aside. */ -export function overrideHoldsOnlySwitch(override: Doc, base: Doc): boolean { - const strip = (doc: Doc) => { +export function overrideHoldsOnlySwitch(override: FormDoc, base: FormDoc): boolean { + const strip = (doc: FormDoc) => { const out = authored(doc); delete out.overrides; if (isDoc(out.config)) out.config = withSwitch(out.config, true); From 5c7d00942690fe609de170e79539b43f3697e934 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 17:01:03 +0000 Subject: [PATCH 3/6] chore(i18n): regenerate the Traditional Chinese locale for the public forms page The zh-Hant locale is generated from zh; the publicFormsSetup block added to zh had not been carried over, so zh-hant-generated.test.ts flagged the file as stale. Claude-Session: https://claude.ai/code/session_01JQwxbWoxCrkYwcqxxENvmn Co-authored-by: Claude --- ui/packages/i18n/src/locales/zh-Hant.ts | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index 52ab20ca9af..41dc08c7281 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -5958,32 +5958,32 @@ const zhHant = { }, publicFormsSetup: { title: "對外表單", - subtitle: "訪客不用登入就能填寫的表單,例如網站上的「聯絡我們」。每提交一次就新增一筆記錄。", + subtitle: "訪客不用登入就能填寫的表單,比如網站上的「聯絡我們」。每提交一次就新增一條記錄。", notAllowed: "只有系統管理員可以管理對外表單。", - designHint: "關閉一個表單就不再接收提交,它的網址也打不開了。表單的設計在 Studio 裡進行。", + designHint: "關掉一個表單就不再接收提交,它的地址也打不開了。表單的設計在 Studio 裡做。", refresh: "重新整理", emptyTitle: "還沒有對外表單", - emptyBody: "對外表單在 Studio 裡設計。應用程式中有了對外表單,就會列在這裡。", + emptyBody: "對外表單在 Studio 裡設計。應用裡有了對外表單,就會列在這裡。", loadFailed: "對外表單載入失敗:{{message}}", columnName: "名稱", columnObject: "提交後新增", - columnAddress: "網址", + columnAddress: "地址", columnStatus: "狀態", columnActions: "操作", on: "開", off: "關", switchOnLabel: "開啟 {{name}}", switchOffLabel: "關閉 {{name}}", - copy: "複製網址", - copied: "網址已複製", + copy: "複製地址", + copied: "地址已複製", clipboardUnavailable: "無法使用剪貼簿", - open: "在新分頁開啟", + open: "在新標籤頁開啟", switchedOn: "{{name}} 已開啟:訪客可以填寫。", - switchedOff: "{{name}} 已關閉:網址不再能開啟。", - pendingDraft: "{{name}} 在 Studio 裡有未發布的修改,請先在那裡發布或捨棄。", + switchedOff: "{{name}} 已關閉:地址不再能開啟。", + pendingDraft: "{{name}} 在 Studio 裡有未釋出的修改,請先在那裡釋出或放棄。", switchFailed: "無法切換 {{name}}:{{message}}", - refusalNoPackage: "找不到這個表單所屬的應用程式。", - refusalNoVersion: "這個表單所屬的應用程式沒有宣告版本,無法儲存本環境的自訂。", + refusalNoPackage: "找不到這個表單所屬的應用。", + refusalNoVersion: "這個表單所屬的應用沒有宣告版本,無法儲存本環境的定製。", refusalLoadFailed: "讀取表單失敗。", }, slackSetup: { From 8902d697eea2ccb871387f91ba48422d5735ebc5 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 17:43:30 +0000 Subject: [PATCH 4/6] chore(changeset): declare the public forms page's new ids and language keys as a widening MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The page adds a Setup navigation id, a component id and new language-pack keys, which this lane counts as Clause-② yes (widening). Claude-Session: https://claude.ai/code/session_01JQwxbWoxCrkYwcqxxENvmn Co-authored-by: Claude --- .changeset/36444-setup-public-forms.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/36444-setup-public-forms.md b/.changeset/36444-setup-public-forms.md index dbfbea7ffd2..fb17b3ad875 100644 --- a/.changeset/36444-setup-public-forms.md +++ b/.changeset/36444-setup-public-forms.md @@ -6,7 +6,7 @@ feat(setup): Setup → Configuration → Public forms lists every public form of the environment and switches it on or off -Clause-②: no +Clause-②: yes (widening) — a new Setup navigation id `nav_public_forms`, a new component id `forms:public-forms`, and new language-pack keys (the `publicFormsSetup` block and the nav label) in every shipped locale Metadata-protocol: none A system administrator (`manage_platform_settings`, the capability the Setup entry asks) now has one page for the operations side of public forms. It lists every public form of the environment: its name, the object a submission creates a record of, its address, and whether it is on. Per row: switch it on or off, copy its address, or open it in a new tab. A form is designed (created, deleted, its fields and title changed) in Studio, not here. From d91c73bcad5eb93ae30c7f16ebf60ec77adbd562 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 19:10:08 +0000 Subject: [PATCH 5/6] fix(setup): a public form its app ships switched off is never shown or switched on; say when a form stays on an earlier app version An installed app's form shipped with its switch off is withdrawn by the app's own document, which the anonymous routes never let an override re-open. The page now lists it as switched off by its app, with its switch disabled even when an override already switches it on, and a switch-on writes nothing and says why. Switching back on an override taken from an earlier app version still restores the app's own form when nothing else differs; otherwise the override is kept, switched on, and the page says the form stays on that earlier version. The switches need manage_metadata, the capability the server checks on every write they make: without it they are disabled with a sentence saying why, and a refused switch is told in business words, not the server's message. Claude-Session: https://claude.ai/code/session_01JQwxbWoxCrkYwcqxxENvmn Co-authored-by: Claude --- .changeset/36444-setup-public-forms.md | 3 + .../views/setup/PublicFormsSetupPage.test.tsx | 179 ++++++++++++++++++ .../src/views/setup/PublicFormsSetupPage.tsx | 52 ++++- .../src/views/setup/publicForms.test.ts | 84 +++++++- .../app-shell/src/views/setup/publicForms.ts | 131 ++++++++++--- ui/packages/i18n/src/locales/ar.ts | 6 + ui/packages/i18n/src/locales/de.ts | 6 + ui/packages/i18n/src/locales/en.ts | 6 + ui/packages/i18n/src/locales/es.ts | 6 + ui/packages/i18n/src/locales/fr.ts | 6 + ui/packages/i18n/src/locales/ja.ts | 6 + ui/packages/i18n/src/locales/ko.ts | 6 + ui/packages/i18n/src/locales/pt-BR.ts | 6 + ui/packages/i18n/src/locales/ru.ts | 6 + ui/packages/i18n/src/locales/zh-Hans.ts | 6 + ui/packages/i18n/src/locales/zh-Hant.ts | 6 + 16 files changed, 486 insertions(+), 29 deletions(-) create mode 100644 ui/packages/app-shell/src/views/setup/PublicFormsSetupPage.test.tsx diff --git a/.changeset/36444-setup-public-forms.md b/.changeset/36444-setup-public-forms.md index fb17b3ad875..919055400bb 100644 --- a/.changeset/36444-setup-public-forms.md +++ b/.changeset/36444-setup-public-forms.md @@ -13,7 +13,10 @@ A system administrator (`manage_platform_settings`, the capability the Setup ent - **Which forms are listed.** A form view whose `sharing` opens it to anonymous intake once switched on (`allowAnonymous: true` and a `publicLink`), read by the same rule the anonymous form routes use (`anonymousFormIntakeCandidates`). A switched-off form stays listed and can be switched back on. A form with no public address or no anonymous access is an internal form and is not listed. The list is the effective one (`GET /meta/view`), so an installed app's form switched off in this environment lists as off. - **Where a switch is saved.** The switch is the form's `sharing.enabled`, saved and published at once. A form of a writable package is saved in that package. A form of an installed (read-only) app is saved as this environment's customization, an override in the app's `.custom` package (ADR-0146), never an edit of the app's own package, so the app upgrades as before. Switching such a form back on removes the override when it held nothing but the switch, so the app's own form is served again; an override that also carries design changes keeps them, with the switch on. +- **A form its installed app ships switched off** (its address and anonymous access kept, its switch `false` or omitted, which the stack schema reads as `false`) stays closed whatever the environment saves: the anonymous routes treat the app's own document as a withdrawal that no override re-opens. The page lists such a form as "Off (switched off by its app)" with its switch disabled, also when an override already switches it on, and a switch-on writes nothing and says the app ships it switched off. +- **After an app upgrade**, switching back on an override taken from an earlier version restores the app's own form when the form is otherwise unchanged. When it is not, the override is kept with the switch on and the page says the form stays on the app's earlier version, which Studio's "Restore package original" undoes. - A switch over a draft already pending where it would save writes nothing and says so: that draft is its saver's and is never published on their behalf. +- A switch writes the form's metadata, which the server lets only a `manage_metadata` holder do. Without it the page still lists the forms but disables the switches and says why. A refused switch is told in business words, never the server's raw message. - A switched-off form keeps answering as it does today: `404 FORM_NOT_FOUND` at its address. No route, error code or stored key is added. New Setup navigation entry `nav_public_forms` in `group_configuration` (label "Public Forms", in every shipped locale) opening the component `forms:public-forms`; the Setup navigation now carries 35 entries. New locale block `publicFormsSetup` in every console locale. Not shown: when a form last took a submission, since a submission is an ordinary record of the form's object and records no form. diff --git a/ui/packages/app-shell/src/views/setup/PublicFormsSetupPage.test.tsx b/ui/packages/app-shell/src/views/setup/PublicFormsSetupPage.test.tsx new file mode 100644 index 00000000000..a1b3ba48a5c --- /dev/null +++ b/ui/packages/app-shell/src/views/setup/PublicFormsSetupPage.test.tsx @@ -0,0 +1,179 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * Setup → Public forms, rendered (objectstack#36444): the page's gates and what + * a row says. Which forms are listed and where a switch is saved are + * `publicForms.test.ts`'s; here the list read, the metadata client and the + * package list are faked, and `t` echoes the KEY and its values. + */ + +import '@testing-library/jest-dom/vitest'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; +import type { ReactNode } from 'react'; +import { MemoryRouter } from 'react-router-dom'; + +const fake = vi.hoisted(() => ({ + items: [] as unknown[], + layered: (_name: string, _packageId?: string): { code?: unknown; effective?: unknown; draft?: unknown } => ({}), + packages: new Map(), + save: undefined as unknown as (...args: unknown[]) => Promise, + toast: { success: (..._args: unknown[]) => undefined, error: (..._args: unknown[]) => undefined }, +})); + +vi.mock('@object-ui/i18n', async (importOriginal) => ({ + ...(await importOriginal>()), + useObjectTranslation: () => ({ + t: (key: string, values?: Record) => (values ? `«${key}» ${JSON.stringify(values)}` : `«${key}»`), + language: 'en', + }), +})); +vi.mock('sonner', () => ({ toast: fake.toast })); +vi.mock('../../providers/AdapterProvider.js', () => { + // One adapter for the whole run, as the provider holds one: the page re-reads when it changes. + const adapter = { getClient: () => ({ meta: { getItems: async () => ({ items: fake.items }) } }) }; + return { useAdapter: () => adapter }; +}); +vi.mock('@object-ui/react', async (importOriginal) => ({ + ...(await importOriginal>()), + useMetadata: () => ({ objects: [{ name: 'crm_lead', label: 'Lead' }] }), +})); +vi.mock('../metadata-admin/useMetadata.js', async (importOriginal) => { + const client = { + layered: async (_type: string, name: string, options?: { packageId?: string }) => fake.layered(name, options?.packageId), + save: (...args: unknown[]) => fake.save(...args), + publish: async () => ({}), + reset: async () => ({}), + }; + return { ...(await importOriginal>()), useMetadataClient: () => client }; +}); +vi.mock('../studio-design/packages-io.js', async (importOriginal) => ({ + ...(await importOriginal>()), + fetchListedPackageManifests: async () => fake.packages, +})); + +import { MePermissionsProvider, type MePermissionsAuthenticatedResponse } from '@object-ui/permissions'; +import { PublicFormsSetupPage } from './PublicFormsSetupPage'; + +const sharing = (enabled?: boolean) => ({ + ...(enabled === undefined ? {} : { enabled }), + allowAnonymous: true, + publicLink: 'contact-us', +}); +const form = (enabled: boolean | undefined, extra: Record = {}) => ({ + name: 'web_to_lead', + object: 'crm_lead', + viewKind: 'form', + label: 'Contact us', + _packageId: 'crm', + config: { title: 'Contact us', data: { object: 'crm_lead' }, sharing: sharing(enabled) }, + ...extra, +}); + +function served(systemPermissions: string[]): MePermissionsAuthenticatedResponse { + return { + authenticated: true, + userId: 'admin', + tenantId: 'org1', + positions: [], + hasAnyQueue: false, + objectsUsingQueues: [], + permissionSets: [], + objects: {}, + fields: {}, + systemPermissions, + } as MePermissionsAuthenticatedResponse; +} + +function host(systemPermissions: string[]) { + return ({ children }: { children: ReactNode }) => ( + + {children} + + ); +} + +const ADMIN = ['manage_platform_settings', 'manage_metadata']; + +beforeEach(() => { + fake.items = []; + fake.layered = () => ({}); + fake.packages = new Map(); + fake.save = async () => ({}); + fake.toast.success = vi.fn(); + fake.toast.error = vi.fn(); +}); +afterEach(cleanup); + +describe('PublicFormsSetupPage', () => { + it('without the Setup capability: says so and lists nothing', async () => { + fake.items = [form(true)]; + render(, { wrapper: host(['manage_metadata']) }); + expect(await screen.findByTestId('public-forms-not-allowed')).toHaveTextContent('«publicFormsSetup.notAllowed»'); + expect(screen.queryByTestId('public-forms-table')).toBeNull(); + }); + + it('without the metadata capability the server asks for every switch: lists the forms, says why the switches are off-limits', async () => { + fake.items = [form(true)]; + fake.packages.set('crm', { writable: true, manifest: { id: 'crm' } }); + render(, { wrapper: host(['manage_platform_settings']) }); + expect(await screen.findByTestId('public-form-row-web_to_lead')).toHaveAttribute('data-on', 'true'); + expect(screen.getByTestId('public-forms-no-switch')).toHaveTextContent('«publicFormsSetup.noSwitchPermission»'); + expect(screen.getByTestId('public-form-switch-web_to_lead')).toBeDisabled(); + }); + + for (const [how, enabled] of [['enabled: false', false], ['no enabled', undefined]] as const) { + it(`(${how}) shows a form its installed app ships switched off as off, even when an override switches it on`, async () => { + const base = form(enabled); + const override = { ...form(true), _packageId: undefined, overrides: { package: 'crm', basedOn: '3.0.0' } }; + fake.items = [{ ...override, _packageId: 'crm' }]; + fake.layered = () => ({ code: base, effective: override }); + fake.packages.set('crm', { writable: false, manifest: { id: 'crm', version: '3.0.0' } }); + render(, { wrapper: host(ADMIN) }); + const row = await screen.findByTestId('public-form-row-web_to_lead'); + await waitFor(() => expect(row).toHaveAttribute('data-on', 'false')); + expect(row).toHaveAttribute('data-shipped-off', 'true'); + expect(screen.getByTestId('public-form-shipped-off-web_to_lead')).toHaveTextContent('«publicFormsSetup.shippedOff»'); + expect(screen.getByTestId('public-form-switch-web_to_lead')).toBeDisabled(); + }); + } + + it('a switch over a pending draft says so and does not read as done', async () => { + fake.items = [form(true)]; + fake.layered = () => ({ code: form(true), effective: form(true) }); + fake.packages.set('crm', { writable: true, manifest: { id: 'crm' } }); + fake.save = async () => { + throw Object.assign(new Error('conflict'), { status: 409, code: 'METADATA_CONFLICT' }); + }; + render(, { wrapper: host(ADMIN) }); + fireEvent.click(await screen.findByTestId('public-form-switch-web_to_lead')); + await waitFor(() => expect(fake.toast.error).toHaveBeenCalledWith(expect.stringContaining('«publicFormsSetup.pendingDraft»'))); + expect(fake.toast.success).not.toHaveBeenCalled(); + expect(screen.getByTestId('public-form-row-web_to_lead')).toHaveAttribute('data-on', 'true'); + }); + + it('a switch the server refuses is told in business words, never the server\'s own message', async () => { + fake.items = [form(true)]; + fake.layered = () => ({ code: form(true), effective: form(true) }); + fake.packages.set('crm', { writable: true, manifest: { id: 'crm' } }); + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); + for (const [status, sentence] of [ + [403, '«publicFormsSetup.refusalForbidden»'], + [500, '«publicFormsSetup.refusalServer»'], + ] as const) { + (fake.toast.error as ReturnType).mockClear(); + fake.save = async () => { + throw Object.assign(new Error('Capability manage_metadata required for PUT /meta/view/web_to_lead'), { status }); + }; + const { unmount } = render(, { wrapper: host(ADMIN) }); + fireEvent.click(await screen.findByTestId('public-form-switch-web_to_lead')); + await waitFor(() => expect(fake.toast.error).toHaveBeenCalledTimes(1)); + const [said] = (fake.toast.error as ReturnType).mock.calls[0] as [string]; + expect(said).toContain('«publicFormsSetup.switchFailed»'); + expect(said).toContain(sentence); + expect(said).not.toContain('Capability'); + unmount(); + } + warn.mockRestore(); + }); +}); diff --git a/ui/packages/app-shell/src/views/setup/PublicFormsSetupPage.tsx b/ui/packages/app-shell/src/views/setup/PublicFormsSetupPage.tsx index da1f32b9829..10024e9b074 100644 --- a/ui/packages/app-shell/src/views/setup/PublicFormsSetupPage.tsx +++ b/ui/packages/app-shell/src/views/setup/PublicFormsSetupPage.tsx @@ -6,6 +6,11 @@ * its address, open it in a new tab. For system administrators only: the page * asks the capability its Setup entry asks ({@link PUBLIC_FORMS_CAPABILITY}). * + * A switch writes the form's metadata, which the server lets only an author + * (`manage_metadata`, {@link AUTHORING_CAPABILITY}) do: without it the + * switches are shown off-limits, with a sentence saying why, rather than + * answering every flip with the server's refusal. + * * Operations only: a form is designed (created, deleted, its fields and title * changed) in Studio. Which forms are listed and where a switch is saved are * `publicForms.ts`'s. @@ -40,9 +45,11 @@ import { useAdapter } from '../../providers/AdapterProvider.js'; import { PageHeader } from '../../layout/PageHeader.js'; import { useMetadataClient } from '../metadata-admin/useMetadata.js'; import { formatMetadataError } from '@object-ui/data-objectstack'; +import { AUTHORING_CAPABILITY } from '../../hooks/useCanAuthorMetadata.js'; import { PUBLIC_FORMS_CAPABILITY } from './publicFormsRef.js'; import { PublicFormSwitchRefusal, + markShippedOff, publicFormRowsOf, switchPublicForm, type PublicFormRow, @@ -60,11 +67,24 @@ function refusalText(t: Translate, err: PublicFormSwitchRefusal): string { return t('publicFormsSetup.refusalNoPackage'); case 'no-version': return t('publicFormsSetup.refusalNoVersion'); + case 'shipped-off': + return t('publicFormsSetup.refusalShippedOff'); default: return t('publicFormsSetup.refusalLoadFailed'); } } +/** + * The sentence for a write the server refused: business words, never the + * server's own message (that goes to the console log for whoever debugs it). + */ +function serverRefusalText(t: Translate, err: unknown): string { + const e = err as { status?: unknown; statusCode?: unknown } | null | undefined; + if (e?.status === 403 || e?.statusCode === 403) return t('publicFormsSetup.refusalForbidden'); + console.warn('[public forms] switch refused:', formatMetadataError(err)); + return t('publicFormsSetup.refusalServer'); +} + type Read = { kind: 'loading' } | { kind: 'failed'; message: string } | { kind: 'ready'; rows: PublicFormRow[] }; export function PublicFormsSetupPage() { @@ -96,6 +116,8 @@ function PublicFormsSetupBody() { const adapter = useAdapter(); const metadata = useMetadata(); const metadataClient = useMetadataClient(); + const { hasCapabilities } = usePermissions(); + const canSwitch = hasCapabilities([AUTHORING_CAPABILITY]); const [read, setRead] = React.useState({ kind: 'loading' }); const [busy, setBusy] = React.useState(null); const [nonce, setNonce] = React.useState(0); @@ -108,7 +130,8 @@ function PublicFormsSetupBody() { try { if (!client?.meta?.getItems) throw new Error('meta.getItems is not available on this client'); const answer = await client.meta.getItems('view'); - if (live) setRead({ kind: 'ready', rows: publicFormRowsOf(answer) }); + const rows = await markShippedOff(publicFormRowsOf(answer), metadataClient as any); + if (live) setRead({ kind: 'ready', rows }); } catch (err) { if (live) setRead({ kind: 'failed', message: formatMetadataError(err) }); } @@ -116,7 +139,7 @@ function PublicFormsSetupBody() { return () => { live = false; }; - }, [adapter, nonce]); + }, [adapter, metadataClient, nonce]); const objectLabel = React.useCallback( (name: string | undefined) => { @@ -150,7 +173,11 @@ function PublicFormsSetupBody() { toast.error(t('publicFormsSetup.pendingDraft', { name: row.title })); return; } - toast.success(t(on ? 'publicFormsSetup.switchedOn' : 'publicFormsSetup.switchedOff', { name: row.title })); + if (typeof outcome === 'object') { + toast.success(t('publicFormsSetup.switchedOnEarlierVersion', { name: row.title, version: outcome.basedOn })); + } else { + toast.success(t(on ? 'publicFormsSetup.switchedOn' : 'publicFormsSetup.switchedOff', { name: row.title })); + } // The row reads back as the server now serves it. setRead((prev) => prev.kind === 'ready' @@ -159,8 +186,9 @@ function PublicFormsSetupBody() { ); setNonce((n) => n + 1); } catch (err) { - const message = err instanceof PublicFormSwitchRefusal ? refusalText(t, err) : formatMetadataError(err); + const message = err instanceof PublicFormSwitchRefusal ? refusalText(t, err) : serverRefusalText(t, err); toast.error(t('publicFormsSetup.switchFailed', { name: row.title, message })); + if (err instanceof PublicFormSwitchRefusal && err.reason === 'shipped-off') setNonce((n) => n + 1); } finally { setBusy(null); } @@ -204,6 +232,11 @@ function PublicFormsSetupBody() {

{t('publicFormsSetup.designHint')}

{refresh} + {!canSwitch && ( + + {t('publicFormsSetup.noSwitchPermission')} + + )} {read.rows.length === 0 ? (

{t('publicFormsSetup.emptyTitle')}

@@ -226,7 +259,12 @@ function PublicFormsSetupBody() { const address = addressOf(row.slug); const label = objectLabel(row.object); return ( - + {row.title} {label ? {label} : null} @@ -236,7 +274,7 @@ function PublicFormsSetupBody() {
void flip(row, next)} aria-label={t(row.on ? 'publicFormsSetup.switchOffLabel' : 'publicFormsSetup.switchOnLabel', { name: row.title, @@ -248,6 +286,8 @@ function PublicFormsSetupBody() {