diff --git a/.changeset/34908-view-audience-picker.md b/.changeset/34908-view-audience-picker.md new file mode 100644 index 00000000000..de90ca4e0ff --- /dev/null +++ b/.changeset/34908-view-audience-picker.md @@ -0,0 +1,20 @@ +--- +'@objectstack/spec': patch +'@objectstack/platform-objects': patch +'@object-ui/app-shell': patch +'@object-ui/i18n': patch +--- + +feat(app-shell): 「Who sees this view」 — pick a shared view's or a dashboard's audience from the known capabilities, and see which positions will see it + +Clause-②: no +Metadata-protocol: none + +The audience gate is the existing, server-enforced `requiredPermissions` (all of the capabilities listed are required). The console now sets it from a closed list and shows who it reaches; no key, value or gate changes, and nothing is granted from the view (granting stays in Setup). + +- **`@object-ui/app-shell`.** The view switcher's in-place create card offers 「Who sees this view」 for a shared view: the capabilities the environment knows (declared, or granted by a permission set), each with the permission sets granting it, and a read-only preview of the positions whose permission sets grant every capability picked. The preview reads each position's sets from the server (`GET /meta/position?include=grants`, the sets the resolver grants its holders), never from a position's raw definition; a list served without them leaves the positions unknown. While a gate is picked, the card says it applies to its creator too. It starts from the open view's gate, which a new shared view used to inherit silently, and the pick replaces it; an empty pick writes no gate. A failed catalog read offers nothing to type. The shared hint no longer says every shared view is seen by everyone who can see the list. In Studio, the view panel's and the dashboard settings' audience row is the new `ref-multi:capability` picker: a closed list (no typed-name box when the catalog is unread, empty or failed), each option with its granting sets, and the same preview under it. The picker reads the catalog once its row is on screen, so an editor whose audience section stays closed sends no request. +- **`@objectstack/spec`.** The view and dashboard forms' `requiredPermissions` rows declare `widget: 'ref-multi:capability'` (the list is closed: a host with no catalog offers nothing to add). The view hint's last sentence now says only what holds on every carrier: the person setting the gate no longer sees the view in the list either. +- **`@objectstack/platform-objects`.** The `metadataForms` bundles carry the narrowed view hint (zh-CN, ja-JP and es-ES translated; the other locales the English source). +- **`@object-ui/i18n`.** The create card's new strings and the corrected shared hint, in all eleven console locales. + +Nothing to migrate. diff --git a/content/docs/permissions/capabilities.mdx b/content/docs/permissions/capabilities.mdx index 24ca2d9f60a..6f555a74631 100644 --- a/content/docs/permissions/capabilities.mdx +++ b/content/docs/permissions/capabilities.mdx @@ -197,6 +197,49 @@ the same way; a user who may edit the object still reads all of its list views, so a save of what they loaded keeps them. +## Showing a list view to some positions, without code + +An administrator can decide who sees a shared list view or a dashboard in the +console, with no source file. The gate is the same `requiredPermissions` as +above, and the console only sets it; it grants nothing. Granting stays in +Setup. + +1. **Have a capability for the audience.** Use one your app declares, or + declare one in the environment + ([below](#declaring-a-capability-in-the-environment)). One capability per + audience, for example `crm_deal.view_sales` for "the sales team's deal + view". +2. **Grant it in Setup.** Add the name to the `systemPermissions` of a + permission set, and give that set to the positions that should see the + view. A position carries no capability of its own: it passes on what its + permission sets grant. To show the view to two groups, grant the one + capability to both groups' sets. +3. **Pick it on the view.** In the view switcher, **Add view → Shared** offers + **Who sees this view**. For an existing view, Studio's view panel has + **Required permissions** under **Navigation & sharing**, and a dashboard's + settings have it under **Access**. Both list only the capabilities the + environment knows, that is the ones declared and the ones a permission set + grants, with the sets granting each. You cannot type a name that matches + nothing there. + +Under the pick, the console previews the positions that will see the view: the +positions whose permission sets grant **every** capability picked. It reads +which sets each position grants from the server, the sets the resolver grants +its holders, so a position that has been switched off reaches no one. The preview is +still advice, and the server stays the authority: it cannot name people who +hold a set directly rather than through a position, nor people who hold the +picked capabilities between several positions. A person holds everything each +of their positions grants, so two positions that each grant part of the pick +let their joint holders through. + + +**The gate applies to you too.** Pick a capability you do not hold, and the view +leaves your own view switcher as well. A view or a dashboard saved on its own +is then refused to you on every door, Studio included, until someone grants +you the capability. Grant it to your own permission set first if you still need +to open the view. + + ## One holder per name Each capability name has exactly one holder in the registry. When a package @@ -303,6 +346,7 @@ copy and the two would share one gate. Prefix your capability names. - [ ] The declaration is reachable from the stack (`capabilities: [...]`) or a `*.capability.ts` file - [ ] No other installed package declares the same name — the registry refuses a second holder at boot - [ ] Something actually **requires** the name (`requiredPermissions`), and something **grants** it (`systemPermissions`) +- [ ] A list view or dashboard gated from the console: its capability is granted to the positions' permission sets, and to your own if you still need to open it ## See also diff --git a/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts index 77aa571ceb3..14e8aec4167 100644 --- a/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts @@ -1661,7 +1661,7 @@ export const arMetadataForms: NonNullable = { }, requiredPermissions: { label: "Required Permissions", - helpText: "Who sees this view: the capabilities a person must hold, every one listed. Permission sets grant capabilities, and a position passes on the ones its permission sets grant. Leave it empty and everyone who can see the list sees this view. To show it to several groups, pick one capability and grant it to each group's permission set. The server enforces it: anyone else does not find the view in the list and is refused if they open it directly. The gate applies to you too: list a capability you do not hold, or misspell one, and you can no longer open this view either." + helpText: "Who sees this view: the capabilities a person must hold, every one listed. Permission sets grant capabilities, and a position passes on the ones its permission sets grant. Leave it empty and everyone who can see the list sees this view. To show it to several groups, pick one capability and grant it to each group's permission set. The server enforces it: anyone else does not find the view in the list and is refused if they open it directly. The gate applies to you too: list a capability you do not hold, or misspell one, and you no longer see this view in the list either." }, object: { label: "الكائن" diff --git a/packages/platform-objects/src/apps/translations/ar.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/ar.source-hashes.generated.ts index 1aa6247cb11..425cd5e3b85 100644 --- a/packages/platform-objects/src/apps/translations/ar.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/ar.source-hashes.generated.ts @@ -67,7 +67,7 @@ export const arGeneratedSourceHashes: Readonly> = { "metadataForms.report.fields.exportOptions.formats.label": "193cd91818d64ef7", "metadataForms.report.fields.exportOptions.includeHeaders.helpText": "44cbc80015ff051d", "metadataForms.report.fields.exportOptions.includeHeaders.label": "f114a4778c9727ae", - "metadataForms.view.fields.requiredPermissions.helpText": "c4599be2ffa06c02", + "metadataForms.view.fields.requiredPermissions.helpText": "824ea3479e2e607a", "metadataForms.view.fields.requiredPermissions.label": "a47b2168b71f5e68", "objects.sys_email.fields.message_id.label": "14cd089a4062f4b1", "objects.sys_email_template.fields.package_id.help": "e1f8cc4d0105cedc", diff --git a/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts index 1918baa469d..8684c74ca38 100644 --- a/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts @@ -1661,7 +1661,7 @@ export const deMetadataForms: NonNullable = { }, requiredPermissions: { label: "Required Permissions", - helpText: "Who sees this view: the capabilities a person must hold, every one listed. Permission sets grant capabilities, and a position passes on the ones its permission sets grant. Leave it empty and everyone who can see the list sees this view. To show it to several groups, pick one capability and grant it to each group's permission set. The server enforces it: anyone else does not find the view in the list and is refused if they open it directly. The gate applies to you too: list a capability you do not hold, or misspell one, and you can no longer open this view either." + helpText: "Who sees this view: the capabilities a person must hold, every one listed. Permission sets grant capabilities, and a position passes on the ones its permission sets grant. Leave it empty and everyone who can see the list sees this view. To show it to several groups, pick one capability and grant it to each group's permission set. The server enforces it: anyone else does not find the view in the list and is refused if they open it directly. The gate applies to you too: list a capability you do not hold, or misspell one, and you no longer see this view in the list either." }, object: { label: "Objekt" diff --git a/packages/platform-objects/src/apps/translations/de.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/de.source-hashes.generated.ts index 16eebeb04a9..0a35ec33d1c 100644 --- a/packages/platform-objects/src/apps/translations/de.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/de.source-hashes.generated.ts @@ -128,7 +128,7 @@ export const deGeneratedSourceHashes: Readonly> = { "metadataForms.view.fields.kanban.label": "dd95c452aa71459e", "metadataForms.view.fields.name.label": "5274417ff1ccaf01", "metadataForms.view.fields.navigation.label": "51cd9fc784a9643f", - "metadataForms.view.fields.requiredPermissions.helpText": "c4599be2ffa06c02", + "metadataForms.view.fields.requiredPermissions.helpText": "824ea3479e2e607a", "metadataForms.view.fields.requiredPermissions.label": "a47b2168b71f5e68", "metadataForms.view.fields.userActions.filter.label": "802895ec427fc6af", "metadataForms.view.fields.userFilters.element.label": "e480e4fe57239c98", diff --git a/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts index 25f673b19c7..d67367073e1 100644 --- a/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts @@ -1661,7 +1661,7 @@ export const enMetadataForms: NonNullable = { }, requiredPermissions: { label: "Required Permissions", - helpText: "Who sees this view: the capabilities a person must hold, every one listed. Permission sets grant capabilities, and a position passes on the ones its permission sets grant. Leave it empty and everyone who can see the list sees this view. To show it to several groups, pick one capability and grant it to each group's permission set. The server enforces it: anyone else does not find the view in the list and is refused if they open it directly. The gate applies to you too: list a capability you do not hold, or misspell one, and you can no longer open this view either." + helpText: "Who sees this view: the capabilities a person must hold, every one listed. Permission sets grant capabilities, and a position passes on the ones its permission sets grant. Leave it empty and everyone who can see the list sees this view. To show it to several groups, pick one capability and grant it to each group's permission set. The server enforces it: anyone else does not find the view in the list and is refused if they open it directly. The gate applies to you too: list a capability you do not hold, or misspell one, and you no longer see this view in the list either." }, object: { label: "Object" diff --git a/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts index ca94e15f7bd..7cb179a9236 100644 --- a/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts @@ -1661,7 +1661,7 @@ export const esESMetadataForms: NonNullable = }, requiredPermissions: { label: "Permisos requeridos", - helpText: "Quién ve esta vista: las capacidades que una persona debe tener, todas las indicadas. Los conjuntos de permisos otorgan capacidades, y un puesto transmite las que otorgan sus conjuntos de permisos. Si se deja vacío, todos los que pueden ver la lista ven esta vista. Para mostrarla a varios grupos, elija una capacidad y otórguela al conjunto de permisos de cada grupo. El servidor lo aplica: los demás no encuentran la vista en la lista y se les deniega si la abren directamente. Esto también se aplica a usted: si indica una capacidad que no tiene, o la escribe mal, usted tampoco podrá volver a abrir esta vista." + helpText: "Quién ve esta vista: las capacidades que una persona debe tener, todas las indicadas. Los conjuntos de permisos otorgan capacidades, y un puesto transmite las que otorgan sus conjuntos de permisos. Si se deja vacío, todos los que pueden ver la lista ven esta vista. Para mostrarla a varios grupos, elija una capacidad y otórguela al conjunto de permisos de cada grupo. El servidor lo aplica: los demás no encuentran la vista en la lista y se les deniega si la abren directamente. Esto también se aplica a usted: si indica una capacidad que no tiene, o la escribe mal, usted tampoco verá esta vista en la lista." }, object: { label: "Objeto" diff --git a/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts index afa5dd31ca6..e2633b32210 100644 --- a/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts @@ -1661,7 +1661,7 @@ export const frMetadataForms: NonNullable = { }, requiredPermissions: { label: "Required Permissions", - helpText: "Who sees this view: the capabilities a person must hold, every one listed. Permission sets grant capabilities, and a position passes on the ones its permission sets grant. Leave it empty and everyone who can see the list sees this view. To show it to several groups, pick one capability and grant it to each group's permission set. The server enforces it: anyone else does not find the view in the list and is refused if they open it directly. The gate applies to you too: list a capability you do not hold, or misspell one, and you can no longer open this view either." + helpText: "Who sees this view: the capabilities a person must hold, every one listed. Permission sets grant capabilities, and a position passes on the ones its permission sets grant. Leave it empty and everyone who can see the list sees this view. To show it to several groups, pick one capability and grant it to each group's permission set. The server enforces it: anyone else does not find the view in the list and is refused if they open it directly. The gate applies to you too: list a capability you do not hold, or misspell one, and you no longer see this view in the list either." }, object: { label: "Objet" diff --git a/packages/platform-objects/src/apps/translations/fr.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/fr.source-hashes.generated.ts index ebd32ddebcd..5edcd428bcb 100644 --- a/packages/platform-objects/src/apps/translations/fr.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/fr.source-hashes.generated.ts @@ -164,7 +164,7 @@ export const frGeneratedSourceHashes: Readonly> = { "metadataForms.view.fields.navigation.label": "51cd9fc784a9643f", "metadataForms.view.fields.navigation.mode.label": "74dde5013435abdc", "metadataForms.view.fields.pagination.label": "309131fbaca258df", - "metadataForms.view.fields.requiredPermissions.helpText": "c4599be2ffa06c02", + "metadataForms.view.fields.requiredPermissions.helpText": "824ea3479e2e607a", "metadataForms.view.fields.requiredPermissions.label": "a47b2168b71f5e68", "metadataForms.view.fields.selection.type.label": "901bb552898b2cab", "metadataForms.view.fields.type.label": "901bb552898b2cab", diff --git a/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts index 921d9a48fef..3c03010502a 100644 --- a/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts @@ -1661,7 +1661,7 @@ export const jaJPMetadataForms: NonNullable = }, requiredPermissions: { label: "必要な権限", - helpText: "このビューを見られる人:閲覧者が保持する必要のあるケイパビリティで、列挙したものはすべて必要です。ケイパビリティは権限セットが付与し、ポジションはその権限セットが付与するものを引き継ぎます。空にすると、リストを見られる全員がこのビューを見られます。複数のグループに見せるには、ケイパビリティを 1 つ選び、各グループの権限セットに付与してください。サーバーが強制します:それ以外の人にはリストにこのビューが表示されず、直接開いても拒否されます。これはあなた自身にも適用されます:保持していないケイパビリティや綴りを誤ったケイパビリティを指定すると、あなたもこのビューを開けなくなります。" + helpText: "このビューを見られる人:閲覧者が保持する必要のあるケイパビリティで、列挙したものはすべて必要です。ケイパビリティは権限セットが付与し、ポジションはその権限セットが付与するものを引き継ぎます。空にすると、リストを見られる全員がこのビューを見られます。複数のグループに見せるには、ケイパビリティを 1 つ選び、各グループの権限セットに付与してください。サーバーが強制します:それ以外の人にはリストにこのビューが表示されず、直接開いても拒否されます。これはあなた自身にも適用されます:保持していないケイパビリティや綴りを誤ったケイパビリティを指定すると、あなたのリストにもこのビューは表示されなくなります。" }, object: { label: "オブジェクト" diff --git a/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts index 671ad38fc06..f8f4e16e934 100644 --- a/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts @@ -1661,7 +1661,7 @@ export const koMetadataForms: NonNullable = { }, requiredPermissions: { label: "Required Permissions", - helpText: "Who sees this view: the capabilities a person must hold, every one listed. Permission sets grant capabilities, and a position passes on the ones its permission sets grant. Leave it empty and everyone who can see the list sees this view. To show it to several groups, pick one capability and grant it to each group's permission set. The server enforces it: anyone else does not find the view in the list and is refused if they open it directly. The gate applies to you too: list a capability you do not hold, or misspell one, and you can no longer open this view either." + helpText: "Who sees this view: the capabilities a person must hold, every one listed. Permission sets grant capabilities, and a position passes on the ones its permission sets grant. Leave it empty and everyone who can see the list sees this view. To show it to several groups, pick one capability and grant it to each group's permission set. The server enforces it: anyone else does not find the view in the list and is refused if they open it directly. The gate applies to you too: list a capability you do not hold, or misspell one, and you no longer see this view in the list either." }, object: { label: "객체" diff --git a/packages/platform-objects/src/apps/translations/ko.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/ko.source-hashes.generated.ts index b440ec908a1..8de3bbc85df 100644 --- a/packages/platform-objects/src/apps/translations/ko.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/ko.source-hashes.generated.ts @@ -67,7 +67,7 @@ export const koGeneratedSourceHashes: Readonly> = { "metadataForms.report.fields.exportOptions.formats.label": "193cd91818d64ef7", "metadataForms.report.fields.exportOptions.includeHeaders.helpText": "44cbc80015ff051d", "metadataForms.report.fields.exportOptions.includeHeaders.label": "f114a4778c9727ae", - "metadataForms.view.fields.requiredPermissions.helpText": "c4599be2ffa06c02", + "metadataForms.view.fields.requiredPermissions.helpText": "824ea3479e2e607a", "metadataForms.view.fields.requiredPermissions.label": "a47b2168b71f5e68", "objects.sys_email.fields.message_id.label": "14cd089a4062f4b1", "objects.sys_email_template.fields.id.label": "00b0385c9c152888", diff --git a/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts index a9c2c2e0944..2149b6f7354 100644 --- a/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts @@ -1661,7 +1661,7 @@ export const ptBRMetadataForms: NonNullable = }, requiredPermissions: { label: "Required Permissions", - helpText: "Who sees this view: the capabilities a person must hold, every one listed. Permission sets grant capabilities, and a position passes on the ones its permission sets grant. Leave it empty and everyone who can see the list sees this view. To show it to several groups, pick one capability and grant it to each group's permission set. The server enforces it: anyone else does not find the view in the list and is refused if they open it directly. The gate applies to you too: list a capability you do not hold, or misspell one, and you can no longer open this view either." + helpText: "Who sees this view: the capabilities a person must hold, every one listed. Permission sets grant capabilities, and a position passes on the ones its permission sets grant. Leave it empty and everyone who can see the list sees this view. To show it to several groups, pick one capability and grant it to each group's permission set. The server enforces it: anyone else does not find the view in the list and is refused if they open it directly. The gate applies to you too: list a capability you do not hold, or misspell one, and you no longer see this view in the list either." }, object: { label: "Objeto" diff --git a/packages/platform-objects/src/apps/translations/pt-BR.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/pt-BR.source-hashes.generated.ts index 9a8c8163394..5eca386c3e6 100644 --- a/packages/platform-objects/src/apps/translations/pt-BR.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/pt-BR.source-hashes.generated.ts @@ -84,7 +84,7 @@ export const ptBRGeneratedSourceHashes: Readonly> = { "metadataForms.report.fields.exportOptions.includeHeaders.label": "f114a4778c9727ae", "metadataForms.view.fields.gantt.label": "57ffc6ef520edfc5", "metadataForms.view.fields.kanban.label": "dd95c452aa71459e", - "metadataForms.view.fields.requiredPermissions.helpText": "c4599be2ffa06c02", + "metadataForms.view.fields.requiredPermissions.helpText": "824ea3479e2e607a", "metadataForms.view.fields.requiredPermissions.label": "a47b2168b71f5e68", "metadataForms.view.sections.gantt.label": "57ffc6ef520edfc5", "metadataForms.view.sections.kanban.label": "dd95c452aa71459e", diff --git a/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts index bd40396d57d..d538390d9d0 100644 --- a/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts @@ -1661,7 +1661,7 @@ export const ruMetadataForms: NonNullable = { }, requiredPermissions: { label: "Required Permissions", - helpText: "Who sees this view: the capabilities a person must hold, every one listed. Permission sets grant capabilities, and a position passes on the ones its permission sets grant. Leave it empty and everyone who can see the list sees this view. To show it to several groups, pick one capability and grant it to each group's permission set. The server enforces it: anyone else does not find the view in the list and is refused if they open it directly. The gate applies to you too: list a capability you do not hold, or misspell one, and you can no longer open this view either." + helpText: "Who sees this view: the capabilities a person must hold, every one listed. Permission sets grant capabilities, and a position passes on the ones its permission sets grant. Leave it empty and everyone who can see the list sees this view. To show it to several groups, pick one capability and grant it to each group's permission set. The server enforces it: anyone else does not find the view in the list and is refused if they open it directly. The gate applies to you too: list a capability you do not hold, or misspell one, and you no longer see this view in the list either." }, object: { label: "Объект" diff --git a/packages/platform-objects/src/apps/translations/ru.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/ru.source-hashes.generated.ts index 1a970de4508..2ecfaaa7130 100644 --- a/packages/platform-objects/src/apps/translations/ru.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/ru.source-hashes.generated.ts @@ -67,7 +67,7 @@ export const ruGeneratedSourceHashes: Readonly> = { "metadataForms.report.fields.exportOptions.formats.label": "193cd91818d64ef7", "metadataForms.report.fields.exportOptions.includeHeaders.helpText": "44cbc80015ff051d", "metadataForms.report.fields.exportOptions.includeHeaders.label": "f114a4778c9727ae", - "metadataForms.view.fields.requiredPermissions.helpText": "c4599be2ffa06c02", + "metadataForms.view.fields.requiredPermissions.helpText": "824ea3479e2e607a", "metadataForms.view.fields.requiredPermissions.label": "a47b2168b71f5e68", "objects.sys_email.fields.message_id.label": "14cd089a4062f4b1", "objects.sys_email_template.fields.id.label": "00b0385c9c152888", diff --git a/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts index c711030e0ba..f3587d2b26f 100644 --- a/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts @@ -1661,7 +1661,7 @@ export const zhCNMetadataForms: NonNullable = }, requiredPermissions: { label: "所需权限", - helpText: "谁能看此视图:查看者必须持有的能力,列出的每一项都要具备。能力由权限集授予,岗位通过其权限集获得这些能力。留空则所有能看到该列表的人都能看到此视图。要给多类人看,请选一个能力并授予每类人的权限集。由服务器强制执行:其他人在列表中看不到此视图,直接打开也会被拒绝。这也适用于你自己:列出你未持有或拼错的能力后,你也将无法再打开此视图。" + helpText: "谁能看此视图:查看者必须持有的能力,列出的每一项都要具备。能力由权限集授予,岗位通过其权限集获得这些能力。留空则所有能看到该列表的人都能看到此视图。要给多类人看,请选一个能力并授予每类人的权限集。由服务器强制执行:其他人在列表中看不到此视图,直接打开也会被拒绝。这也适用于你自己:列出你未持有或拼错的能力后,你在列表中也将看不到此视图。" }, object: { label: "对象" diff --git a/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts index 34af280d9f6..123b80915bb 100644 --- a/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts @@ -1661,7 +1661,7 @@ export const zhHantMetadataForms: NonNullable }, requiredPermissions: { label: "Required Permissions", - helpText: "Who sees this view: the capabilities a person must hold, every one listed. Permission sets grant capabilities, and a position passes on the ones its permission sets grant. Leave it empty and everyone who can see the list sees this view. To show it to several groups, pick one capability and grant it to each group's permission set. The server enforces it: anyone else does not find the view in the list and is refused if they open it directly. The gate applies to you too: list a capability you do not hold, or misspell one, and you can no longer open this view either." + helpText: "Who sees this view: the capabilities a person must hold, every one listed. Permission sets grant capabilities, and a position passes on the ones its permission sets grant. Leave it empty and everyone who can see the list sees this view. To show it to several groups, pick one capability and grant it to each group's permission set. The server enforces it: anyone else does not find the view in the list and is refused if they open it directly. The gate applies to you too: list a capability you do not hold, or misspell one, and you no longer see this view in the list either." }, object: { label: "物件" diff --git a/packages/platform-objects/src/apps/translations/zh-Hant.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/zh-Hant.source-hashes.generated.ts index dc54a98d4f4..de71721e4db 100644 --- a/packages/platform-objects/src/apps/translations/zh-Hant.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/zh-Hant.source-hashes.generated.ts @@ -61,7 +61,7 @@ export const zhHantGeneratedSourceHashes: Readonly> = { "metadataForms.report.fields.exportOptions.formats.label": "193cd91818d64ef7", "metadataForms.report.fields.exportOptions.includeHeaders.helpText": "44cbc80015ff051d", "metadataForms.report.fields.exportOptions.includeHeaders.label": "f114a4778c9727ae", - "metadataForms.view.fields.requiredPermissions.helpText": "c4599be2ffa06c02", + "metadataForms.view.fields.requiredPermissions.helpText": "824ea3479e2e607a", "metadataForms.view.fields.requiredPermissions.label": "a47b2168b71f5e68", "objects.sys_email.fields.message_id.label": "14cd089a4062f4b1", "objects.sys_email_template.fields.id.label": "00b0385c9c152888", diff --git a/packages/spec/src/ui/dashboard.metadata-form.ts b/packages/spec/src/ui/dashboard.metadata-form.ts index 91cb5891458..c3360881d98 100644 --- a/packages/spec/src/ui/dashboard.metadata-form.ts +++ b/packages/spec/src/ui/dashboard.metadata-form.ts @@ -148,7 +148,8 @@ export const dashboardForm = defineMetadataForm({ { // The audience gate (#34908, ruling 7103739693 letter B): the existing, // server-enforced `requiredPermissions`, given an authoring row — the - // list view's row in `view.metadata-form.ts`, worded for a dashboard. + // list view's row in `view.metadata-form.ts` (the same `ref-multi:capability` + // picker and position preview), worded for a dashboard. label: 'Access', description: 'Who can see this dashboard.', collapsible: true, @@ -156,7 +157,7 @@ export const dashboardForm = defineMetadataForm({ fields: [ { field: 'requiredPermissions', - widget: 'string-tags', + widget: 'ref-multi:capability', helpText: 'Who sees this dashboard: the capabilities a person must hold, every one listed. Permission sets ' + 'grant capabilities, and a position passes on the ones its permission sets grant. Leave it empty and ' + 'everyone sees this dashboard. To show it to several groups, pick one capability and grant it to each ' diff --git a/packages/spec/src/ui/view.metadata-form.ts b/packages/spec/src/ui/view.metadata-form.ts index b6a4450d816..b8aea7e18ac 100644 --- a/packages/spec/src/ui/view.metadata-form.ts +++ b/packages/spec/src/ui/view.metadata-form.ts @@ -320,15 +320,25 @@ export const viewForm = defineMetadataForm({ // second audience key. The hint restates the clauses of // `AUDIENCE_REQUIRED_PERMISSIONS_DESCRIPTION` (all of them, no any-of // form, enforced by the server) for the administrator who sets it. + // `ref-multi:capability` offers only the capabilities the environment + // knows (declared, or granted by a permission set) and previews which + // positions the picked set reaches; the list is closed, so a host that + // feeds no catalog offers nothing to add. It writes the names only — + // granting stays in Setup. + // The last sentence says what holds for the person setting the gate on + // every carrier: the switcher drops the view for them too. It does not + // promise the designer refuses it: a view item is refused on every door, + // but an entry kept in its object's view set stays open to that set's + // editors there. { field: 'requiredPermissions', - widget: 'string-tags', + widget: 'ref-multi:capability', helpText: 'Who sees this view: the capabilities a person must hold, every one listed. Permission sets grant ' + 'capabilities, and a position passes on the ones its permission sets grant. Leave it empty and everyone ' + 'who can see the list sees this view. To show it to several groups, pick one capability and grant it to ' + 'each group\'s permission set. The server enforces it: anyone else does not find the view in the list and ' + 'is refused if they open it directly. The gate applies to you too: list a capability you do not hold, or ' - + 'misspell one, and you can no longer open this view either.', + + 'misspell one, and you no longer see this view in the list either.', }, ], }, diff --git a/ui/packages/app-shell/src/views/CreateViewDialog.tsx b/ui/packages/app-shell/src/views/CreateViewDialog.tsx index 01876e3f11e..2cdd6fee390 100644 --- a/ui/packages/app-shell/src/views/CreateViewDialog.tsx +++ b/ui/packages/app-shell/src/views/CreateViewDialog.tsx @@ -52,6 +52,9 @@ import type { ListViewVisualization } from '@object-ui/core'; import { slugify } from './metadata-admin/createDerive.js'; import { romanizeHan, useHanRomanizer } from './metadata-admin/romanizeHan.js'; import { datasetOptionLabel, useObjectDatasetBinding } from './studio-design/objectDatasets.js'; +import { usePickerLoad } from './metadata-admin/loadState.js'; +import type { CapabilityAudience } from './capabilityAudience.js'; +import { ViewAudiencePicker } from './ViewAudiencePicker.js'; import { deriveFieldOptions, isImageLikeField, @@ -1082,6 +1085,14 @@ export interface InPlaceViewRequest { scope: 'personal' | 'shared'; /** Carry the list's unsaved filters and sort into the new view. */ includeCurrent: boolean; + /** + * objectstack#34908 — a shared view's audience gate as the card's picker + * left it: the capabilities a reader must all hold (`[]` = no gate). Present + * only when the card offered the picker, and then it is authoritative over + * any gate the new view would otherwise inherit from the open one; absent, + * the host builds the body as before. + */ + requiredPermissions?: string[]; } export interface CreateViewCardProps { @@ -1112,6 +1123,15 @@ export interface CreateViewCardProps { onCreate: (request: InPlaceViewRequest) => boolean | Promise; /** Back to the view list. */ onBack: () => void; + /** + * objectstack#34908 — read the audience catalog (the capabilities the + * environment knows, the permission sets granting each, the positions + * holding them). Given ⇒ the shared scope offers 「Who sees this view」; + * read once the reader picks Shared. Absent ⇒ no picker. + */ + loadAudience?: () => Promise; + /** The open view's gate, the picker's starting value (the new view starts from the open one). */ + initialRequiredPermissions?: readonly string[]; } /** @@ -1138,6 +1158,8 @@ export function CreateViewCard({ shownFields, onCreate, onBack, + loadAudience, + initialRequiredPermissions, }: CreateViewCardProps) { const { t } = useObjectTranslation(); const allTypes = useMemo(() => buildViewTypeMeta(t), [t]); @@ -1159,6 +1181,12 @@ export function CreateViewCard({ const [includeCurrent, setIncludeCurrent] = useState(true); const [scope, setScope] = useState<'personal' | 'shared'>(canCreatePersonal ? 'personal' : 'shared'); const [submitting, setSubmitting] = useState(false); + const [requiredPermissions, setRequiredPermissions] = useState(() => [...(initialRequiredPermissions ?? [])]); + const offersAudience = scope === 'shared' && !!loadAudience; + const audience = usePickerLoad(useMemo( + () => (offersAudience ? loadAudience! : null), + [offersAudience, loadAudience], + )); const submittingRef = useRef(false); const baseId = useId(); // Loads the pinyin dictionary for a Chinese name, so the key reads as it. @@ -1202,7 +1230,12 @@ export function CreateViewCard({ submittingRef.current = true; setSubmitting(true); try { - await onCreate({ config, scope, includeCurrent: hasUnsavedConditions && includeCurrent }); + await onCreate({ + config, + scope, + includeCurrent: hasUnsavedConditions && includeCurrent, + ...(offersAudience ? { requiredPermissions } : {}), + }); } finally { submittingRef.current = false; setSubmitting(false); @@ -1335,9 +1368,14 @@ export function CreateViewCard({ )} {scope === 'shared' && (

- {t('view.switcher.scopeHint', { defaultValue: 'Shared views are seen by everyone who can see this list' })} + {t('view.switcher.scopeHint', { + defaultValue: 'Shared views are seen by everyone who can see this list, unless the view is limited to the holders of a capability', + })}

)} + {offersAudience && ( + + )} + )} + + ); + })} + + )} + {audience.status === 'error' ? ( +

+ {t('view.switcher.audienceLoadFailed', { + defaultValue: 'The capabilities could not be loaded, so none can be added: {{message}}', + message: audience.message, + })} +

+ ) : loaded && options.length === 0 ? ( +

+ {t('view.switcher.audienceNone', { + defaultValue: 'No capability is defined yet. Capabilities are granted on permission sets, in Setup.', + })} +

+ ) : ( + + )} + {preview && ( +

+ {preview} +

+ )} + {/* The gate refuses a view item whole, its creator included, and the card + opens the view once it is created: say so while a gate is picked. */} + {value.length > 0 && ( +

+ {t('view.switcher.audienceSelf', { + defaultValue: 'This applies to you too: if you do not hold every capability picked, the view leaves your own list once it is created', + })} +

+ )} + + ); +} diff --git a/ui/packages/app-shell/src/views/capabilityAudience.ts b/ui/packages/app-shell/src/views/capabilityAudience.ts new file mode 100644 index 00000000000..f492ca3e24d --- /dev/null +++ b/ui/packages/app-shell/src/views/capabilityAudience.ts @@ -0,0 +1,185 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * Who a list view's (or a dashboard's) audience gate reaches — the catalog the + * "Who sees this view" pickers offer and the positions they preview + * (objectstack#34908, ruling 7103739693 letter B). + * + * The gate is the existing `requiredPermissions` (ruling 6095014058): a list of + * capabilities, every one required, enforced by the server's `/meta` read gate. + * A capability reaches a person through a permission set's `systemPermissions`, + * and a position passes on the capabilities of the permission sets it grants + * (ADR-0131 D3/D4) — it carries none of its own. So this + * module reads three registries and joins them; it writes nothing, and the + * view surface never grants (granting stays in Setup). + * + * The catalog is CLOSED: the names offered are the capabilities the registry + * declares (`defineCapability`) and every name a permission set grants — the + * same "known capability" set `validateCapabilityReferences` in + * `@objectstack/lint` resolves against — so an administrator, or an AI driving + * the console, cannot pick a name that matches nothing (a misspelled gate hides + * the view, or the dashboard, from everyone, its author included). + * + * The position preview reads which sets each position grants from the server: + * `GET /meta/position?include=grants` serves `_grantedPermissionSets`, the sets + * in force as the authorization resolver reads them (`describePositionGrants`), + * so the browser never joins a position's raw `permissionSets` itself. A + * position is listed when those sets grant EVERY picked capability between + * them. A list served without that decoration (no security service, a caller + * it is not described for) leaves the positions unknown, never guessed. The + * preview still cannot list people who hold a set directly rather than through + * a position; the server's gate stays the authority. + */ + +/** One capability the environment knows, as the pickers offer it. */ +export interface CapabilityOption { + /** The capability name — what `requiredPermissions` stores. */ + name: string; + /** The declaration's label, when the registry declares one. */ + label?: string; + /** The permission sets granting it, by name, sorted. */ + grantedBy: string[]; +} + +/** One position, with the capabilities its permission sets grant. */ +export interface PositionReach { + name: string; + label?: string; + /** Every capability granted by the sets the position grants in force, as served. */ + capabilities: string[]; +} + +/** The joined catalog: what may be picked, and which positions hold what. */ +export interface CapabilityAudience { + capabilities: CapabilityOption[]; + /** `null` when the positions' grants could not be read, or were not served: the preview then says so. */ + positions: PositionReach[] | null; +} + +type Row = Record; + +/** A list row as the metadata list read answers it: the item, or an envelope around it. */ +function unwrap(raw: unknown): Row | null { + const item = raw && typeof raw === 'object' && 'item' in (raw as Row) ? (raw as Row).item : raw; + return item && typeof item === 'object' ? (item as Row) : null; +} + +const nameOf = (row: Row): string | undefined => + typeof row.name === 'string' && row.name.trim() ? row.name : undefined; +const labelOf = (row: Row): string | undefined => + typeof row.label === 'string' && row.label.trim() ? row.label : undefined; +const stringsOf = (value: unknown): string[] => + Array.isArray(value) ? value.filter((v): v is string => typeof v === 'string' && v.trim() !== '') : []; + +/** + * The sets a position grants in force, as `?include=grants` serves them + * (`_grantedPermissionSets: [{ name, via }]`); `undefined` when the row carries + * no such decoration. + */ +function grantedSetsOf(row: Row): string[] | undefined { + const served = row._grantedPermissionSets; + if (!Array.isArray(served)) return undefined; + return served + .map((entry) => (entry && typeof entry === 'object' ? (entry as Row).name : undefined)) + .filter((name): name is string => typeof name === 'string' && name.trim() !== ''); +} + +/** + * Join the three registries' rows into the pickers' catalog. Pure: the rows + * are what `list('capability')`, `list('permission')` and + * `list('position', { include: 'grants' })` answered (`positions: null` when + * that read failed). A position row without the served grants makes the + * positions unknown (`null`): the preview is never computed from the raw + * `permissionSets` a position names. + */ +export function buildCapabilityAudience( + capabilityRows: readonly unknown[], + permissionSetRows: readonly unknown[], + positionRows: readonly unknown[] | null, +): CapabilityAudience { + const labels = new Map(); + for (const raw of capabilityRows) { + const row = unwrap(raw); + const name = row && nameOf(row); + if (row && name) labels.set(name, labelOf(row)); + } + const grantedBy = new Map>(); + const setGrants = new Map(); + for (const raw of permissionSetRows) { + const row = unwrap(raw); + const set = row && nameOf(row); + if (!row || !set) continue; + const caps = stringsOf(row.systemPermissions); + setGrants.set(set, caps); + for (const cap of caps) { + if (!grantedBy.has(cap)) grantedBy.set(cap, new Set()); + grantedBy.get(cap)!.add(set); + } + } + const names = new Set([...labels.keys(), ...grantedBy.keys()]); + const capabilities = [...names] + .sort((a, b) => a.localeCompare(b)) + .map((name) => ({ + name, + ...(labels.get(name) ? { label: labels.get(name) } : {}), + grantedBy: [...(grantedBy.get(name) ?? [])].sort((a, b) => a.localeCompare(b)), + })); + + const rows = positionRows === null + ? null + : positionRows.map(unwrap).filter((row): row is Row => !!row && !!nameOf(row)); + const positions = rows === null || rows.some((row) => grantedSetsOf(row) === undefined) + ? null + : rows + .map((row) => { + const caps = new Set(); + for (const set of grantedSetsOf(row)!) for (const cap of setGrants.get(set) ?? []) caps.add(cap); + return { + name: nameOf(row)!, + ...(labelOf(row) ? { label: labelOf(row) } : {}), + capabilities: [...caps].sort((a, b) => a.localeCompare(b)), + }; + }) + .sort((a, b) => a.name.localeCompare(b.name)); + + return { capabilities, positions }; +} + +/** + * The positions whose permission sets grant EVERY picked capability — who the + * gate lets in through one position alone. It is not the whole audience: a + * person's capabilities are the union over every position they hold (and any + * set granted to them directly), so a holder of two positions that each grant + * part of the pick passes the gate too. Empty `picked` is no gate: `null`, + * which a preview reads as "everyone who can see the list". + */ +export function positionsReached( + picked: readonly string[], + positions: readonly PositionReach[], +): PositionReach[] | null { + if (picked.length === 0) return null; + return positions.filter((p) => picked.every((cap) => p.capabilities.includes(cap))); +} + +/** The metadata reads {@link loadCapabilityAudience} makes — the console `MetadataClient`'s `list`. */ +export interface CapabilityAudienceSource { + list: (type: string, options?: { include?: 'grants' }) => Promise; +} + +/** + * Read the three registries and join them. A failed capability or permission + * set read fails the load (the pickers then say so, and offer nothing to add); a + * failed position read keeps the catalog and leaves `positions` `null`. + */ +export async function loadCapabilityAudience(source: CapabilityAudienceSource): Promise { + const [capabilities, permissionSets, positions] = await Promise.all([ + source.list('capability'), + source.list('permission'), + source.list('position', { include: 'grants' }).catch(() => null), + ]); + return buildCapabilityAudience( + Array.isArray(capabilities) ? capabilities : [], + Array.isArray(permissionSets) ? permissionSets : [], + positions === null ? null : Array.isArray(positions) ? positions : [], + ); +} diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.tsx index 685b5b1251e..6ec0447caef 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.tsx @@ -111,6 +111,7 @@ import { conditionSubjectsForMetadataType, } from './conditionScope.js'; import { mapLoaded, usePickerLoad } from './loadState.js'; +import { useCapabilityAudienceLoader } from './useCapabilityAudienceLoader.js'; import { useMetadataClient, useMetadataTypes, @@ -1398,6 +1399,14 @@ function MetadataResourceEditPageImpl({ ), ); + // objectstack#34908 — the audience catalog for the `ref-multi:capability` + // picker (a list view's or a dashboard's `requiredPermissions`): the + // capabilities the environment knows, the permission sets granting each and + // the positions holding them. The picker reads it through this loader once + // it is on screen, so a form without that row, or with it in a closed + // section, sends no request. + const loadCapabilityAudience = useCapabilityAudienceLoader(client); + // Component ids placed on the page being edited — fuels the `ref:component` // picker so a page variable's `source` (the component that writes it) is // chosen from the real canvas components, not a free-text id. Derived from @@ -1456,8 +1465,9 @@ function MetadataResourceEditPageImpl({ objectViews: objectViewsState, componentIds, permissionSets: permissionSetsState, + loadCapabilityAudience, }), - [type, objectsState, objectCatalogState, objectViewsState, componentIds, permissionSetsState], + [type, objectsState, objectCatalogState, objectViewsState, componentIds, permissionSetsState, loadCapabilityAudience], ); // Load layered view + initial draft. diff --git a/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.widgetLabelling.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.widgetLabelling.test.tsx index 9e3506b3921..d344ccc1f26 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.widgetLabelling.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.widgetLabelling.test.tsx @@ -156,6 +156,9 @@ const CASES: Case[] = [ { key: 'ref-multi:permission', schema: { type: 'array', title: TITLE, items: { type: 'string' } }, ctx: { permissionSets: loaded([{ name: 'sales_rep' }, { name: 'support_agent' }]) }, value: ['sales_rep'] }, // No `ctx` at all: the hosts that feed no catalog get the typed-name box inside the same named list (objectui#12126). { key: 'ref-multi:permission', variant: 'no-catalog', schema: { type: 'array', title: TITLE, items: { type: 'string' } }, value: ['sales_rep'] }, + { key: 'ref-multi:capability', schema: { type: 'array', title: TITLE, items: { type: 'string' } }, ctx: { capabilityAudience: loaded({ capabilities: [{ name: 'view_deal_sales', grantedBy: ['sales_rep_set'] }], positions: [] }) }, value: ['view_deal_sales'] }, + // No `ctx` at all: a closed list says the capabilities are not available here, inside the same named list (objectstack#34908). + { key: 'ref-multi:capability', variant: 'no-catalog', schema: { type: 'array', title: TITLE, items: { type: 'string' } }, value: ['view_deal_sales'] }, { key: 'filter-mode', schema: { type: 'object', title: TITLE }, ctx: { objectFields: loaded([{ name: 'status' }]) }, value: { element: 'dropdown' } }, { key: 'object-selector', schema: { type: 'string', title: TITLE }, ctx: { objectNames: loaded(['account']) }, value: 'account' }, { key: 'object-selector', variant: 'multiple', schema: { type: 'array', title: TITLE }, spec: { multiple: true }, ctx: { objectNames: loaded(['account', 'contact']) }, value: ['account'] }, diff --git a/ui/packages/app-shell/src/views/metadata-admin/inspectors/DashboardDefaultInspector.tsx b/ui/packages/app-shell/src/views/metadata-admin/inspectors/DashboardDefaultInspector.tsx index f054cf4e57d..0ff0a98458e 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/inspectors/DashboardDefaultInspector.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/inspectors/DashboardDefaultInspector.tsx @@ -42,6 +42,10 @@ import { AddWidgetPicker } from '../previews/AddWidgetPicker.js'; import { WIDGET_TYPE_META, UnknownWidgetIcon } from '../previews/widget-types.js'; import type { MetadataDefaultInspectorProps } from '../default-inspector-registry.js'; import { SchemaForm } from '../SchemaForm.js'; +import type { WidgetContext } from '../widgets.js'; +import { conditionScopeForMetadataType } from '../conditionScope.js'; +import { useMetadataClient } from '../useMetadata.js'; +import { useCapabilityAudienceLoader } from '../useCapabilityAudienceLoader.js'; import { fallbackFormPatch } from './fallbackFormPatch.js'; import type { FormViewSpec } from '../SchemaForm.js'; import { getDashboardForm, getDashboardSchema } from '../dashboard-schema.js'; @@ -187,6 +191,21 @@ export function DashboardDefaultInspector({ return { schema: merged.schema, form: stackSectionsForNarrowPanel(merged.form) }; }, [serverSchema, locale]); + // objectstack#34908 — the Access section's audience row is the + // `ref-multi:capability` picker; hand it the loader of the capability + // catalog and the positions preview, which it reads once the collapsed + // section is opened. This host handed down no `WidgetContext` before, so it + // now states the verdict the scope table rules for its type + // (`conditionScopeForMetadataType('dashboard')`) rather than inventing one; + // the dashboard form declares no `condition` row, so nothing renders + // differently for it. + const metadataClient = useMetadataClient(); + const loadCapabilityAudience = useCapabilityAudienceLoader(metadataClient); + const widgetContext = React.useMemo( + () => ({ conditionScope: conditionScopeForMetadataType('dashboard'), loadCapabilityAudience }), + [loadCapabilityAudience], + ); + return ( ( + () => ({ ...widgetContext, loadCapabilityAudience }), + [widgetContext, loadCapabilityAudience], + ); + /** Shallow-write a curated patch onto the variant. */ const writeVariant = (patch: Record) => { onPatch({ [variantKey]: { ...variant, ...patch } }); @@ -572,7 +585,7 @@ export function ViewVariantInspector({ value={variant} hiddenFields={['type', 'object', 'label']} readOnly={readOnly} - widgetContext={widgetContext} + widgetContext={formWidgetContext} issues={variantIssues} revealIssues={revealIssues} onInlineIssueFieldsChange={setFormIssueRows} diff --git a/ui/packages/app-shell/src/views/metadata-admin/metadata-form-zh-cn.ts b/ui/packages/app-shell/src/views/metadata-admin/metadata-form-zh-cn.ts index 6ccafe214f1..3c3c900d092 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/metadata-form-zh-cn.ts +++ b/ui/packages/app-shell/src/views/metadata-admin/metadata-form-zh-cn.ts @@ -501,7 +501,7 @@ export const ZH_CN_SPEC_FORMS: NonNullable = { 'navigation.width': { label: '宽度', helpText: '[已弃用 → size] 抽屉的像素 / 百分比宽度(如 "600px")。编写时无法预知客户端视口,因此选不出合适的像素宽度——请使用 `size` 档位。' }, sharing: { label: '共享', helpText: '视图共享配置:谁锁定了视图配置' }, 'sharing.lockedBy': { label: '锁定者', helpText: '锁定该视图配置的用户' }, - requiredPermissions: { label: '所需权限', helpText: '谁能看此视图:查看者必须持有的能力,列出的每一项都要具备。能力由权限集授予,岗位通过其权限集获得这些能力。留空则所有能看到该列表的人都能看到此视图。要给多类人看,请选一个能力并授予每类人的权限集。由服务器强制执行:其他人在列表中看不到此视图,直接打开也会被拒绝。这也适用于你自己:列出你未持有或拼错的能力后,你也将无法再打开此视图。' }, + requiredPermissions: { label: '所需权限', helpText: '谁能看此视图:查看者必须持有的能力,列出的每一项都要具备。能力由权限集授予,岗位通过其权限集获得这些能力。留空则所有能看到该列表的人都能看到此视图。要给多类人看,请选一个能力并授予每类人的权限集。由服务器强制执行:其他人在列表中看不到此视图,直接打开也会被拒绝。这也适用于你自己:列出你未持有或拼错的能力后,你在列表中也将看不到此视图。' }, }, }, app: { diff --git a/ui/packages/app-shell/src/views/metadata-admin/useCapabilityAudienceLoader.ts b/ui/packages/app-shell/src/views/metadata-admin/useCapabilityAudienceLoader.ts new file mode 100644 index 00000000000..ec1b760c95b --- /dev/null +++ b/ui/packages/app-shell/src/views/metadata-admin/useCapabilityAudienceLoader.ts @@ -0,0 +1,26 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The loader of the audience catalog the `ref-multi:capability` picker offers + * — the capabilities the environment knows, the permission sets granting each + * and the positions holding them (objectstack#34908). + * + * A host hands the loader down on {@link WidgetContext}; it does not call it. + * The picker itself reads the three registries, once it is on screen, so an + * editor whose audience row sits in a closed section, or whose form declares + * no such row, sends no request. The loader is stable per source, so the + * picker's read runs once per mount, not once per render. + */ + +import * as React from 'react'; +import { + loadCapabilityAudience, + type CapabilityAudience, + type CapabilityAudienceSource, +} from '../capabilityAudience.js'; + +export function useCapabilityAudienceLoader( + source: CapabilityAudienceSource | null | undefined, +): (() => Promise) | undefined { + return React.useMemo(() => (source ? () => loadCapabilityAudience(source) : undefined), [source]); +} diff --git a/ui/packages/app-shell/src/views/metadata-admin/widgets.tsx b/ui/packages/app-shell/src/views/metadata-admin/widgets.tsx index dc8da0f5929..e44f0b514c1 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/widgets.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/widgets.tsx @@ -54,9 +54,11 @@ import { toast } from 'sonner'; import { useObjectTranslation } from '@object-ui/i18n'; import { createAuthenticatedFetch } from '@object-ui/auth'; import { useMetadataLocale, t, tFormat } from './i18n.js'; +import type { SupportedLocale } from './i18n.js'; import { fieldHistoryChoiceOf, fieldHistoryOptions, fieldHistoryValueOf } from './fieldHistoryChoice.js'; import { isKnownViewType, viewTypeLabel } from './viewTypeLabels.js'; import type { FormFieldSpec, FormViewSpec, VisibilityPredicate } from './form-spec.js'; +import { positionsReached, type CapabilityAudience } from '../capabilityAudience.js'; import { usePredicateScope } from '@object-ui/react'; import { buildPredicateCtx, visibleOptions, type PredicateCtx } from './predicate.js'; import { foldFilterGroupToSpecRules, FILTER_FOLD_REFUSAL_KEYS } from '../viewFilterFold.js'; @@ -75,6 +77,7 @@ import { isLoading, loadErrorOf, loadedData, + mapLoaded, NOT_ASKED, offeredOptions, usePickerLoad, @@ -320,6 +323,22 @@ export interface WidgetContext { * does for a completed load that found no permission sets. */ permissionSets?: LoadState; + /** + * The capabilities the environment knows, joined with the permission sets + * granting each and the positions holding them — fuels the + * `ref-multi:capability` picker of an audience gate (`requiredPermissions` + * on a list view or a dashboard). Absent reads as {@link NOT_ASKED}, unless + * {@link WidgetContext.loadCapabilityAudience} is given. + */ + capabilityAudience?: LoadState; + /** + * Reads {@link WidgetContext.capabilityAudience} when it is not given: the + * `ref-multi:capability` picker calls it once it is on screen, so a host + * whose audience row sits in a closed section sends no request. Keep it + * stable (`useCapabilityAudienceLoader`), or the picker reads again on + * every render. + */ + loadCapabilityAudience?: () => Promise; } /* Stable empties for the arms that have no catalog to offer yet — `idle` and @@ -842,6 +861,18 @@ interface RefMultiRegistry { addPlaceholderKey: string; /** The add picker's placeholder once every declared item is picked. */ allAddedKey: string; + /** What the picked names mean, drawn under the list (the capability picker's position preview). */ + footer?: (selected: readonly string[], context: WidgetContext | undefined, locale: SupportedLocale) => React.ReactNode; + /** A second line under an offered item (the capability picker: the permission sets granting it). */ + detail?: (name: string, context: WidgetContext | undefined, locale: SupportedLocale) => string | undefined; + /** + * A CLOSED list (objectstack#34908): no typed-name box on any arm. A catalog + * nobody fed says `unreadKey`, a completed read that found nothing says + * `noneKey`, a failed read shows only the failure notice — so a name that + * matches nothing can never be added. Names already stored stay listed and + * removable on every arm. + */ + closed?: { unreadKey: string; noneKey: string }; } /** @@ -860,6 +891,11 @@ interface RefMultiRegistry { * unregistered hint falls back to; * - LOADED — an add picker offering the declared items not yet picked. * + * A registry declared `closed` (the capability picker, objectstack#34908) + * offers no text box on any arm: FAILED shows only its notice, `idle` and an + * empty load each say why nothing can be added, LOADING shows a disabled + * picker. + * * A stored name the LOADED catalog does not declare stays in the list, flagged * `(not found)`, so it is neither dropped nor read as a declared item * (objectui#8488). The flag is a claim about the registry's answer, so it is @@ -977,17 +1013,39 @@ function RefMultiWidget({ {remaining.map((o) => ( - - {o.label && o.label !== o.name && {o.label}} - {o.name} + + + {o.label && o.label !== o.name && {o.label}} + {o.name} + + {registry.detail?.(o.name, context, locale) && ( + + {registry.detail(o.name, context, locale)} + + )} ))} + ) : registry.closed ? ( + // A closed list offers no typed-name box: say why nothing can be + // added (a failed read already shows its notice above). + loadError ? null : loading ? ( + + ) : ( +

+ {t(declared ? registry.closed.noneKey : registry.closed.unreadKey, locale)} +

+ ) ) : ( freeform ))} + {registry.footer?.(selected, context, locale)} ); } @@ -1005,6 +1063,86 @@ function RefMultiPermissionWidget(props: WidgetProps) { return ; } +/** + * Who an audience gate lets in through a position: the positions whose + * permission sets grant every picked capability, read off the same catalog + * the picker offers. Advisory — the server's read gate is the authority. + */ +function CapabilityAudienceFooter({ + selected, + context, + locale, +}: { + selected: readonly string[]; + context: WidgetContext | undefined; + locale: SupportedLocale; +}) { + const state = context?.capabilityAudience ?? NOT_ASKED; + if (state.status !== 'loaded') return null; + const positions = state.data.positions; + let text: string; + if (selected.length === 0) text = t('engine.form.audienceEveryone', locale); + else if (positions === null) text = t('engine.form.audiencePositionsUnread', locale); + else { + const reached = positionsReached(selected, positions) ?? []; + text = reached.length === 0 + ? t('engine.form.audienceNoPosition', locale) + : tFormat('engine.form.audiencePositions', locale, { positions: reached.map((p) => p.label ?? p.name).join(', ') }); + } + return ( +

+ {text} +

+ ); +} + +/** + * The `ref-multi:capability` registration: the capabilities the environment + * knows (declared, or granted by a permission set), each offered with the + * permission sets granting it, and the positions the picked set reaches. The + * list is CLOSED: no arm offers a typed-name box, so a gate cannot name a + * capability nothing declares or grants (objectstack#34908). + */ +const CAPABILITY_REGISTRY: RefMultiRegistry = { + type: 'capability', + closed: { unreadKey: 'engine.form.capabilitiesUnread', noneKey: 'engine.form.capabilitiesNone' }, + detail: (name, context, locale) => { + const state = context?.capabilityAudience; + if (state?.status !== 'loaded') return undefined; + const sets = state.data.capabilities.find((c) => c.name === name)?.grantedBy ?? []; + return sets.length > 0 ? tFormat('engine.form.capabilityGrantedBy', locale, { sets: sets.join(', ') }) : undefined; + }, + catalog: (context) => + context?.capabilityAudience + ? mapLoaded(context.capabilityAudience, (audience) => + audience.capabilities.map((c) => ({ name: c.name, label: c.label })), + ) + : undefined, + addLabelKey: 'engine.form.addCapabilityPlain', + addPlaceholderKey: 'engine.form.addCapability', + allAddedKey: 'engine.form.allCapabilitiesAdded', + footer: (selected, context, locale) => ( + + ), +}; + +function RefMultiCapabilityWidget(props: WidgetProps) { + const { context } = props; + // The host hands down a loader, not a catalog: read it here, once the row is + // on screen. A catalog the host already holds wins. + const read = usePickerLoad( + context?.capabilityAudience ? null : context?.loadCapabilityAudience ?? null, + ); + const effective = React.useMemo( + () => + context?.capabilityAudience || !context?.loadCapabilityAudience + ? context + : { ...context, capabilityAudience: read }, + [context, read], + ); + return ; +} + /* -------------------------------------------------------------------------- */ /* object-selector — multi-select object picker */ /* -------------------------------------------------------------------------- */ @@ -3665,6 +3803,7 @@ export const WIDGETS = { 'ref:component': RefComponentWidget, 'ref:dataset': RefDatasetWidget, 'ref-multi:permission': RefMultiPermissionWidget, + 'ref-multi:capability': RefMultiCapabilityWidget, 'filter-mode': FilterModeWidget, 'object-selector': ObjectSelectorWidget, 'field-selector': FieldSelectorWidget, @@ -3779,6 +3918,7 @@ export const WIDGET_LABELLING: Record = { 'ref:component': 'control', 'ref:dataset': 'control', 'ref-multi:permission': 'group', + 'ref-multi:capability': 'group', 'filter-mode': 'group', 'object-selector': 'control', 'field-selector': 'control', diff --git a/ui/packages/app-shell/src/views/objectViewTitleSwitcher.tsx b/ui/packages/app-shell/src/views/objectViewTitleSwitcher.tsx index 7c5e54d1428..16ef0df1e24 100644 --- a/ui/packages/app-shell/src/views/objectViewTitleSwitcher.tsx +++ b/ui/packages/app-shell/src/views/objectViewTitleSwitcher.tsx @@ -57,6 +57,7 @@ import type { buildViewTabs } from './objectViewTabs.js'; import type { ConsoleObjectViewProps } from './ObjectView.js'; import { FOOTER_ITEM, ObjectViewSwitcherMenu, type SwitcherCreateOptions } from './objectViewSwitcherMenu.js'; import { useCreateViewInPlace } from './objectViewViewCrud.js'; +import type { CapabilityAudience } from './capabilityAudience.js'; type TFn = ReturnType['t']; @@ -301,6 +302,16 @@ export function ObjectViewTitleSwitcher({ ); } +/** + * objectstack#34908 — the open view's audience gate, the create card's + * starting pick: a new shared view starts from the open one, gate included. + * Read where a view carries it — its body, or a view item's `config`. + */ +function requiredPermissionsOf(view: Record | undefined): string[] { + const own = view?.requiredPermissions ?? view?.config?.requiredPermissions; + return Array.isArray(own) ? own.filter((p: unknown): p is string => typeof p === 'string' && p.trim() !== '') : []; +} + /** The field names an open view's columns list (a name, or `{ field }`). */ function shownFieldsOf(view: Record | undefined): string[] { const columns = Array.isArray(view?.columns) ? view.columns : []; @@ -380,6 +391,8 @@ export function useObjectViewTitleSwitcher({ canCreatePersonal: boolean; canCreateShared: boolean; hasUnsavedConditions: boolean; + /** objectstack#34908 — the audience catalog for a shared view's 「Who sees this view」. Absent ⇒ no picker. */ + loadAudience?: () => Promise; }; onRenamePersonalView?: (viewId: string) => void; onDeletePersonalView?: (viewId: string) => void; @@ -402,6 +415,8 @@ export function useObjectViewTitleSwitcher({ hasUnsavedConditions: create.hasUnsavedConditions, shownFields: shownFieldsOf(create.activeView), onCreate: createInPlace, + loadAudience: create.canCreateShared ? create.loadAudience : undefined, + initialRequiredPermissions: requiredPermissionsOf(create.activeView), } : undefined; // objectui#12528 — the view's description is shown once. It rides on the diff --git a/ui/packages/app-shell/src/views/objectViewViewCrud.tsx b/ui/packages/app-shell/src/views/objectViewViewCrud.tsx index 6fb1a46fe7d..992001acf36 100644 --- a/ui/packages/app-shell/src/views/objectViewViewCrud.tsx +++ b/ui/packages/app-shell/src/views/objectViewViewCrud.tsx @@ -606,7 +606,7 @@ export function useCreateViewInPlace({ clearSourceListState?: (viewId: string) => void; t: ReturnType['t']; }) { - return useCallback(async ({ config, scope, includeCurrent }: InPlaceViewRequest): Promise => { + return useCallback(async ({ config, scope, includeCurrent, requiredPermissions }: InPlaceViewRequest): Promise => { const { type, label, name } = config; const block = config[type]; const listState = readListState(); @@ -625,6 +625,14 @@ export function useCreateViewInPlace({ // the name and key the card gave it. const body: Record = { ...built.config, type, label, name }; delete body.id; + // objectstack#34908 — the card's 「Who sees this view」, when it + // offered one, decides the gate: the open view's own gate (copied + // over with its other keys) is replaced, and an empty pick is no + // gate, so no key is written. + if (requiredPermissions) { + delete body.requiredPermissions; + if (requiredPermissions.length > 0) body.requiredPermissions = [...requiredPermissions]; + } return createShared(body); } try { diff --git a/ui/packages/app-shell/src/views/viewAudience-34908.test.tsx b/ui/packages/app-shell/src/views/viewAudience-34908.test.tsx new file mode 100644 index 00000000000..3f086d92085 --- /dev/null +++ b/ui/packages/app-shell/src/views/viewAudience-34908.test.tsx @@ -0,0 +1,440 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#34908 (ruling 7103739693, letter B) — 「Who sees this view」. + * + * What is pinned: + * - the catalog: the capabilities offered are the ones the registry declares + * and every name a permission set grants (a closed list), each with the + * sets granting it; a position holds what the sets it grants IN FORCE + * grant, as `?include=grants` serves them (never its raw `permissionSets`); + * an undecorated or failed position read leaves the positions unknown; + * - the preview: a position is listed when its sets grant EVERY picked + * capability (the gate is all-of); nothing picked is no gate; + * - the create card's shared scope: the corrected hint, the picker offered + * only for a shared view and only from the catalog, its position preview, + * the open view's gate as the starting pick, and the pick on the request; + * a failed catalog read adds nothing (no free text); a picked gate says it + * applies to the creator too; + * - the host: the picked gate replaces the one the open view would hand on, + * an empty pick writes no key, and no picker leaves the body as before; + * - the Studio form widget `ref-multi:capability`: the closed list (no + * typed-name box on any arm), each option with its granting sets, and the + * same preview under it; it reads the catalog through the host's loader + * once it is on screen, so a closed section sends no request. + */ + +import '@testing-library/jest-dom/vitest'; +import * as React from 'react'; +import { describe, it, expect, vi, afterEach } from 'vitest'; +// The source under test reaches these through dynamic imports (the capability +// lint, the CEL authoring helpers); pay their first load during collection, not +// inside a case's clocked window. +import '@objectstack/lint'; +import '@objectstack/formula'; +import { render, cleanup, fireEvent, waitFor, screen, within, act, renderHook } from '@testing-library/react'; + +vi.mock('sonner', () => ({ toast: { error: vi.fn(), success: vi.fn() } })); +// One client for every render: a fresh object per call would re-run every +// effect keyed on the client (the card's dataset binding), render after render. +const client = { list: async () => [] }; +vi.mock('./metadata-admin/useMetadata', async (importOriginal) => ({ + ...(await importOriginal>()), + useMetadataClient: () => client, +})); + +import { + buildCapabilityAudience, + loadCapabilityAudience, + positionsReached, + type CapabilityAudience, +} from './capabilityAudience'; +import { CreateViewCard, type InPlaceViewRequest } from './CreateViewDialog'; +import { useCreateViewInPlace } from './objectViewViewCrud'; +import { SchemaForm } from './metadata-admin/SchemaForm'; +import { formDeclaresWidget } from './metadata-admin/widgets'; +import { getViewForm } from './metadata-admin/view-schema'; + +afterEach(cleanup); + +const settle = () => act(() => new Promise((resolve) => setTimeout(resolve, 30))); + +const CAPABILITIES = [{ name: 'view_deal_sales', label: '客户视图·业务员' }, { item: { name: 'view_deal_finance' } }]; +const PERMISSION_SETS = [ + { name: 'sales_rep_set', systemPermissions: ['view_deal_sales', 'export_reports'] }, + { name: 'sales_lead_set', systemPermissions: ['view_deal_sales', 'view_deal_finance'] }, + { name: 'finance_set', systemPermissions: ['view_deal_finance'] }, +]; +// As `GET /meta/position?include=grants` serves them: `_grantedPermissionSets` +// is the server's answer (the sets in force); the raw `permissionSets` a +// position names is NOT what the preview reads — `paused_lead` names a set +// but grants none (switched off), and `accountant` names one that is not served. +const grants = (...sets: string[]) => sets.map((name) => ({ name, via: 'definition' })); +const POSITIONS = [ + { name: 'sales_rep', label: '业务员', permissionSets: ['sales_rep_set'], _grantedPermissionSets: grants('sales_rep_set') }, + { name: 'sales_lead', label: '销售主管', permissionSets: ['sales_lead_set'], _grantedPermissionSets: grants('sales_lead_set') }, + { name: 'accountant', permissionSets: ['finance_set', 'missing_set'], _grantedPermissionSets: grants('finance_set') }, + { name: 'paused_lead', permissionSets: ['sales_lead_set'], _grantedPermissionSets: [] }, +]; + +const AUDIENCE = buildCapabilityAudience(CAPABILITIES, PERMISSION_SETS, POSITIONS); + +describe('the audience catalog', () => { + it('offers the declared capabilities and every one a permission set grants, each with the sets granting it', () => { + expect(AUDIENCE.capabilities).toEqual([ + { name: 'export_reports', grantedBy: ['sales_rep_set'] }, + { name: 'view_deal_finance', grantedBy: ['finance_set', 'sales_lead_set'] }, + { name: 'view_deal_sales', label: '客户视图·业务员', grantedBy: ['sales_lead_set', 'sales_rep_set'] }, + ]); + }); + + it('a position holds what the sets it grants IN FORCE (as served) grant, never what its raw definition names', () => { + expect(AUDIENCE.positions).toEqual([ + { name: 'accountant', capabilities: ['view_deal_finance'] }, + { name: 'paused_lead', capabilities: [] }, + { name: 'sales_lead', label: '销售主管', capabilities: ['view_deal_finance', 'view_deal_sales'] }, + { name: 'sales_rep', label: '业务员', capabilities: ['export_reports', 'view_deal_sales'] }, + ]); + }); + + it('a position list served without its grants leaves the positions unknown, never joined in the browser', () => { + const undecorated = POSITIONS.map(({ _grantedPermissionSets: _served, ...raw }) => raw); + expect(buildCapabilityAudience(CAPABILITIES, PERMISSION_SETS, undecorated).positions).toBeNull(); + }); + + it('the preview lists a position only when its sets grant EVERY picked capability; nothing picked is no gate', () => { + const positions = AUDIENCE.positions!; + expect(positionsReached([], positions)).toBeNull(); + expect(positionsReached(['view_deal_sales'], positions)!.map((p) => p.name)).toEqual(['sales_lead', 'sales_rep']); + expect(positionsReached(['view_deal_sales', 'view_deal_finance'], positions)!.map((p) => p.name)).toEqual(['sales_lead']); + expect(positionsReached(['nobody_has_this'], positions)).toEqual([]); + }); + + it('reads the positions with their served grants', async () => { + const list = vi.fn(async (type: string, _options?: { include?: 'grants' }) => + (type === 'capability' ? CAPABILITIES : type === 'permission' ? PERMISSION_SETS : POSITIONS) as unknown[]); + const audience = await loadCapabilityAudience({ list }); + expect(list).toHaveBeenCalledWith('position', { include: 'grants' }); + expect(positionsReached(['view_deal_sales'], audience.positions!)!.map((p) => p.name)).toEqual(['sales_lead', 'sales_rep']); + }); + + it('a failed position read keeps the catalog and leaves the positions unknown; a failed capability read fails the load', async () => { + const fine = await loadCapabilityAudience({ + list: async (type) => { + if (type === 'position') throw new Error('403'); + return type === 'capability' ? CAPABILITIES : PERMISSION_SETS; + }, + }); + expect(fine.capabilities.map((c) => c.name)).toContain('view_deal_sales'); + expect(fine.positions).toBeNull(); + await expect(loadCapabilityAudience({ + list: async (type) => { + if (type === 'capability') throw new Error('boom'); + return []; + }, + })).rejects.toThrow('boom'); + }); +}); + +// --------------------------------------------------------------------------- +// The create card's shared scope +// --------------------------------------------------------------------------- + +function mountCard(props: Partial> = {}) { + const onCreate = vi.fn(async (_request: InPlaceViewRequest) => true); + render( + {}} + {...props} + />, + ); + return { onCreate }; +} + +const submit = () => screen.getByTestId('create-view-card-submit'); +const toShared = () => fireEvent.click(screen.getByTestId('create-view-card-scope-shared')); + +async function addCapability(name: string) { + fireEvent.keyDown(screen.getByTestId('view-audience-add'), { key: 'ArrowDown' }); + const listbox = await screen.findByRole('listbox'); + fireEvent.click(within(listbox).getByTestId(`view-audience-option-${name}`)); + await waitFor(() => expect(screen.queryByRole('listbox')).not.toBeInTheDocument()); +} + +describe('the create card: who sees a shared view', () => { + it('the shared hint no longer claims everyone sees every shared view', () => { + mountCard(); + toShared(); + expect(screen.getByTestId('create-view-card-shared-hint').textContent).toMatch(/unless the view is limited to the holders of a capability/); + }); + + it('the picker is offered for a shared view only, and the catalog is read only then', async () => { + const loadAudience = vi.fn(async () => AUDIENCE); + mountCard({ loadAudience }); + await settle(); + expect(screen.queryByTestId('view-audience-picker')).toBeNull(); + expect(loadAudience).not.toHaveBeenCalled(); + toShared(); + expect(screen.getByTestId('view-audience-picker')).toBeInTheDocument(); + await waitFor(() => expect(loadAudience).toHaveBeenCalledTimes(1)); + expect(screen.getByTestId('view-audience-preview').textContent).toBe('Everyone who can see this list'); + }); + + it('offers only the known capabilities, with their sets, and previews the positions that will see the view', async () => { + const { onCreate } = mountCard({ loadAudience: async () => AUDIENCE }); + toShared(); + await settle(); + fireEvent.keyDown(screen.getByTestId('view-audience-add'), { key: 'ArrowDown' }); + const listbox = await screen.findByRole('listbox'); + expect(within(listbox).getAllByRole('option').map((o) => o.getAttribute('data-testid'))).toEqual([ + 'view-audience-option-export_reports', + 'view-audience-option-view_deal_finance', + 'view-audience-option-view_deal_sales', + ]); + expect(within(listbox).getByTestId('view-audience-option-view_deal_sales').textContent).toContain('Granted by sales_lead_set, sales_rep_set'); + fireEvent.click(within(listbox).getByTestId('view-audience-option-view_deal_sales')); + await waitFor(() => expect(screen.queryByRole('listbox')).not.toBeInTheDocument()); + expect(screen.getByTestId('view-audience-preview').textContent).toBe('销售主管, 业务员 will see this view'); + await addCapability('view_deal_finance'); + expect(screen.getByTestId('view-audience-preview').textContent).toBe('销售主管 will see this view'); + fireEvent.click(submit()); + await waitFor(() => expect(onCreate).toHaveBeenCalledTimes(1)); + expect(onCreate.mock.calls[0][0]).toMatchObject({ scope: 'shared', requiredPermissions: ['view_deal_sales', 'view_deal_finance'] }); + }); + + it('a pick no single position holds claims no exclusive audience: two positions together can pass the gate', async () => { + // No one position grants both, but the gate reads the UNION of a person's + // positions: a holder of sales_rep (export_reports) and accountant + // (view_deal_finance) passes with no direct grant at all. + expect(positionsReached(['export_reports', 'view_deal_finance'], AUDIENCE.positions!)).toEqual([]); + const held = new Set( + AUDIENCE.positions!.filter((p) => p.name === 'sales_rep' || p.name === 'accountant').flatMap((p) => p.capabilities), + ); + expect(['export_reports', 'view_deal_finance'].every((c) => held.has(c))).toBe(true); + mountCard({ loadAudience: async () => AUDIENCE, initialRequiredPermissions: ['export_reports', 'view_deal_finance'] }); + toShared(); + await settle(); + expect(screen.getByTestId('view-audience-preview').textContent).toBe( + 'No single position holds every picked capability: only people who hold all of them, directly or through several positions, will see this view', + ); + }); + + it('while a gate is picked, it says the gate applies to the creator too; with none picked it says nothing of the kind', async () => { + mountCard({ loadAudience: async () => AUDIENCE }); + toShared(); + await settle(); + expect(screen.queryByTestId('view-audience-self')).toBeNull(); + await addCapability('view_deal_sales'); + expect(screen.getByTestId('view-audience-self').textContent).toMatch(/^This applies to you too/); + }); + + it('starts from the open view\'s gate, which can be removed: the request then carries an empty gate', async () => { + const { onCreate } = mountCard({ loadAudience: async () => AUDIENCE, initialRequiredPermissions: ['view_deal_sales'] }); + toShared(); + await settle(); + expect(screen.getByTestId('view-audience-picked-view_deal_sales')).toBeInTheDocument(); + fireEvent.click(within(screen.getByTestId('view-audience-picked-view_deal_sales')).getByRole('button')); + fireEvent.click(submit()); + await waitFor(() => expect(onCreate).toHaveBeenCalledTimes(1)); + expect(onCreate.mock.calls[0][0].requiredPermissions).toEqual([]); + }); + + it('a failed catalog read says so and offers nothing to type or pick', async () => { + mountCard({ loadAudience: async () => { throw new Error('denied'); } }); + toShared(); + await settle(); + expect(screen.getByTestId('view-audience-load-failed').textContent).toContain('denied'); + expect(screen.queryByTestId('view-audience-add')).toBeNull(); + expect(within(screen.getByTestId('view-audience-picker')).queryByRole('textbox')).toBeNull(); + }); + + it('CONTROL: a personal view, or a host with no catalog, sends no gate', async () => { + const first = mountCard({ loadAudience: async () => AUDIENCE }); + fireEvent.click(submit()); + await waitFor(() => expect(first.onCreate).toHaveBeenCalledTimes(1)); + expect(first.onCreate.mock.calls[0][0]).not.toHaveProperty('requiredPermissions'); + cleanup(); + const second = mountCard(); + toShared(); + expect(screen.queryByTestId('view-audience-picker')).toBeNull(); + fireEvent.click(submit()); + await waitFor(() => expect(second.onCreate).toHaveBeenCalledTimes(1)); + expect(second.onCreate.mock.calls[0][0]).not.toHaveProperty('requiredPermissions'); + }); +}); + +// --------------------------------------------------------------------------- +// The host: the picked gate decides the new shared view's body +// --------------------------------------------------------------------------- + +describe('useCreateViewInPlace: the picked gate', () => { + const GATED = { id: 'crm_deal.mine', name: 'mine', label: 'Mine', type: 'grid', columns: ['name'], requiredPermissions: ['view_deal_finance'] }; + const t = ((key: string) => key) as never; + + function setup() { + const createShared = vi.fn(async (_body: Record) => true); + const { result } = renderHook(() => useCreateViewInPlace({ + objectName: 'crm_deal', + activeView: GATED, + readListState: () => ({ url: {} }), + savePersonal: vi.fn(async () => 'pv'), + openPersonal: vi.fn(), + createShared, + t, + })); + return { create: result.current, createShared }; + } + const request = (requiredPermissions?: string[]): InPlaceViewRequest => ({ + config: { type: 'grid', label: 'Sales', name: 'sales' }, + scope: 'shared', + includeCurrent: false, + ...(requiredPermissions ? { requiredPermissions } : {}), + }); + + it('a pick replaces the gate the open view would hand on', async () => { + const { create, createShared } = setup(); + await create(request(['view_deal_sales'])); + expect(createShared.mock.calls[0][0].requiredPermissions).toEqual(['view_deal_sales']); + }); + + it('an empty pick writes no gate at all', async () => { + const { create, createShared } = setup(); + await create(request([])); + expect(createShared.mock.calls[0][0]).not.toHaveProperty('requiredPermissions'); + }); + + it('CONTROL: with no picker the body is built as before, the open view\'s gate included', async () => { + const { create, createShared } = setup(); + await create(request()); + expect(createShared.mock.calls[0][0].requiredPermissions).toEqual(['view_deal_finance']); + }); +}); + +// --------------------------------------------------------------------------- +// The Studio form widget +// --------------------------------------------------------------------------- + +describe('the view form\'s audience row in Studio', () => { + it('the view form declares the capability picker', () => { + expect(formDeclaresWidget(getViewForm('en'), 'ref-multi:capability')).toBe(true); + }); + + function mountRow(audience: CapabilityAudience | null, value: string[]) { + render( + {}} + widgetContext={{ + conditionScope: 'none', + ...(audience ? { capabilityAudience: { status: 'loaded', data: audience } } : {}), + }} + />, + ); + } + + it('lists the picked names and previews the positions that will see the view', () => { + mountRow(AUDIENCE, ['view_deal_sales']); + expect(screen.getByTestId('ref-multi-capability')).toHaveTextContent('view_deal_sales'); + expect(screen.getByTestId('ref-multi-capability-audience').textContent).toContain('销售主管, 业务员'); + }); + + it('a stored name the catalog does not know is flagged, not dropped', () => { + mountRow(AUDIENCE, ['view_deal_sale']); + expect(screen.getByTestId('ref-multi-capability').querySelector('[data-not-found]')).not.toBeNull(); + }); + + it('nothing picked: everyone who can see the list sees it', () => { + mountRow(AUDIENCE, []); + expect(screen.getByTestId('ref-multi-capability-audience').textContent).toMatch(/everyone who can see the list/i); + }); + + it('offers each capability with the permission sets granting it', async () => { + mountRow(AUDIENCE, []); + fireEvent.keyDown(screen.getByTestId('ref-multi-capability-add'), { key: 'ArrowDown' }); + const listbox = await screen.findByRole('listbox'); + expect(within(listbox).getAllByTestId('ref-multi-capability-detail').map((d) => d.textContent)).toEqual([ + 'Granted by sales_rep_set', + 'Granted by finance_set, sales_lead_set', + 'Granted by sales_lead_set, sales_rep_set', + ]); + }); + + it('is a closed list: no catalog fed, an empty one, or a failed read offers no box to type a name in', () => { + mountRow(null, ['view_deal_sales']); + expect(screen.queryByTestId('ref-multi-capability-audience')).toBeNull(); + expect(screen.queryByTestId('ref-multi-capability-freeform')).toBeNull(); + expect(screen.getByTestId('ref-multi-capability-closed').textContent).toBe('The capability list is not available here, so none can be added.'); + cleanup(); + mountRow({ capabilities: [], positions: [] }, []); + expect(screen.queryByTestId('ref-multi-capability-freeform')).toBeNull(); + expect(screen.getByTestId('ref-multi-capability-closed').textContent).toMatch(/^No capability is defined yet/); + cleanup(); + render( + {}} + widgetContext={{ conditionScope: 'none', capabilityAudience: { status: 'error', message: 'denied' } }} + />, + ); + expect(screen.getByTestId('ref-multi-capability-load-failed')).toBeInTheDocument(); + expect(screen.queryByTestId('ref-multi-capability-freeform')).toBeNull(); + expect(screen.getByTestId('ref-multi-capability')).toHaveTextContent('view_deal_sales'); + }); + + it('reads the catalog through the host\'s loader only once the row is on screen', async () => { + const load = vi.fn(async () => AUDIENCE); + render( + {}} + widgetContext={{ conditionScope: 'none', loadCapabilityAudience: load }} + />, + ); + await settle(); + // The section is closed: no request. + expect(load).not.toHaveBeenCalled(); + expect(screen.queryByTestId('ref-multi-capability')).toBeNull(); + fireEvent.click(screen.getByText('Access')); + await waitFor(() => + expect(screen.getByTestId('ref-multi-capability-audience').textContent).toContain('销售主管, 业务员'), + ); + expect(load).toHaveBeenCalledTimes(1); + }); + + it('control: a catalog the host already holds is used as given, and the loader is not called', async () => { + const load = vi.fn(async () => AUDIENCE); + render( + {}} + widgetContext={{ conditionScope: 'none', capabilityAudience: { status: 'loaded', data: AUDIENCE }, loadCapabilityAudience: load }} + />, + ); + await settle(); + expect(load).not.toHaveBeenCalled(); + expect(screen.getByTestId('ref-multi-capability-audience').textContent).toContain('销售主管, 业务员'); + }); + + it('nothing reachable: the preview no longer promises the object\'s editors', () => { + mountRow(AUDIENCE, ['export_reports', 'view_deal_finance']); + expect(screen.getByTestId('ref-multi-capability-audience').textContent).toBe( + 'No single position holds every picked capability: only people who hold all of them, directly or through several positions, will see it.', + ); + }); +}); diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index 432120bad48..54d36bd6aee 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -1485,7 +1485,21 @@ const ar = { typeLabel: 'نوع العرض', includeCurrent: 'تضمين عوامل التصفية والفرز الحالية', scopeShared: 'مشترك', - scopeHint: 'العروض المشتركة يراها كل من يمكنه رؤية هذه القائمة', + scopeHint: 'العروض المشتركة يراها كل من يمكنه رؤية هذه القائمة، ما لم يُقصر العرض على حاملي صلاحية', + // objectstack#34908 — who a shared view reaches: the capability picker and its position preview. + audienceLabel: 'من يرى هذا العرض', + audienceEveryone: 'كل من يمكنه رؤية هذه القائمة', + audienceAdd: 'قصر العرض على صلاحية…', + audienceAllAdded: 'تمت إضافة كل الصلاحيات', + audienceLoading: 'جارٍ تحميل الصلاحيات…', + audienceLoadFailed: 'تعذر تحميل الصلاحيات، لذا لا يمكن إضافة أي منها: {{message}}', + audienceNone: 'لم تُعرَّف أي صلاحية بعد. تُمنح الصلاحيات في الإعداد عبر مجموعات الأذونات.', + audienceGrantedBy: 'تمنحها {{sets}}', + audienceRemove: 'إزالة {{name}}', + audiencePositions: 'سيرى هذا العرض: {{positions}}', + audienceNoPosition: 'لا يوجد منصب واحد يحمل كل الصلاحيات المختارة: لن يرى هذا العرض إلا من يحملها كلها، مباشرة أو عبر عدة مناصب', + audienceSelf: 'ينطبق هذا عليك أيضًا: إذا لم تكن تحمل كل الصلاحيات المختارة، فسيختفي العرض من قائمتك أنت أيضًا بعد إنشائه', + audiencePositionsUnread: 'تعذرت قراءة المناصب، لذا لا يظهر من سيرى هذا العرض', // objectstack#36409 — a shared view's name already taken, and a view that is gone. shareNameTaken: 'توجد مسودة غير منشورة تستخدم اسم هذا العرض بالفعل، لذلك لم تتم المشاركة. غيّر اسم العرض وحاول مرة أخرى.', viewGone: 'العرض الذي فتحته لم يعد متاحًا، لذا تعرض القائمة العرض الافتراضي.', diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index bddfbcf2439..c187e481dfb 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -1348,7 +1348,21 @@ const de = { typeLabel: 'Ansichtstyp', includeCurrent: 'Aktuelle Filter und Sortierung übernehmen', scopeShared: 'Geteilt', - scopeHint: 'Geteilte Ansichten sieht jeder, der diese Liste sehen kann', + scopeHint: 'Geteilte Ansichten sieht jeder, der diese Liste sehen kann, außer die Ansicht ist auf die Inhaber einer Berechtigung beschränkt', + // objectstack#34908 — who a shared view reaches: the capability picker and its position preview. + audienceLabel: 'Wer diese Ansicht sieht', + audienceEveryone: 'Jeder, der diese Liste sehen kann', + audienceAdd: 'Auf eine Berechtigung beschränken…', + audienceAllAdded: 'Alle Berechtigungen hinzugefügt', + audienceLoading: 'Berechtigungen werden geladen…', + audienceLoadFailed: 'Die Berechtigungen konnten nicht geladen werden, daher kann keine hinzugefügt werden: {{message}}', + audienceNone: 'Noch keine Berechtigung definiert. Berechtigungen werden im Setup über Berechtigungssätze vergeben.', + audienceGrantedBy: 'Vergeben durch {{sets}}', + audienceRemove: '{{name}} entfernen', + audiencePositions: '{{positions}} sehen diese Ansicht', + audienceNoPosition: 'Keine einzelne Position hat alle gewählten Berechtigungen: Nur wer alle hat, direkt oder über mehrere Positionen, sieht diese Ansicht', + audienceSelf: 'Das gilt auch für Sie: Haben Sie nicht alle gewählten Berechtigungen, verschwindet die Ansicht nach dem Erstellen auch aus Ihrer eigenen Liste', + audiencePositionsUnread: 'Die Positionen konnten nicht gelesen werden, daher wird nicht angezeigt, wer diese Ansicht sieht', // objectstack#36409 — a shared view's name already taken, and a view that is gone. shareNameTaken: 'Ein unveröffentlichter Entwurf verwendet bereits den Namen dieser Ansicht, daher wurde nichts geteilt. Geben Sie der Ansicht einen anderen Namen und versuchen Sie es erneut.', viewGone: 'Die geöffnete Ansicht ist nicht mehr verfügbar, daher zeigt die Liste ihre Standardansicht.', diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index cb216001c7b..a16318e78b9 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -1660,7 +1660,21 @@ const en = { typeLabel: 'View type', includeCurrent: 'Include the current filters and sort', scopeShared: 'Shared', - scopeHint: 'Shared views are seen by everyone who can see this list', + scopeHint: 'Shared views are seen by everyone who can see this list, unless the view is limited to the holders of a capability', + // objectstack#34908 — who a shared view reaches: the capability picker and its position preview. + audienceLabel: 'Who sees this view', + audienceEveryone: 'Everyone who can see this list', + audienceAdd: 'Limit to a capability…', + audienceAllAdded: 'All capabilities added', + audienceLoading: 'Loading capabilities…', + audienceLoadFailed: 'The capabilities could not be loaded, so none can be added: {{message}}', + audienceNone: 'No capability is defined yet. Capabilities are granted on permission sets, in Setup.', + audienceGrantedBy: 'Granted by {{sets}}', + audienceRemove: 'Remove {{name}}', + audiencePositions: '{{positions}} will see this view', + audienceNoPosition: 'No single position holds every picked capability: only people who hold all of them, directly or through several positions, will see this view', + audienceSelf: 'This applies to you too: if you do not hold every capability picked, the view leaves your own list once it is created', + audiencePositionsUnread: 'The positions could not be read, so who will see this view is not shown', // objectstack#36409 — a shared view's name already taken, and a view that is gone. shareNameTaken: 'An unpublished draft already uses this view’s name, so nothing was shared. Give the view another name and try again.', viewGone: 'The view you opened is no longer available, so the list shows its default view.', diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index 75eff829d9b..fadc22aa746 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -1385,7 +1385,21 @@ const es = { typeLabel: 'Tipo de vista', includeCurrent: 'Incluir los filtros y el orden actuales', scopeShared: 'Compartida', - scopeHint: 'Las vistas compartidas las ve cualquiera que pueda ver esta lista', + scopeHint: 'Las vistas compartidas las ve cualquiera que pueda ver esta lista, salvo que la vista se limite a quienes tengan un permiso', + // objectstack#34908 — who a shared view reaches: the capability picker and its position preview. + audienceLabel: 'Quién ve esta vista', + audienceEveryone: 'Cualquiera que pueda ver esta lista', + audienceAdd: 'Limitar a un permiso…', + audienceAllAdded: 'Todos los permisos añadidos', + audienceLoading: 'Cargando permisos…', + audienceLoadFailed: 'No se pudieron cargar los permisos, así que no se puede añadir ninguno: {{message}}', + audienceNone: 'Aún no hay permisos definidos. Los permisos se conceden en Configuración, en los conjuntos de permisos.', + audienceGrantedBy: 'Concedido por {{sets}}', + audienceRemove: 'Quitar {{name}}', + audiencePositions: '{{positions}} verán esta vista', + audienceNoPosition: 'Ningún puesto por sí solo tiene todos los permisos elegidos: solo quienes los tengan todos, directamente o a través de varios puestos, verán esta vista', + audienceSelf: 'Esto también le afecta: si no tiene todos los permisos elegidos, la vista desaparecerá de su propia lista una vez creada', + audiencePositionsUnread: 'No se pudieron leer los puestos, así que no se muestra quién verá esta vista', // objectstack#36409 — a shared view's name already taken, and a view that is gone. shareNameTaken: 'Un borrador sin publicar ya usa el nombre de esta vista, así que no se compartió nada. Ponle otro nombre a la vista e inténtalo de nuevo.', viewGone: 'La vista que abriste ya no está disponible, así que la lista muestra su vista predeterminada.', diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index 46a334ba5fd..21296c8f1e3 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -1380,7 +1380,21 @@ const fr = { typeLabel: 'Type de vue', includeCurrent: 'Inclure les filtres et le tri actuels', scopeShared: 'Partagée', - scopeHint: 'Les vues partagées sont visibles par tous ceux qui voient cette liste', + scopeHint: 'Les vues partagées sont visibles par tous ceux qui voient cette liste, sauf si la vue est limitée aux détenteurs d’une autorisation', + // objectstack#34908 — who a shared view reaches: the capability picker and its position preview. + audienceLabel: 'Qui voit cette vue', + audienceEveryone: 'Tous ceux qui voient cette liste', + audienceAdd: 'Limiter à une autorisation…', + audienceAllAdded: 'Toutes les autorisations ajoutées', + audienceLoading: 'Chargement des autorisations…', + audienceLoadFailed: 'Les autorisations n’ont pas pu être chargées, aucune ne peut donc être ajoutée : {{message}}', + audienceNone: 'Aucune autorisation n’est encore définie. Les autorisations s’accordent dans Configuration, sur les ensembles d’autorisations.', + audienceGrantedBy: 'Accordée par {{sets}}', + audienceRemove: 'Retirer {{name}}', + audiencePositions: '{{positions}} verront cette vue', + audienceNoPosition: 'Aucun poste ne détient à lui seul toutes les autorisations choisies : seules les personnes qui les détiennent toutes, directement ou via plusieurs postes, verront cette vue', + audienceSelf: 'Cela vous concerne aussi : si vous ne détenez pas toutes les autorisations choisies, la vue quitte votre propre liste une fois créée', + audiencePositionsUnread: 'Les postes n’ont pas pu être lus, qui verra cette vue n’est donc pas affiché', // objectstack#36409 — a shared view's name already taken, and a view that is gone. shareNameTaken: 'Un brouillon non publié utilise déjà le nom de cette vue, donc rien n’a été partagé. Donnez un autre nom à la vue et réessayez.', viewGone: 'La vue ouverte n’est plus disponible, la liste affiche donc sa vue par défaut.', diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index 84676a167a6..34b7e0cfe26 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -1348,7 +1348,21 @@ const ja = { typeLabel: 'ビューの種類', includeCurrent: '現在のフィルターと並べ替えを含める', scopeShared: '共有', - scopeHint: '共有ビューはこのリストを見られる全員に表示されます', + scopeHint: '共有ビューはこのリストを見られる全員に表示されます。ただし、ある権限の保有者に限定した場合を除きます', + // objectstack#34908 — who a shared view reaches: the capability picker and its position preview. + audienceLabel: 'このビューを見られる人', + audienceEveryone: 'このリストを見られる全員', + audienceAdd: '権限の保有者に限定…', + audienceAllAdded: 'すべての権限を追加済み', + audienceLoading: '権限を読み込み中…', + audienceLoadFailed: '権限を読み込めないため、追加できません:{{message}}', + audienceNone: '権限はまだ定義されていません。権限はセットアップで権限セットに付与します。', + audienceGrantedBy: '付与元:{{sets}}', + audienceRemove: '{{name}} を削除', + audiencePositions: '{{positions}} がこのビューを見られます', + audienceNoPosition: '選択したすべての権限を単独で持つ役職はありません。直接、または複数の役職を通じてすべてを持つ人だけがこのビューを見られます', + audienceSelf: 'これはあなた自身にも適用されます。選択したすべての権限を持っていない場合、作成後このビューはあなたのリストからも消えます', + audiencePositionsUnread: '役職を読み込めないため、このビューを見られる人は表示されません', // objectstack#36409 — a shared view's name already taken, and a view that is gone. shareNameTaken: '未公開の下書きがすでにこのビューの名前を使っているため、共有しませんでした。ビューの名前を変えてもう一度お試しください。', viewGone: '開いたビューはもう存在しないため、リストは既定のビューを表示しています。', diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index a47943f0187..b53defa22e0 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -1348,7 +1348,21 @@ const ko = { typeLabel: '보기 유형', includeCurrent: '현재 필터와 정렬 포함', scopeShared: '공유', - scopeHint: '공유 보기는 이 목록을 볼 수 있는 모든 사람에게 표시됩니다', + scopeHint: '공유 보기는 이 목록을 볼 수 있는 모든 사람에게 표시됩니다. 단, 특정 권한 보유자로 제한한 경우는 예외입니다', + // objectstack#34908 — who a shared view reaches: the capability picker and its position preview. + audienceLabel: '이 보기를 볼 수 있는 사람', + audienceEveryone: '이 목록을 볼 수 있는 모든 사람', + audienceAdd: '권한 보유자로 제한…', + audienceAllAdded: '모든 권한이 추가됨', + audienceLoading: '권한을 불러오는 중…', + audienceLoadFailed: '권한을 불러올 수 없어 추가할 수 없습니다: {{message}}', + audienceNone: '아직 정의된 권한이 없습니다. 권한은 설정에서 권한 집합에 부여합니다.', + audienceGrantedBy: '{{sets}}에서 부여', + audienceRemove: '{{name}} 제거', + audiencePositions: '{{positions}}이(가) 이 보기를 봅니다', + audienceNoPosition: '선택한 모든 권한을 단독으로 가진 직위가 없습니다. 직접 또는 여러 직위를 통해 모두 가진 사람만 이 보기를 봅니다', + audienceSelf: '이는 본인에게도 적용됩니다. 선택한 모든 권한을 갖고 있지 않으면 생성 후 이 보기는 본인 목록에서도 사라집니다', + audiencePositionsUnread: '직위를 읽을 수 없어 이 보기를 볼 사람이 표시되지 않습니다', // objectstack#36409 — a shared view's name already taken, and a view that is gone. shareNameTaken: '게시되지 않은 초안이 이미 이 보기의 이름을 사용하고 있어 공유하지 않았습니다. 보기 이름을 바꾸고 다시 시도하세요.', viewGone: '연 보기가 더 이상 없으므로 목록에 기본 보기가 표시됩니다.', diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index 5a925e1705c..63658167e53 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -1380,7 +1380,21 @@ const pt = { typeLabel: 'Tipo de visualização', includeCurrent: 'Incluir os filtros e a ordenação atuais', scopeShared: 'Compartilhada', - scopeHint: 'Visualizações compartilhadas são vistas por todos que podem ver esta lista', + scopeHint: 'Visualizações compartilhadas são vistas por todos que podem ver esta lista, a menos que a visualização seja limitada a quem tem uma permissão', + // objectstack#34908 — who a shared view reaches: the capability picker and its position preview. + audienceLabel: 'Quem vê esta visualização', + audienceEveryone: 'Todos que podem ver esta lista', + audienceAdd: 'Limitar a uma permissão…', + audienceAllAdded: 'Todas as permissões adicionadas', + audienceLoading: 'Carregando permissões…', + audienceLoadFailed: 'Não foi possível carregar as permissões, então nenhuma pode ser adicionada: {{message}}', + audienceNone: 'Nenhuma permissão definida ainda. As permissões são concedidas em Configuração, nos conjuntos de permissões.', + audienceGrantedBy: 'Concedida por {{sets}}', + audienceRemove: 'Remover {{name}}', + audiencePositions: '{{positions}} verão esta visualização', + audienceNoPosition: 'Nenhum cargo sozinho tem todas as permissões escolhidas: só quem tiver todas, diretamente ou por vários cargos, verá esta visualização', + audienceSelf: 'Isso também vale para você: se você não tiver todas as permissões escolhidas, a visualização sai da sua própria lista depois de criada', + audiencePositionsUnread: 'Não foi possível ler os cargos, então não é mostrado quem verá esta visualização', // objectstack#36409 — a shared view's name already taken, and a view that is gone. shareNameTaken: 'Um rascunho não publicado já usa o nome desta visualização, então nada foi compartilhado. Dê outro nome à visualização e tente novamente.', viewGone: 'A visualização que você abriu não está mais disponível, então a lista mostra a visualização padrão.', diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index 77d9eca1ccd..5713c283caa 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -1418,7 +1418,21 @@ const ru = { typeLabel: 'Тип представления', includeCurrent: 'Включить текущие фильтры и сортировку', scopeShared: 'Общее', - scopeHint: 'Общие представления видны всем, кто видит этот список', + scopeHint: 'Общие представления видны всем, кто видит этот список, если представление не ограничено владельцами разрешения', + // objectstack#34908 — who a shared view reaches: the capability picker and its position preview. + audienceLabel: 'Кто видит это представление', + audienceEveryone: 'Все, кто видит этот список', + audienceAdd: 'Ограничить разрешением…', + audienceAllAdded: 'Все разрешения добавлены', + audienceLoading: 'Загрузка разрешений…', + audienceLoadFailed: 'Не удалось загрузить разрешения, поэтому добавить их нельзя: {{message}}', + audienceNone: 'Разрешения ещё не определены. Разрешения выдаются в настройках через наборы разрешений.', + audienceGrantedBy: 'Выдаётся набором {{sets}}', + audienceRemove: 'Удалить {{name}}', + audiencePositions: 'Это представление увидят: {{positions}}', + audienceNoPosition: 'Ни одна должность сама по себе не имеет всех выбранных разрешений: представление увидят только те, у кого есть все они — напрямую или через несколько должностей', + audienceSelf: 'Это касается и вас: если у вас нет всех выбранных разрешений, после создания представление исчезнет и из вашего списка', + audiencePositionsUnread: 'Не удалось прочитать должности, поэтому не показано, кто увидит это представление', // objectstack#36409 — a shared view's name already taken, and a view that is gone. shareNameTaken: 'Неопубликованный черновик уже использует имя этого представления, поэтому ничего не открыто для всех. Переименуйте представление и попробуйте снова.', viewGone: 'Открытое представление больше недоступно, поэтому список показывает представление по умолчанию.', diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index a6ffde7ff72..8641a299123 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -1375,7 +1375,21 @@ const zh = { typeLabel: '视图类型', includeCurrent: '包含当前的筛选和排序', scopeShared: '共享', - scopeHint: '共享视图对能看到此列表的所有人可见', + scopeHint: '共享视图对能看到此列表的所有人可见,除非限定为持有某项能力的人', + // objectstack#34908 — who a shared view reaches: the capability picker and its position preview. + audienceLabel: '谁能看此视图', + audienceEveryone: '能看到此列表的所有人', + audienceAdd: '限定为持有某项能力的人…', + audienceAllAdded: '已添加全部能力', + audienceLoading: '正在加载能力…', + audienceLoadFailed: '无法加载能力,因此无法添加:{{message}}', + audienceNone: '尚未定义任何能力。能力在设置中通过权限集授予。', + audienceGrantedBy: '由 {{sets}} 授予', + audienceRemove: '移除 {{name}}', + audiencePositions: '{{positions}} 会看到此视图', + audienceNoPosition: '没有哪个岗位单独持有所选的全部能力:只有直接或通过多个岗位合计持有全部这些能力的人能看到此视图', + audienceSelf: '这对你自己同样生效:如果你没有持有所选的全部能力,视图创建后也会从你自己的列表中消失', + audiencePositionsUnread: '无法读取岗位,因此不显示谁会看到此视图', // objectstack#36409 — a shared view's name already taken, and a view that is gone. shareNameTaken: '一个尚未发布的草稿已经用了这个视图的名称,所以没有共享。请换个名称再试。', viewGone: '你打开的视图已不存在,列表显示的是默认视图。', diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index c69973ef4b9..84d8f46d812 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -1375,7 +1375,21 @@ const zhHant = { typeLabel: '檢視型別', includeCurrent: '包含當前的篩選和排序', scopeShared: '共享', - scopeHint: '共享檢視對能看到此列表的所有人可見', + scopeHint: '共享檢視對能看到此列表的所有人可見,除非限定為持有某項能力的人', + // objectstack#34908 — who a shared view reaches: the capability picker and its position preview. + audienceLabel: '誰能看此檢視', + audienceEveryone: '能看到此列表的所有人', + audienceAdd: '限定為持有某項能力的人…', + audienceAllAdded: '已新增全部能力', + audienceLoading: '正在載入能力…', + audienceLoadFailed: '無法載入能力,因此無法新增:{{message}}', + audienceNone: '尚未定義任何能力。能力在設定中通過權限集授予。', + audienceGrantedBy: '由 {{sets}} 授予', + audienceRemove: '移除 {{name}}', + audiencePositions: '{{positions}} 會看到此檢視', + audienceNoPosition: '沒有哪個崗位單獨持有所選的全部能力:只有直接或通過多個崗位合計持有全部這些能力的人能看到此檢視', + audienceSelf: '這對你自己同樣生效:如果你沒有持有所選的全部能力,檢視建立後也會從你自己的列表中消失', + audiencePositionsUnread: '無法讀取崗位,因此不顯示誰會看到此檢視', // objectstack#36409 — a shared view's name already taken, and a view that is gone. shareNameTaken: '一個尚未釋出的草稿已經用了這個檢視的名稱,所以沒有共享。請換個名稱再試。', viewGone: '你開啟的檢視已不存在,列表顯示的是預設檢視。', diff --git a/ui/packages/i18n/src/namespaces/studio/en.ts b/ui/packages/i18n/src/namespaces/studio/en.ts index 9e54fa03a70..4a968fab2d9 100644 --- a/ui/packages/i18n/src/namespaces/studio/en.ts +++ b/ui/packages/i18n/src/namespaces/studio/en.ts @@ -1855,6 +1855,18 @@ const STUDIO_EN: Record = { 'engine.form.addPermissionSetPlain': 'Add permission set', 'engine.form.addPermissionSet': 'Add permission set…', 'engine.form.allPermissionSetsAdded': 'All permission sets added', + // The `ref-multi:capability` picker of an audience gate (`requiredPermissions` + // on a list view or a dashboard) and its position preview. + 'engine.form.addCapabilityPlain': 'Add capability', + 'engine.form.addCapability': 'Add capability…', + 'engine.form.allCapabilitiesAdded': 'All capabilities added', + 'engine.form.audienceEveryone': 'No capability picked: everyone who can see the list sees it.', + 'engine.form.audiencePositions': 'Positions that will see it: {positions}.', + 'engine.form.audienceNoPosition': 'No single position holds every picked capability: only people who hold all of them, directly or through several positions, will see it.', + 'engine.form.capabilityGrantedBy': 'Granted by {sets}', + 'engine.form.capabilitiesUnread': 'The capability list is not available here, so none can be added.', + 'engine.form.capabilitiesNone': 'No capability is defined yet. Capabilities are granted on permission sets, in Setup.', + 'engine.form.audiencePositionsUnread': 'The positions could not be read, so who will see it is not shown.', 'engine.form.noObjectFields': 'No object fields ({error}).', // objectui#10862, slice 4 — the not-found `error` the field and dataset // catalogue hooks (`useObjectFields`, `useDatasetSemantics`) publish, read diff --git a/ui/packages/i18n/src/namespaces/studio/zh.ts b/ui/packages/i18n/src/namespaces/studio/zh.ts index 41488bbe6a0..de7633a9df4 100644 --- a/ui/packages/i18n/src/namespaces/studio/zh.ts +++ b/ui/packages/i18n/src/namespaces/studio/zh.ts @@ -1644,6 +1644,16 @@ const STUDIO_ZH: Record = { 'engine.form.addPermissionSetPlain': '添加权限集', 'engine.form.addPermissionSet': '添加权限集…', 'engine.form.allPermissionSetsAdded': '已添加全部权限集', + 'engine.form.addCapabilityPlain': '添加能力', + 'engine.form.addCapability': '添加能力…', + 'engine.form.allCapabilitiesAdded': '已添加全部能力', + 'engine.form.audienceEveryone': '未选能力:能看到该列表的人都能看到。', + 'engine.form.audiencePositions': '会看到的岗位:{positions}。', + 'engine.form.audienceNoPosition': '没有哪个岗位单独持有所选的全部能力:只有直接或通过多个岗位合计持有全部这些能力的人能看到。', + 'engine.form.capabilityGrantedBy': '由 {sets} 授予', + 'engine.form.capabilitiesUnread': '此处读取不到能力列表,无法添加。', + 'engine.form.capabilitiesNone': '尚未定义任何能力。能力在设置中通过权限集授予。', + 'engine.form.audiencePositionsUnread': '读取不到岗位,无法显示谁会看到。', 'engine.form.noObjectFields': '没有对象字段({error})。', // objectui#10862, slice 4. 'engine.form.objectNotFound': '未找到对象',