diff --git a/.changeset/36444-setup-public-forms.md b/.changeset/36444-setup-public-forms.md new file mode 100644 index 00000000000..64b13808396 --- /dev/null +++ b/.changeset/36444-setup-public-forms.md @@ -0,0 +1,24 @@ +--- +'@object-ui/app-shell': patch +'@object-ui/i18n': patch +'@objectstack/platform-objects': patch +'@objectstack/spec': patch +'@objectstack/metadata-core': patch +--- + +feat(setup): Setup → Configuration → Public forms lists every public form of the environment and switches it on or off + +Clause-②: yes (widening) — a new Setup navigation id `nav_public_forms`, a new component id `forms:public-forms`, new language-pack keys (the `publicFormsSetup` block and the nav label) in every shipped locale, and `anonymousFormIntakeWithdrawnIn` newly exported from `@objectstack/spec/ui` (moved from `@objectstack/metadata-core`, which re-exports the same binding) +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 form its installed app ships switched off** (its address kept, `enabled` or `allowAnonymous` set to `false`, or `enabled` 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 judges this with the routes' own function, `anonymousFormIntakeWithdrawnIn`, now declared in `@objectstack/spec/ui` beside the rest of the intake rule; `@objectstack/metadata-core` re-exports the same binding, so the server's import is unchanged. 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. A form whose app's document cannot be read is shown as status unknown, never as on. +- **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, and a list read that fails, are 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/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/metadata-core/src/anonymous-form-intake.test.ts b/packages/metadata-core/src/anonymous-form-intake.test.ts index 4c334174e41..99f7d986f04 100644 --- a/packages/metadata-core/src/anonymous-form-intake.test.ts +++ b/packages/metadata-core/src/anonymous-form-intake.test.ts @@ -322,13 +322,14 @@ describe('anonymousFormIntakeWithdrawnIn — an explicit withdrawal of the same // The candidates half is declared in `@objectstack/spec/ui` and re-exported by // this package. "One copy" is checkable only as IDENTITY: a wrapper or a copy // answers the same today and drifts tomorrow, while the same binding cannot. -describe('the candidates and object-name halves are the spec bindings themselves, re-exported (one copy, not a copy)', () => { +describe('the candidates, object-name and withdrawal halves are the spec bindings themselves, re-exported (one copy, not a copy)', () => { const NAMES = [ 'publicFormSlug', 'anonymousFormIntakeSlug', 'anonymousFormIntakeCandidates', 'anonymousFormIntakeSlugs', 'anonymousFormObjectName', + 'anonymousFormIntakeWithdrawnIn', ] as const; it.each(NAMES)('%s: this module and the package barrel export the @objectstack/spec/ui function', (name) => { diff --git a/packages/metadata-core/src/anonymous-form-intake.ts b/packages/metadata-core/src/anonymous-form-intake.ts index 28ebb91dcc1..42188ea5e8e 100644 --- a/packages/metadata-core/src/anonymous-form-intake.ts +++ b/packages/metadata-core/src/anonymous-form-intake.ts @@ -41,21 +41,23 @@ import { postureEnforcesWall, type TenancyPosture, } from '@objectstack/spec/security'; -import { publicFormSlug, type AnonymousFormIntakeCandidate } from '@objectstack/spec/ui'; +import type { AnonymousFormIntakeCandidate } from '@objectstack/spec/ui'; import { applyInjectedSystemColumns } from './injected-system-columns.js'; import { resolveRecordWallOrganizationField } from './record-organization.js'; // The candidates half of the rule — which form candidates a `view` body opens -// to anonymous intake — and the object-name half (`anonymousFormObjectName`, -// the object a candidate submits into) live in `@objectstack/spec/ui` beside the -// `SharingConfigSchema` it reads, so a console can import the same rule the -// doors serve. Re-exported here as the SAME bindings (never a wrapper or a +// to anonymous intake — the object-name half (`anonymousFormObjectName`, the +// object a candidate submits into) and the withdrawal half +// (`anonymousFormIntakeWithdrawnIn`, whether a layer's body withdraws a +// candidate) live in `@objectstack/spec/ui` beside the `SharingConfigSchema` +// they read, so a console can import the same rule the doors serve. Re-exported here as the SAME bindings (never a wrapper or a // copy), so every server caller keeps importing it from this package and the // two entries cannot disagree; the identity is pinned in this module's test. export { anonymousFormIntakeCandidates, anonymousFormIntakeSlug, anonymousFormIntakeSlugs, + anonymousFormIntakeWithdrawnIn, anonymousFormObjectName, publicFormSlug, } from '@objectstack/spec/ui'; @@ -196,108 +198,3 @@ export function anonymousFormIntakeUnavailableMessage(slug: string, u: Anonymous ); } -/** - * Where a form sits in a `view` body, independent of its content: the nested - * `form`, one `formViews` entry, or the flattened `config`. - */ -function anonymousFormSlot(view: Record, candidate: AnonymousFormIntakeCandidate): string { - if (candidate.form === view.form) return 'form'; - if (candidate.key !== undefined && view.formViews?.[candidate.key] === candidate.form) { - return `formViews:${candidate.key}`; - } - return 'config'; -} - -/** - * The forms a `view` body EXPLICITLY withdraws, with their slot and slug: a - * form `sharing` that keeps a non-empty `publicLink` and sets `enabled === - * false` or `allowAnonymous === false`. Judged on the body as stored: a switch - * that is absent is not a withdrawal (only an explicit `false` is), and a - * sharing with no public link withdraws nothing — removing the sharing block or - * clearing the link is not a withdrawal. A package artifact parsed by the - * stack schema (strict `defineStack`) carries the schema's default - * `enabled: false`, which is an explicit `false`: a shipped form that keeps its - * link without switching `enabled` on is withdrawn (fail closed). An artifact - * that reached the runtime unparsed (`strict: false`, a hand-built manifest) - * is judged as written, so a switch it omits is absent. The env-wide definition is the - * switch above it, so an env-wide save may still open it. - */ -function anonymousFormExplicitWithdrawals(view: unknown): Array<{ slot: string; slug: string }> { - if (!view || typeof view !== 'object') return []; - const v = view as Record; - const forms: Array<{ slot: string; form: unknown }> = []; - if (v.form && typeof v.form === 'object') forms.push({ slot: 'form', form: v.form }); - if (v.formViews && typeof v.formViews === 'object') { - for (const [key, fv] of Object.entries(v.formViews)) forms.push({ slot: `formViews:${key}`, form: fv }); - } - if (v.viewKind === 'form' && v.config && typeof v.config === 'object') forms.push({ slot: 'config', form: v.config }); - const out: Array<{ slot: string; slug: string }> = []; - for (const { slot, form } of forms) { - const sharing = form && typeof form === 'object' ? (form as Record).sharing : undefined; - if (!sharing || typeof sharing !== 'object') continue; - const s = sharing as Record; - if (typeof s.publicLink !== 'string' || !s.publicLink) continue; - if (s.enabled !== false && s.allowAnonymous !== false) continue; - out.push({ slot, slug: publicFormSlug(s.publicLink) }); - } - return out; -} - -/** - * Does one metadata layer withdraw an open form candidate? A WITHDRAWAL IS A - * KILL SWITCH: layering may only narrow anonymous intake, never re-open it, so - * the anonymous form doors serve a candidate only when no layer beneath it - * withdraws it, and the organization-scoped write door refuses a save that - * would leave one open. - * - * Identity is the `name`: the layer withdraws the candidate only through a - * body of the same `name` as the candidate's `view`. What that name is depends - * on the caller. The organization-scoped write door passes the env-wide body - * of the stored row the overlay is keyed by, so a key rename, a `form.name`, - * a slot move or an expansion rename is still judged against the form it was. - * The anonymous doors pass the env-wide view list and the item they serve, so - * they judge by the served item name (a known limit: an overlay stored before - * the withdrawal, or restored by rollback or revert, that moves its form to - * another key or slot is not matched there). The layer withdraws the - * candidate when its body of that name EXPLICITLY - * withdraws a form ({@link anonymousFormExplicitWithdrawals}) that matches the - * candidate by slot (the same `form`, `formViews` key or `config`) OR by slug - * (the same public link, compared exactly as the doors resolve it). Either - * match is enough, so the same form cannot escape a withdrawal by moving to - * another slot or key, or by pointing its link at a new slug; only a form that - * differs from every withdrawn one in both is a different form (a sibling in - * the same container). - * - * Another row that publishes or withdraws the same slug is a different form - * and closes nothing. The package a body is bound to is NOT compared: a - * withdrawal of a name closes that name's form in every package (a known - * limit that fails closed: it may over-close another package's form of the - * same name). It judges only the bodies the layer holds, so a caller closes a - * name in every package only when its layer holds every package's body of the - * name. The organization-scoped write door anchors one body per package. The - * env-wide view list the anonymous doors read holds one item per package of a - * name: a package's saved env-wide copy of a view container serves that - * package's item of each form it expands, and a package-less copy stands in - * for every package with no copy of its own. A layer - * with no body of the row, or whose body has no explicit withdrawal, withdraws - * nothing, so a form published only in an organization stays open there. - */ -export function anonymousFormIntakeWithdrawnIn( - layer: ReadonlyArray, - view: unknown, - candidate: AnonymousFormIntakeCandidate, -): boolean { - if (!view || typeof view !== 'object') return false; - const v = view as Record; - const name = typeof v.name === 'string' && v.name ? v.name : undefined; - if (name === undefined) return false; - const slot = anonymousFormSlot(v, candidate); - for (const other of layer) { - if (!other || typeof other !== 'object') continue; - if ((other as Record).name !== name) continue; - for (const w of anonymousFormExplicitWithdrawals(other)) { - if (w.slot === slot || w.slug === candidate.slug) return true; - } - } - return false; -} 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/packages/spec/api-surface/ui.json b/packages/spec/api-surface/ui.json index 99e688ee856..8f67ffa931b 100644 --- a/packages/spec/api-surface/ui.json +++ b/packages/spec/api-surface/ui.json @@ -537,6 +537,7 @@ "anonymousFormIntakeCandidates (function)", "anonymousFormIntakeSlug (function)", "anonymousFormIntakeSlugs (function)", + "anonymousFormIntakeWithdrawnIn (function)", "anonymousFormObjectName (function)", "appForm (const)", "bulkConfirmTemplateRoots (function)", diff --git a/packages/spec/export-origins/ui.json b/packages/spec/export-origins/ui.json index 209f1362aa0..656f4f5abf5 100644 --- a/packages/spec/export-origins/ui.json +++ b/packages/spec/export-origins/ui.json @@ -520,6 +520,7 @@ "anonymousFormIntakeCandidates": "src/ui/anonymous-form-intake.ts#anonymousFormIntakeCandidates (function)", "anonymousFormIntakeSlug": "src/ui/anonymous-form-intake.ts#anonymousFormIntakeSlug (function)", "anonymousFormIntakeSlugs": "src/ui/anonymous-form-intake.ts#anonymousFormIntakeSlugs (function)", + "anonymousFormIntakeWithdrawnIn": "src/ui/anonymous-form-intake.ts#anonymousFormIntakeWithdrawnIn (function)", "anonymousFormObjectName": "src/ui/anonymous-form-intake.ts#anonymousFormObjectName (function)", "appForm": "src/ui/app.form.ts#appForm (const)", "bulkConfirmTemplateRoots": "src/ui/bulk-action.zod.ts#bulkConfirmTemplateRoots (function)", diff --git a/packages/spec/src/ui/anonymous-form-intake.ts b/packages/spec/src/ui/anonymous-form-intake.ts index 0b6c57b48bc..64898008b49 100644 --- a/packages/spec/src/ui/anonymous-form-intake.ts +++ b/packages/spec/src/ui/anonymous-form-intake.ts @@ -38,14 +38,22 @@ * `@objectstack/metadata-core` re-exports these bindings (the same functions, * not a copy), so the server packages keep importing them from there. * - * ## What stays in `@objectstack/metadata-core` + * ## The withdrawal half * - * The halves that read server state: a withdrawal in another metadata layer + * Whether a metadata layer's body withdraws an open candidate * (`anonymousFormIntakeWithdrawnIn`, a kill switch that layering may only - * narrow, never re-open), and whether the deployment's tenancy posture lets an - * open form take an anonymous submission (`anonymousFormIntakeUnavailability`). - * An open candidate here is what the view body itself declares, before any - * other layer or the posture is consulted. The object a candidate submits into + * narrow, never re-open) is a pure judgement of bodies the caller hands it, so + * it is declared here too: the anonymous doors judge the layers they read with + * it, and a console that switches an installed app's form judges the app's own + * document with the same function (objectstack#36444). + * + * ## What stays in `@objectstack/metadata-core` + * + * The half that reads server state: whether the deployment's tenancy posture + * lets an open form take an anonymous submission + * (`anonymousFormIntakeUnavailability`). An open candidate here is what the + * view body itself declares, before any other layer or the posture is + * consulted. The object a candidate submits into * (`anonymousFormObjectName`) reads no server state, so it is declared here * too, and `@objectstack/metadata-core` re-exports it. * @@ -118,3 +126,109 @@ export function anonymousFormIntakeCandidates(view: unknown): AnonymousFormIntak export function anonymousFormIntakeSlugs(view: unknown): string[] { return [...new Set(anonymousFormIntakeCandidates(view).map((c) => c.slug))].sort(); } + +/** + * Where a form sits in a `view` body, independent of its content: the nested + * `form`, one `formViews` entry, or the flattened `config`. + */ +function anonymousFormSlot(view: Record, candidate: AnonymousFormIntakeCandidate): string { + if (candidate.form === view.form) return 'form'; + if (candidate.key !== undefined && view.formViews?.[candidate.key] === candidate.form) { + return `formViews:${candidate.key}`; + } + return 'config'; +} + +/** + * The forms a `view` body EXPLICITLY withdraws, with their slot and slug: a + * form `sharing` that keeps a non-empty `publicLink` and sets `enabled === + * false` or `allowAnonymous === false`. Judged on the body as stored: a switch + * that is absent is not a withdrawal (only an explicit `false` is), and a + * sharing with no public link withdraws nothing — removing the sharing block or + * clearing the link is not a withdrawal. A package artifact parsed by the + * stack schema (strict `defineStack`) carries the schema's default + * `enabled: false`, which is an explicit `false`: a shipped form that keeps its + * link without switching `enabled` on is withdrawn (fail closed). An artifact + * that reached the runtime unparsed (`strict: false`, a hand-built manifest) + * is judged as written, so a switch it omits is absent. The env-wide definition is the + * switch above it, so an env-wide save may still open it. + */ +function anonymousFormExplicitWithdrawals(view: unknown): Array<{ slot: string; slug: string }> { + if (!view || typeof view !== 'object') return []; + const v = view as Record; + const forms: Array<{ slot: string; form: unknown }> = []; + if (v.form && typeof v.form === 'object') forms.push({ slot: 'form', form: v.form }); + if (v.formViews && typeof v.formViews === 'object') { + for (const [key, fv] of Object.entries(v.formViews)) forms.push({ slot: `formViews:${key}`, form: fv }); + } + if (v.viewKind === 'form' && v.config && typeof v.config === 'object') forms.push({ slot: 'config', form: v.config }); + const out: Array<{ slot: string; slug: string }> = []; + for (const { slot, form } of forms) { + const sharing = form && typeof form === 'object' ? (form as Record).sharing : undefined; + if (!sharing || typeof sharing !== 'object') continue; + const s = sharing as Record; + if (typeof s.publicLink !== 'string' || !s.publicLink) continue; + if (s.enabled !== false && s.allowAnonymous !== false) continue; + out.push({ slot, slug: publicFormSlug(s.publicLink) }); + } + return out; +} + +/** + * Does one metadata layer withdraw an open form candidate? A WITHDRAWAL IS A + * KILL SWITCH: layering may only narrow anonymous intake, never re-open it, so + * the anonymous form doors serve a candidate only when no layer beneath it + * withdraws it, and the organization-scoped write door refuses a save that + * would leave one open. + * + * Identity is the `name`: the layer withdraws the candidate only through a + * body of the same `name` as the candidate's `view`. What that name is depends + * on the caller. The organization-scoped write door passes the env-wide body + * of the stored row the overlay is keyed by, so a key rename, a `form.name`, + * a slot move or an expansion rename is still judged against the form it was. + * The anonymous doors pass the env-wide view list and the item they serve, so + * they judge by the served item name (a known limit: an overlay stored before + * the withdrawal, or restored by rollback or revert, that moves its form to + * another key or slot is not matched there). The layer withdraws the + * candidate when its body of that name EXPLICITLY + * withdraws a form ({@link anonymousFormExplicitWithdrawals}) that matches the + * candidate by slot (the same `form`, `formViews` key or `config`) OR by slug + * (the same public link, compared exactly as the doors resolve it). Either + * match is enough, so the same form cannot escape a withdrawal by moving to + * another slot or key, or by pointing its link at a new slug; only a form that + * differs from every withdrawn one in both is a different form (a sibling in + * the same container). + * + * Another row that publishes or withdraws the same slug is a different form + * and closes nothing. The package a body is bound to is NOT compared: a + * withdrawal of a name closes that name's form in every package (a known + * limit that fails closed: it may over-close another package's form of the + * same name). It judges only the bodies the layer holds, so a caller closes a + * name in every package only when its layer holds every package's body of the + * name. The organization-scoped write door anchors one body per package. The + * env-wide view list the anonymous doors read holds one item per package of a + * name: a package's saved env-wide copy of a view container serves that + * package's item of each form it expands, and a package-less copy stands in + * for every package with no copy of its own. A layer + * with no body of the row, or whose body has no explicit withdrawal, withdraws + * nothing, so a form published only in an organization stays open there. + */ +export function anonymousFormIntakeWithdrawnIn( + layer: ReadonlyArray, + view: unknown, + candidate: AnonymousFormIntakeCandidate, +): boolean { + if (!view || typeof view !== 'object') return false; + const v = view as Record; + const name = typeof v.name === 'string' && v.name ? v.name : undefined; + if (name === undefined) return false; + const slot = anonymousFormSlot(v, candidate); + for (const other of layer) { + if (!other || typeof other !== 'object') continue; + if ((other as Record).name !== name) continue; + for (const w of anonymousFormExplicitWithdrawals(other)) { + if (w.slot === slot || w.slug === candidate.slug) return true; + } + } + return false; +} 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/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.test.tsx b/ui/packages/app-shell/src/views/setup/PublicFormsSetupPage.test.tsx new file mode 100644 index 00000000000..e6bcc341241 --- /dev/null +++ b/ui/packages/app-shell/src/views/setup/PublicFormsSetupPage.test.tsx @@ -0,0 +1,213 @@ +// 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[], + listFails: null as string | null, + 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 () => { + if (fake.listFails) throw new Error(fake.listFails); + return { 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.listFails = null; + 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 list read that fails says so in business words, never the server\'s own message', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); + fake.listFails = 'GET /api/v1/meta/view failed: ECONNRESET upstream'; + render(, { wrapper: host(ADMIN) }); + const alert = await screen.findByTestId('public-forms-load-failed'); + expect(alert).toHaveTextContent('«publicFormsSetup.loadFailed»'); + expect(alert).not.toHaveTextContent('ECONNRESET'); + warn.mockRestore(); + }); + + it('a form whose app\'s document cannot be read is not shown as on', async () => { + fake.items = [form(true)]; + fake.layered = () => { + throw new Error('503'); + }; + 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-unknown', 'true')); + expect(row).toHaveAttribute('data-on', 'false'); + expect(screen.getByTestId('public-form-unknown-web_to_lead')).toHaveTextContent('«publicFormsSetup.statusUnknown»'); + }); + + 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 new file mode 100644 index 00000000000..169a0eda27c --- /dev/null +++ b/ui/packages/app-shell/src/views/setup/PublicFormsSetupPage.tsx @@ -0,0 +1,336 @@ +// 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}). + * + * 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. + * + * 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 { AUTHORING_CAPABILITY } from '../../hooks/useCanAuthorMetadata.js'; +import { PUBLIC_FORMS_CAPABILITY } from './publicFormsRef.js'; +import { + PublicFormSwitchRefusal, + markShippedOff, + 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'); + 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' } | { 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 { 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); + + 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'); + const rows = await markShippedOff(publicFormRowsOf(answer), metadataClient as any); + if (live) setRead({ kind: 'ready', rows }); + } catch (err) { + // The server's own words go to the console log; the page says it in business words. + console.warn('[public forms] list read failed:', formatMetadataError(err)); + if (live) setRead({ kind: 'failed' }); + } + })(); + return () => { + live = false; + }; + }, [adapter, metadataClient, 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; + } + 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' + ? { 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) : 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); + } + }; + + const refresh = ( + + ); + + if (read.kind === 'loading') { + return ( +
+ + +
+ ); + } + if (read.kind === 'failed') { + return ( + + + + {t('publicFormsSetup.loadFailed')} + {refresh} + + + ); + } + return ( +
+
+

{t('publicFormsSetup.designHint')}

+ {refresh} +
+ {!canSwitch && ( + + {t('publicFormsSetup.noSwitchPermission')} + + )} + {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..0bc794c30ed --- /dev/null +++ b/ui/packages/app-shell/src/views/setup/publicForms.test.ts @@ -0,0 +1,347 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { describe, it, expect, vi } from 'vitest'; +import { + PublicFormSwitchRefusal, + baseShipsFormOff, + markShippedOff, + 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: '3.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)); + expect(body.overrides).toEqual({ package: 'crm', basedOn: '3.0.0' }); + }); + + it('after an app upgrade, switching back on says the form stays on the earlier version its override was taken from', async () => { + // Switched off at 2.0.0 (a switch-only copy of the 2.0.0 form); the app is now 3.0.0 with a changed form. + const base = formItem({ label: 'Contact sales' }); + const override = { ...stripped(formItem({}, 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).toEqual({ kind: 'earlier-version', basedOn: '2.0.0' }); + expect(client.reset).not.toHaveBeenCalled(); + const [, , body] = client.save.mock.calls[0] as unknown as [string, string, any]; + 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('after an app upgrade that left the form as it was, switching back on restores the app\'s own form', async () => { + const base = formItem(); + const override = { ...stripped(formItem({}, false)), overrides: { package: 'crm', basedOn: '2.0.0' } }; + 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' } }); + await expect(switchPublicForm(row, true, client, {}, doors)).resolves.toBe('restored'); + expect(client.save).not.toHaveBeenCalled(); + }); + + describe('a form the installed app ships switched off', () => { + const shippedOff = { + 'enabled: false': formItem({}, false), + 'no enabled': formItem({ config: { title: 'Contact us', data: { object: 'crm_lead' }, sharing: { allowAnonymous: true, publicLink: 'contact-us' } } }), + }; + const doors = () => listed({ crm: { writable: false, version: '3.0.0' }, 'crm.custom': { writable: true, version: '0.0.0' } }); + + for (const [how, base] of Object.entries(shippedOff)) { + it(`(${how}) is never switched on: nothing is written, and the refusal says the app ships it off`, async () => { + expect(baseShipsFormOff(base, 'web_to_lead')).toBe(true); + // No override yet: the list serves the app's own document. + const fresh = clientOf(() => ({ code: base, effective: base })); + const freshDoors = doors(); + await expect(switchPublicForm(row, true, fresh, {}, freshDoors)).rejects.toMatchObject({ + name: 'PublicFormSwitchRefusal', + reason: 'shipped-off', + }); + // An override that switches it on already (saved before this page knew better): still refused. + const override = { ...stripped(formItem()), overrides: { package: 'crm', basedOn: '3.0.0' } }; + const overridden = clientOf(() => ({ code: base, effective: override })); + await expect(switchPublicForm(row, true, overridden, {}, doors())).rejects.toMatchObject({ reason: 'shipped-off' }); + for (const c of [fresh, overridden]) { + expect(c.save).not.toHaveBeenCalled(); + expect(c.reset).not.toHaveBeenCalled(); + } + expect(freshDoors.ensureCustomization).not.toHaveBeenCalled(); + }); + + it(`(${how}) is listed, never as on, even when an override switches it on`, async () => { + const override = { ...stripped(formItem()), overrides: { package: 'crm', basedOn: '3.0.0' } }; + const client = clientOf(() => ({ code: base, effective: override })); + const listedDoors = doors(); + const served = publicFormRowOf({ ...override, _packageId: 'crm' })!; + expect(served.on).toBe(true); + const [marked] = await markShippedOff([served], client, listedDoors); + expect(marked).toMatchObject({ name: 'web_to_lead', on: false, shippedOff: true }); + }); + } + + it('(allowAnonymous: false) the routes\' own rule: an app that ships the form closed to anonymous visitors withdraws it, even once an override opens it', async () => { + const base = formItem({ config: { title: 'Contact us', data: { object: 'crm_lead' }, sharing: sharing(true, { allowAnonymous: false }) } }); + const override = { ...stripped(formItem()), overrides: { package: 'crm', basedOn: '3.0.0' } }; + expect(baseShipsFormOff(base, 'web_to_lead', override)).toBe(true); + // The served override reads on, by the candidates rule alone. + const served = publicFormRowOf({ ...override, _packageId: 'crm' })!; + expect(served.on).toBe(true); + const client = clientOf(() => ({ code: base, effective: override })); + const [marked] = await markShippedOff([served], client, doors()); + expect(marked).toMatchObject({ on: false, shippedOff: true }); + await expect(switchPublicForm(row, true, client, {}, doors())).rejects.toMatchObject({ reason: 'shipped-off' }); + expect(client.save).not.toHaveBeenCalled(); + }); + + it('does not read a form whose app\'s document cannot be read as on', async () => { + const client = clientOf(() => { + throw new Error('503'); + }); + const served = publicFormRowOf(formItem())!; + const [marked] = await markShippedOff([served], client, doors()); + expect(marked).toMatchObject({ on: false, unknown: true }); + expect(marked.shippedOff).toBeUndefined(); + }); + + it('leaves a form the app ships on, a writable package\'s form and a form with no package as listed', async () => { + const on = formItem(); + expect(baseShipsFormOff(on, 'web_to_lead')).toBe(false); + const client = clientOf((name) => ({ code: name === 'own' ? formItem({}, false) : on, effective: on })); + const listedDoors = listed({ crm: { writable: false, version: '3.0.0' }, mine: { writable: true } }); + const rows = [ + publicFormRowOf(on)!, + { ...publicFormRowOf(formItem({}, false))!, name: 'own', packageId: 'mine' }, + { ...publicFormRowOf(on)!, name: 'loose', packageId: null }, + ]; + const marked = await markShippedOff(rows, client, listedDoors); + expect(marked).toEqual(rows); + // The package list is read once for the whole page, and only an installed app's form is read. + expect(listedDoors.listPackages).toHaveBeenCalledTimes(1); + expect(client.layered).toHaveBeenCalledTimes(1); + }); + }); + + 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..a2052ff28f7 --- /dev/null +++ b/ui/packages/app-shell/src/views/setup/publicForms.ts @@ -0,0 +1,365 @@ +// 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; when it was taken from an + * earlier version of the app than the one installed, the switch says the + * form stays on that earlier version (the app's earlier document cannot be + * read to tell a switch-only override from a design one). + * + * ## A form the app ships switched off + * + * An installed app whose own document keeps a form's address but switches it + * off (`enabled: false` or `allowAnonymous: false`, matched by slot or by + * slug) WITHDRAWS it: the anonymous routes judge the app's own document as a + * kill switch that no override re-opens (`anonymousFormIntakeWithdrawnIn`, + * pinned in `packages/rest/src/public-form-withdrawal-effective-read.test.ts`). + * This page judges it with that same function, imported from the spec. A + * switch the app's document omits counts as off too, as the stack schema + * parses it (`enabled` defaults to `false`). Such a form is listed, never as + * on ({@link markShippedOff}), and switching it on writes nothing and says the + * app ships it switched off. + * + * 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, anonymousFormIntakeWithdrawnIn, 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'; +import { fetchListedPackageManifests } from '../studio-design/packages-io.js'; + +type FormDoc = Record; + +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 { + /** 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; + /** + * The installed app this form belongs to ships it switched off, so the + * routes keep it closed whatever this environment saves (module header). + * Set by {@link markShippedOff}; absent until then. + */ + shippedOff?: boolean; + /** + * {@link markShippedOff} could not read the app's own document, so whether + * the routes serve the form is not known: the row is not shown as on. + */ + unknown?: boolean; +} + +/** `form` with its switch set to `on`: the only key a switch writes. */ +function withSwitch(form: FormDoc, on: boolean): FormDoc { + 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: 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 ( + 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. `earlier-version`: switched on, and the form stays on the + * app's earlier version `basedOn` that this environment's customization was + * taken from (module header). + */ +export type PublicFormSwitchOutcome = SaveAndPublishOutcome | 'restored' | { kind: 'earlier-version'; basedOn: string }; + +/** A switch the console refuses before writing anything. */ +export class PublicFormSwitchRefusal extends Error { + constructor( + readonly reason: 'no-package' | 'no-version' | 'load-failed' | 'shipped-off', + detail?: string, + ) { + super(detail ?? reason); + this.name = 'PublicFormSwitchRefusal'; + } +} + +/** A document without the read's `_` decorations. */ +function authored(doc: FormDoc): FormDoc { + const out: FormDoc = {}; + 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: 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); + return out; + }; + return canonical(strip(override)) === canonical(strip(base)); +} + +/** + * Whether an installed app's own document `base` of the form `name` ships it + * switched off (module header), judged by the routes' own rule: `base` + * withdraws the form `served` carries (the effective item, an override + * included; `base` itself when omitted), matched by slot or by slug + * (`anonymousFormIntakeWithdrawnIn`). The served form is judged with its switch + * on, the state a switch-on would leave it in. A switch the app's document + * omits counts as off as well, as the stack schema parses it, so the console + * fails closed where the routes do. + */ +export function baseShipsFormOff(base: unknown, name: string, served?: unknown): boolean { + if (!isDoc(base) || !isDoc(base.config)) return false; + const named = { ...base, name }; + const view: FormDoc = isDoc(served) ? { ...served, name } : named; + const probe = isDoc(view.config) ? { ...view, config: withSwitch(view.config, true) } : view; + const candidates = anonymousFormIntakeCandidates(probe).filter((c) => c.key === name); + if (candidates.some((c) => anonymousFormIntakeWithdrawnIn([named], probe, c))) return true; + // An omitted switch: the app's document would open the form switched on, but does not as written. + const wouldOpen = anonymousFormIntakeCandidates({ ...named, config: withSwitch(base.config, true) }).some((c) => c.key === name); + return wouldOpen && !anonymousFormIntakeCandidates(named).some((c) => c.key === name); +} + +type FormLayers = { code?: unknown; effective?: unknown; draft?: unknown }; +type ResolvedTarget = Exclude>, { kind: 'refused' }>; + +/** + * The layers of the form `name` where its target serves it: 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. + */ +async function readFormLayers(name: string, target: ResolvedTarget, client: Pick): Promise { + const at = + target.kind === 'unbound' + ? {} + : target.kind === 'package' + ? { packageId: target.packageId } + : { packageId: target.pair ?? target.base }; + const layers = await client.layered('view', 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)) { + return client.layered('view', name, { packageId: target.base }); + } + return layers; +} + +/** + * `rows` with each installed app's form that the app ships switched off marked + * `shippedOff` and shown off (module header): the list read serves the + * effective item, which an override may switch on although the routes keep the + * form closed. Reads the package list once and the layers of each installed + * app's form; a row whose layers cannot be read is marked `unknown` and is not + * shown as on. + */ +export async function markShippedOff( + rows: readonly PublicFormRow[], + client: Pick, + doors?: Pick, +): Promise { + if (!rows.some((r) => r.packageId)) return [...rows]; + const listPackages = doors?.listPackages ?? fetchListedPackageManifests; + let listing: ReturnType | undefined; + const once = { listPackages: () => (listing ??= listPackages()) }; + return Promise.all( + rows.map(async (row) => { + if (!row.packageId) return row; + const target = await resolveDashboardEditTarget(row.packageId, once); + if (target.kind !== 'customization') return row; + try { + const layers = await readFormLayers(row.name, target, client); + const served = isDoc(layers.effective) ? layers.effective : layers.code; + return baseShipsFormOff(layers.code, row.name, served) ? { ...row, on: false, shippedOff: true } : row; + } catch { + return { ...row, on: false, unknown: true }; + } + }), + ); +} + +/** + * 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 }; + + let layers: FormLayers; + try { + layers = await readFormLayers(row.name, target, client); + } 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 declared = declaredOverrideOf(effective, target.base); + const override = declared ? effective : null; + const base = isDoc(layers.code) ? layers.code : null; + // The app ships the form switched off: no override re-opens it, so nothing is written. + if (on && baseShipsFormOff(base, row.name, effective)) throw new PublicFormSwitchRefusal('shipped-off', target.base); + if (on && override && base && isDoc(base.config)) { + const baseOn = anonymousFormIntakeCandidates({ ...base, name: row.name }).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); + const outcome = await saveAndPublishInPackage('view', row.name, body, saveTarget.packageId, persist); + // Switched on over an override taken from an earlier version of the app: the form stays on that version. + if (on && outcome === 'published' && declared && target.basedOn && declared.basedOn !== target.basedOn) { + return { kind: 'earlier-version', basedOn: declared.basedOn }; + } + return outcome; +} 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 8c0e5292784..c9178a1f019 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -6548,6 +6548,43 @@ const ar = { linkedAt: "تم الربط {{at}}", disconnect: "إلغاء الربط", }, + publicFormsSetup: { + title: "النماذج العامة", + subtitle: "نماذج يمكن لأي شخص تعبئتها دون تسجيل الدخول، مثل نموذج الاتصال على موقعك. يصبح كل إرسال سجلًا.", + notAllowed: "يمكن لمسؤولي النظام فقط إدارة النماذج العامة.", + designHint: "أوقف تشغيل نموذج للتوقف عن تلقي الإرسالات؛ عندها لن يفتح عنوانه شيئًا. تُصمَّم النماذج في Studio.", + refresh: "تحديث", + emptyTitle: "لا توجد نماذج عامة بعد", + emptyBody: "تُصمَّم النماذج العامة في Studio. عندما يحتوي تطبيق على نموذج عام، يظهر هنا.", + loadFailed: "تعذّر تحميل النماذج العامة. حدّث الصفحة للمحاولة مرة أخرى.", + 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: "تعذّرت قراءة النموذج.", + refusalShippedOff: "يوفّره تطبيقه مُعطّلًا، لذا لا يمكن تفعيله من هنا.", + refusalForbidden: "ليست لديك صلاحية تغيير إعدادات التطبيق.", + refusalServer: "رفض الخادم التغيير. حاول مرة أخرى أو تواصل مع مسؤول.", + switchedOnEarlierVersion: "تم تفعيل {{name}}. يبقى على الإصدار السابق {{version}} من التطبيق الذي خصّصته هذه البيئة؛ لاستخدام نموذج التطبيق الحالي، استعد الأصل في Studio.", + noSwitchPermission: "يتطلب تفعيل النماذج أو تعطيلها صلاحية تغيير إعدادات التطبيق، وهي ليست لديك.", + shippedOff: "معطّل (عطّله تطبيقه)", + statusUnknown: "غير معروف (تعذّرت قراءة نسخة التطبيق من هذا النموذج)", + }, 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 d677a8df6fe..56bdcd70e81 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -5897,6 +5897,43 @@ 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. Aktualisieren Sie, um es erneut zu versuchen.", + 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.", + refusalShippedOff: "die App liefert es ausgeschaltet aus, daher kann es hier nicht eingeschaltet werden.", + refusalForbidden: "Sie haben keine Berechtigung, die App-Konfiguration zu ändern.", + refusalServer: "der Server hat die Änderung abgelehnt. Versuchen Sie es erneut oder wenden Sie sich an einen Administrator.", + switchedOnEarlierVersion: "{{name}} ist eingeschaltet. Es bleibt bei der früheren App-Version {{version}}, die diese Umgebung angepasst hat; um das aktuelle Formular der App zu verwenden, stellen Sie das Original in Studio wieder her.", + noSwitchPermission: "Zum Ein- oder Ausschalten von Formularen ist die Berechtigung zum Ändern der App-Konfiguration nötig, die Sie nicht haben.", + shippedOff: "Aus (von der App ausgeschaltet)", + statusUnknown: "Unbekannt (die App-Version dieses Formulars 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 58771dbbf06..707b2ccdb7d 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -6833,6 +6833,43 @@ 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. Refresh to try again.", + 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.", + refusalShippedOff: "its app ships it switched off, so it cannot be switched on here.", + refusalForbidden: "you don't have permission to change app configuration.", + refusalServer: "the server refused the change. Try again, or ask an administrator.", + switchedOnEarlierVersion: "{{name}} is on. It stays on the app's earlier version {{version}}, which this environment customized; to take the app's current form, restore the original in Studio.", + noSwitchPermission: "Switching forms on or off needs permission to change app configuration, which you don't have.", + shippedOff: "Off (switched off by its app)", + statusUnknown: "Unknown (couldn't read its app's version of this form)", + }, 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 2e5084ff5dd..4950ee56371 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -6059,6 +6059,43 @@ 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. Actualice para intentarlo de nuevo.", + 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.", + refusalShippedOff: "su aplicación lo incluye desactivado, así que no se puede activar aquí.", + refusalForbidden: "no tiene permiso para cambiar la configuración de la aplicación.", + refusalServer: "el servidor rechazó el cambio. Inténtelo de nuevo o consulte a un administrador.", + switchedOnEarlierVersion: "{{name}} está activado. Sigue en la versión anterior {{version}} de la aplicación, que este entorno personalizó; para usar el formulario actual de la aplicación, restaure el original en Studio.", + noSwitchPermission: "Para activar o desactivar formularios se necesita permiso para cambiar la configuración de la aplicación, y usted no lo tiene.", + shippedOff: "Desactivado (por su aplicación)", + statusUnknown: "Desconocido (no se pudo leer la versión de la aplicación de este 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 54085bda3ca..a767360835d 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -6055,6 +6055,43 @@ 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. Actualisez pour réessayer.", + 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.", + refusalShippedOff: "son application le livre désactivé, il ne peut donc pas être activé ici.", + refusalForbidden: "vous n'avez pas l'autorisation de modifier la configuration de l'application.", + refusalServer: "le serveur a refusé la modification. Réessayez ou contactez un administrateur.", + switchedOnEarlierVersion: "{{name}} est activé. Il reste sur la version antérieure {{version}} de l'application, que cet environnement a personnalisée ; pour utiliser le formulaire actuel de l'application, restaurez l'original dans Studio.", + noSwitchPermission: "Activer ou désactiver des formulaires nécessite l'autorisation de modifier la configuration de l'application, que vous n'avez pas.", + shippedOff: "Désactivé (par son application)", + statusUnknown: "Inconnu (impossible de lire la version de ce formulaire dans son application)", + }, 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 39f47ede31e..18e5138feac 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -5898,6 +5898,43 @@ const ja = { linkedAt: "連携日時 {{at}}", disconnect: "連携を解除", }, + publicFormsSetup: { + title: "公開フォーム", + subtitle: "サインインせずに誰でも入力できるフォーム(Web サイトのお問い合わせフォームなど)。送信ごとにレコードが作成されます。", + notAllowed: "公開フォームを管理できるのはシステム管理者のみです。", + designHint: "フォームをオフにすると送信を受け付けなくなり、そのアドレスは開けなくなります。フォームの設計は Studio で行います。", + refresh: "更新", + emptyTitle: "公開フォームはまだありません", + emptyBody: "公開フォームは Studio で設計します。アプリに公開フォームがあると、ここに表示されます。", + loadFailed: "公開フォームを読み込めませんでした。更新して再試行してください。", + 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: "フォームを読み込めませんでした。", + refusalShippedOff: "所属アプリがオフの状態で提供しているため、ここではオンにできません。", + refusalForbidden: "アプリ構成を変更する権限がありません。", + refusalServer: "サーバーが変更を拒否しました。再試行するか、管理者に問い合わせてください。", + switchedOnEarlierVersion: "{{name}} をオンにしました。この環境でカスタマイズしたアプリの以前のバージョン {{version}} のままです。アプリの現在のフォームを使うには、Studio で元に戻してください。", + noSwitchPermission: "フォームのオン/オフにはアプリ構成を変更する権限が必要ですが、お持ちではありません。", + shippedOff: "オフ(アプリによりオフ)", + statusUnknown: "不明(所属アプリのこのフォームを読み込めませんでした)", + }, 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 b564bd532b9..5118b41718e 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -5895,6 +5895,43 @@ const ko = { linkedAt: "연결 시각 {{at}}", disconnect: "연결 해제", }, + publicFormsSetup: { + title: "공개 양식", + subtitle: "로그인하지 않고 누구나 작성할 수 있는 양식(예: 웹사이트의 문의 양식). 제출할 때마다 레코드가 생성됩니다.", + notAllowed: "시스템 관리자만 공개 양식을 관리할 수 있습니다.", + designHint: "양식을 끄면 더 이상 제출을 받지 않으며 해당 주소도 열리지 않습니다. 양식 디자인은 Studio에서 합니다.", + refresh: "새로 고침", + emptyTitle: "아직 공개 양식이 없습니다", + emptyBody: "공개 양식은 Studio에서 디자인합니다. 앱에 공개 양식이 있으면 여기에 표시됩니다.", + loadFailed: "공개 양식을 불러오지 못했습니다. 새로 고쳐 다시 시도하세요.", + 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: "양식을 읽지 못했습니다.", + refusalShippedOff: "소속 앱이 꺼진 상태로 제공하므로 여기서 켤 수 없습니다.", + refusalForbidden: "앱 구성을 변경할 권한이 없습니다.", + refusalServer: "서버가 변경을 거부했습니다. 다시 시도하거나 관리자에게 문의하세요.", + switchedOnEarlierVersion: "{{name}}을(를) 켰습니다. 이 환경에서 사용자 지정한 앱의 이전 버전 {{version}}이(가) 계속 사용됩니다. 앱의 현재 양식을 사용하려면 Studio에서 원본으로 복원하세요.", + noSwitchPermission: "양식을 켜거나 끄려면 앱 구성을 변경할 권한이 필요하지만 권한이 없습니다.", + shippedOff: "꺼짐(앱에서 꺼짐)", + statusUnknown: "알 수 없음(앱의 이 양식을 읽지 못했습니다)", + }, 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 9ce1fc490fe..65b69d0956e 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -6054,6 +6054,43 @@ 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. Atualize para tentar novamente.", + 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.", + refusalShippedOff: "o aplicativo o entrega desativado, então ele não pode ser ativado aqui.", + refusalForbidden: "você não tem permissão para alterar a configuração do aplicativo.", + refusalServer: "o servidor recusou a alteração. Tente novamente ou fale com um administrador.", + switchedOnEarlierVersion: "{{name}} está ativado. Ele continua na versão anterior {{version}} do aplicativo, que este ambiente personalizou; para usar o formulário atual do aplicativo, restaure o original no Studio.", + noSwitchPermission: "Ativar ou desativar formulários exige permissão para alterar a configuração do aplicativo, que você não tem.", + shippedOff: "Desativado (pelo aplicativo)", + statusUnknown: "Desconhecido (não foi possível ler a versão do aplicativo deste 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 a090b1effd5..2d0d7e8e5be 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -6230,6 +6230,43 @@ const ru = { linkedAt: "Подключено {{at}}", disconnect: "Отключить", }, + publicFormsSetup: { + title: "Публичные формы", + subtitle: "Формы, которые любой может заполнить без входа, например форма обратной связи на вашем сайте. Каждая отправка создаёт запись.", + notAllowed: "Управлять публичными формами могут только системные администраторы.", + designHint: "Выключите форму, чтобы перестать принимать отправки; её адрес перестанет открываться. Формы проектируются в Studio.", + refresh: "Обновить", + emptyTitle: "Публичных форм пока нет", + emptyBody: "Публичные формы проектируются в Studio. Как только в приложении появится такая форма, она будет показана здесь.", + loadFailed: "Не удалось загрузить публичные формы. Обновите страницу, чтобы повторить попытку.", + 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: "не удалось прочитать форму.", + refusalShippedOff: "приложение поставляет её выключенной, поэтому здесь её нельзя включить.", + refusalForbidden: "у вас нет прав на изменение конфигурации приложения.", + refusalServer: "сервер отклонил изменение. Повторите попытку или обратитесь к администратору.", + switchedOnEarlierVersion: "Форма «{{name}}» включена. Она остаётся на прежней версии приложения {{version}}, которую настроила эта среда; чтобы использовать текущую форму приложения, восстановите оригинал в Studio.", + noSwitchPermission: "Чтобы включать и выключать формы, нужны права на изменение конфигурации приложения, а у вас их нет.", + shippedOff: "Выкл. (выключена приложением)", + statusUnknown: "Неизвестно (не удалось прочитать версию этой формы в приложении)", + }, 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 047925acf79..6b26717de9f 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -5956,6 +5956,43 @@ const zh = { linkedAt: "关联于 {{at}}", disconnect: "解除关联", }, + publicFormsSetup: { + title: "对外表单", + subtitle: "访客不用登录就能填写的表单,比如网站上的「联系我们」。每提交一次就新增一条记录。", + notAllowed: "只有系统管理员可以管理对外表单。", + designHint: "关掉一个表单就不再接收提交,它的地址也打不开了。表单的设计在 Studio 里做。", + refresh: "刷新", + emptyTitle: "还没有对外表单", + emptyBody: "对外表单在 Studio 里设计。应用里有了对外表单,就会列在这里。", + loadFailed: "无法加载对外表单。请刷新重试。", + 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: "读取表单失败。", + refusalShippedOff: "所属应用发布时就关闭了这个表单,无法在这里开启。", + refusalForbidden: "你没有修改应用配置的权限。", + refusalServer: "服务器拒绝了这次修改。请重试,或联系管理员。", + switchedOnEarlierVersion: "{{name}} 已开启。它仍沿用本环境定制时的应用旧版本 {{version}};如需使用应用当前版本的表单,请在 Studio 中恢复原样。", + noSwitchPermission: "开启或关闭表单需要修改应用配置的权限,你目前没有。", + shippedOff: "关闭(应用自带关闭)", + statusUnknown: "未知(无法读取所属应用中的此表单)", + }, 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 8a26b110441..773999edc49 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -5956,6 +5956,43 @@ const zhHant = { linkedAt: "關聯於 {{at}}", disconnect: "解除關聯", }, + publicFormsSetup: { + title: "對外表單", + subtitle: "訪客不用登入就能填寫的表單,比如網站上的「聯絡我們」。每提交一次就新增一條記錄。", + notAllowed: "只有系統管理員可以管理對外表單。", + designHint: "關掉一個表單就不再接收提交,它的地址也打不開了。表單的設計在 Studio 裡做。", + refresh: "重新整理", + emptyTitle: "還沒有對外表單", + emptyBody: "對外表單在 Studio 裡設計。應用裡有了對外表單,就會列在這裡。", + loadFailed: "無法載入對外表單。請重新整理重試。", + 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: "讀取表單失敗。", + refusalShippedOff: "所屬應用釋出時就關閉了這個表單,無法在這裡開啟。", + refusalForbidden: "你沒有修改應用配置的權限。", + refusalServer: "伺服器拒絕了這次修改。請重試,或聯絡管理員。", + switchedOnEarlierVersion: "{{name}} 已開啟。它仍沿用本環境定製時的應用舊版本 {{version}};如需使用應用當前版本的表單,請在 Studio 中恢復原樣。", + noSwitchPermission: "開啟或關閉表單需要修改應用配置的權限,你目前沒有。", + shippedOff: "關閉(應用自帶關閉)", + statusUnknown: "未知(無法讀取所屬應用中的此表單)", + }, slackSetup: { title: "Slack 私信", subtitle: "安裝組織自己的 Slack 應用,讓通知以 Slack 私信送達成員,並管理已關聯的人員。",