Compare commits

..

38 Commits

Author SHA1 Message Date
Thierry Goettelmann
26bd093efb feat(web-core/button): add the restricted prop to UiButton and UiButtonIcon
A restricted button looks disabled but stays focusable, ignores clicks and
shows a "Permission required" tooltip, through the `vRestricted` directive.
It lets the app show the actions the user has no permission to run instead
of hiding them.

See XO-3007
2026-12-02 10:38:28 +01:00
Thierry Goettelmann
3278c5a257 feat(web-core/restricted): add the vRestricted directive
A restricted element keeps the keyboard focus but is announced as disabled
(`aria-disabled`), ignores clicks and shows a "Permission required" tooltip
on hover and on focus, in place of its own tooltip. Components can apply it
to the actions the user has no permission to run.

See XO-3007
2026-12-02 10:38:28 +01:00
Thierry Goettelmann
d41de74e01 feat(web-core/tooltip): allow several tooltips per element
A tooltip is now registered under its own key instead of its target, so
an element can hold several tooltips. A registration can listen to
several event pairs, and a prioritized tooltip hides the other tooltips
of its element while it is shown. This prepares the "Permission
required" tooltip of restricted buttons.

A focus tooltip now only shows on a focus the browser makes visible
(`:focus-visible`), not on a focus that follows a click.

See XO-3007
2026-12-02 10:38:28 +01:00
Thierry Goettelmann
43617968e7 fix(xo6/user,role): adapt to the form inputs, VM columns and test mocks changes
Since the rebase on master, the form inputs no longer accept the `brand`
accent (#10861, #10862), the VM columns include a last backup date column
(#10758), and the test files replace exports through the global module
mocks instead of `vi.mock` (#10841).

The user and role form inputs use the `neutral` accent, the VMs scope
table excludes the column it does not render, and the current user
privileges test stubs its collections with `mockedExport`.

The release emptied the packages to release: `@xen-orchestra/web` and
`@xen-orchestra/web-core` are listed again for the RBAC features.
2026-12-02 10:38:27 +01:00
Thierry Goettelmann
1194f91fa4 fix(xo6/role): hide the scope step errors after a resource change
Changing the resource of a privilege resets its scope selector and its
selected objects. The scope step then showed validation errors for
values the user never edited. The step is now marked untouched after
the reset.

The selector is kept in sync with the typed search through `syncRefs`
instead of a manual `watch`.
2026-12-02 10:38:25 +01:00
Thierry Goettelmann
dfdb8c7703 fix(xo6/group,role): pass the side panel through the panel slot
Since the rebase on master, `VtsContentSidePanel` expects the side panel
in its `panel` slot (#10807). The groups, roles and role templates pages
still passed it in the default slot, so it rendered below the table.
2026-12-02 10:38:25 +01:00
Thierry Goettelmann
65157be841 fix(xo6/role): replace the privilege scope selection workaround with selectedIds
`usePrivilegeScopeSelection` replayed the initial selection once the objects
were loaded. The `selectedIds` option of `useTableSelection` now covers it.

The "required" error no longer shows before any interaction on tables whose
objects load after the drawer opens. IDs that match no loaded object are now
kept in the privilege instead of being dropped.

See XO-3443
2026-12-02 10:38:25 +01:00
Thierry Goettelmann
000016c00c fix(xo6/user,group,role): adapt to the query builder and host columns changes
Since the rebase on master, the query builder filters while typing and no
longer emits the search query (#10797), and the host columns include an
actions column (#10821).

The RBAC tables bind the query builder through `searchBindings`, the
privilege selector preview follows the typed query the same way, and the
hosts scope table excludes the actions column it does not render.
2026-12-02 10:38:25 +01:00
Thierry Goettelmann
3a4bc5cb3e feat(xo6/user,role): select the new user or role after its creation
As for groups, the created user opens in the side panel instead of
keeping the previously selected one, and the role creation page goes
back to the roles list with the new role selected. The new item shows up
even when it lands on another page or outside the active filter.
2026-12-02 10:38:24 +01:00
Thierry Goettelmann
26a9d4d105 feat(xo6/role): add role creation from a template (#10788)
Role templates cannot be assigned to users or groups directly. A new page
lists them with their privileges, and selecting one opens the role
creation form prefilled with its name, description and privileges, which
can all be adjusted before the role is created.

See XO-3273
2026-12-02 10:38:24 +01:00
Thierry Goettelmann
aeb1222037 feat(xo6/user): add current user privileges composable (#10771)
* feat(web/user): add current user privileges composable

Fetch the current user's ACL privileges and expose a `can` helper built on
`hasPrivilegeOn`, so the UI can later hide or disable actions a non-admin
user isn't allowed to perform. Admins skip the fetch and are always allowed.

See XO-3004

* feat(xo6/user): keep the current user up to date for privilege checks

`useCurrentUserPrivileges` now reads the user from `useXoCurrentUser`
instead of a second resource on the same `/users/me` endpoint.

That resource had its polling disabled because its only consumer needed
the user id. Privilege checks depend on `permission`, which can change,
so it is polled again like the privileges themselves. SSE is not an
option here: `user` events are only sent to users holding `user:read`.

Add unit tests for the composable.

See XO-3004
2026-12-02 10:38:24 +01:00
Thierry Goettelmann
a7c0c017a6 fix(xo6/role): offer the wildcard and sub-actions in the privilege form (#10776)
The action select only listed the top-level actions of a resource, so a
privilege on `*` or on a sub-action such as `create:vm` could not be
created from the form, although the API accepts them and the role
templates rely on them.

An action already covered by a broader selected one is now unselected
and disabled: all the selected actions share the same effect and scope,
so it would only create a redundant privilege.

See XO-2354
2026-12-02 10:38:24 +01:00
Thierry Goettelmann
2b98689656 fix(xo6/role): use existing locale keys for the backup archive mode
The `backup:full` and `backup:incremental` keys were removed by the
backup refactoring (#10636), which made the lint fail on the backup
archive selector schema. Use `full` and `incremental` instead, as the
backup job mode label already does.
2026-12-02 10:38:24 +01:00
Thierry Goettelmann
d86917f0c0 feat(xo6/group): add group deletion from the groups list and side panel (#10765)
A group can be deleted from a row of the groups table, whose selection
column is replaced by an action column, or from its side panel. Its members
stay as individual users and lose the roles they inherited from the group,
as the confirmation modal warns.

A synchronized group cannot be deleted: its provider would recreate
it at the next synchronization, without its roles.

Groups can be selected with checkboxes in the groups table and deleted together from
the bulk actions bar

See XO-2352
2026-12-02 10:38:24 +01:00
Thierry Goettelmann
8279f3153d chore(xo6): drop XO6/ prefix from changelog entries 2026-12-02 10:38:23 +01:00
Thierry Goettelmann
39dfc5ee46 feat(xo6/group): list the applied roles in the group side panel (#10659)
* feat(xo6/group): list the applied roles in the group side panel

The group side panel only showed the group's details and its users, while
the users side panel already lists the roles applied to a user. The new
card mirrors it, listing the roles assigned to the group with a link to
each of them in the roles list.

See XO-2659

* docs(changelog): add PR link
2026-12-02 10:38:22 +01:00
Thierry Goettelmann
4608251950 feat(xo6/user): add user creation from the users list (#10658)
* feat(xo6/user): add user creation from the users list

A "New" button in the users list opens a multi-step drawer: user details,
groups, roles, then a review where each step can be edited again. Roles
inherited from the selected groups are shown but not assigned directly:
only the additional roles become direct roles of the user.

The user is created first, then added to its groups and assigned its
roles. A username or email address that is already taken shows a
dedicated error, and the drawer stays open so the form can be fixed.

See XO-2358

* fix(xo6/user): add the new user to its groups one at a time to keep every membership

* refactor(xo6/user): reuse the user details locale key in the user creation

* refactor(xo6/user): share the groups and roles selection tables between the drawers

The roles header checkbox is now disabled on a page of inherited roles only.
2026-12-02 10:38:21 +01:00
Thierry Goettelmann
b44333596c feat(xo6/user): show the username, first name and last name of users (#10657)
The users are now shown by their username, which replaces the deprecated
name property, or by their email address when they have none. The users
list and the user side panel also show their first and last names.
2026-12-02 10:38:21 +01:00
Thierry Goettelmann
a0f3436613 fix(xo6/user): list the applied roles in the user side panel (#10656)
* fix(xo6/user): list the applied roles in the user side panel

The "Roles applied" card of the user side panel was a placeholder that
always showed "No role applied". It now lists the roles of the user as in
the mockup: one section per group the roles are inherited from, then the
direct roles.

* refactor(xo6/user): reuse the user groups computed with the user roles in the roles card
2026-12-02 10:38:21 +01:00
Thierry Goettelmann
88fbfd1a7e feat(xo6/privilege): add scope sub-page to the privilege detail page (#10655)
* feat(xo6/privilege): add scope sub-page to the privilege detail page

The Scope sub-page shows which objects a privilege applies to: its scope
type, the query of a dynamic selection, and the table of the objects it
currently applies to, whether selected manually, matched by the query or
covering all the objects of its resource.

See XO-2948

* fix(xo6/role): read the privilege scope type from its resource in the privilege scope page

* fix(xo6/role): show the error state of the objects a privilege currently applies to

* feat(xo6/privilege): show the full objects table in the privilege scope page

As in the mockups, the objects a privilege currently applies to are listed
in the same table as in its creation drawer (columns of the resource, search
engine), read-only, instead of a list of names.
2026-12-02 10:38:17 +01:00
Thierry Goettelmann
2ad7d19662 feat(xo6/privilege): add privilege detail page with its general information (#10654)
* feat(xo6/privilege): add privilege detail page with its general information

The number of a privilege in the privileges table of a role, and the title
of its side panel, now open the privilege's detail page. It opens on
General, which lists the privilege's resource, action and effect, in the
same layout as the other detail pages. The breadcrumb leads back to the
role the privilege belongs to.

See XO-2947

* fix(xo6/role): show the not found page when the privilege cannot be fetched

* refactor(xo6/role): remove the unused panel slot of the privilege detail layout
2026-12-02 10:38:17 +01:00
Thierry Goettelmann
e41c89d25b feat(xo6/role): add privileges sub-page to the role detail page (#10653)
* feat(xo6/role): add privileges sub-page to the role detail page

The Privileges sub-page lists the privileges granted by a role. Selecting one
opens a side panel with its details and its scope: the scope type, the query
of a dynamic selection, and the objects it currently applies to.

The privilege rows of the role side panel are extracted to be shared with
the privilege side panel.

See XO-2946

* fix(xo6/role): read the privilege scope type from its resource in the role privileges

* fix(xo6/role): show the loading and error states of the objects a privilege applies to

* feat(xo6/role): add a search engine to the role privileges table

As in the mockups, the privileges of a role can be filtered by resource,
scope, action and effect.
2026-12-02 10:38:17 +01:00
Thierry Goettelmann
3e2b11bb2d feat(xo6/role): add groups sub-page to the role detail page (#10652)
* feat(xo6/role): add groups sub-page to the role detail page

The Groups sub-page lists the groups a role is assigned to, whose members
inherit it. The role can be assigned to groups from a drawer, synchronized
ones included, and detached from them one by one or by selection.

See XO-2945

* fix(xo6/role): unselect the groups detached from the role groups table

* fix(xo6/role): unselect the groups added back to the role groups table

A group detached from the side panel kept its selection flag, so adding it
back made it reappear selected, ready to be detached by a bulk action.
2026-12-02 10:38:17 +01:00
Thierry Goettelmann
0ae2e903b9 feat(xo6/role): add users sub-page to the role detail page (#10651)
* feat(xo6/role): add users sub-page to the role detail page

The Users sub-page lists the users a role is assigned to, directly or
through their groups. The role can be assigned to users from a drawer, and
detached from its direct users one by one or by selection.

See XO-2944

* fix(xo6/role): disable the users header checkbox on a page of inherited users only

* fix(xo6/role): show the no attached user message in an empty role users table

* fix(xo6/role): unselect the users detached from the role users table

* fix(xo6/role): unselect the users added back to the role users table

A user detached from the side panel kept its selection flag, so adding it
back made it reappear selected, ready to be detached by a bulk action.

* fix(xo6/role): hide the checkbox of the inherited users in the role users table

A user who holds the role through a group cannot be detached from the role,
and the disabled checkbox looked like an active one. As in the mockups, only
the direct users have a checkbox.
2026-12-02 10:38:17 +01:00
Thierry Goettelmann
bb887c46f6 feat(xo6/role): add role detail page with its general information (#10650)
* feat(xo6/role): add role detail page with its general information

The role names in the roles tables and the title of the role side panel now
open the role's detail page. It opens on General, which lists the role's own
information, in the same layout as the user and group detail pages.

See XO-2943

* refactor(xo6/role): reuse the role details locale key in the role details card

* fix(xo6/role): show the role names as plain text in the roles selection drawer
2026-12-02 10:38:17 +01:00
Thierry Goettelmann
758f07c7b5 feat(xo6/group): add users sub-page to the group detail page (#10649)
* feat(xo6/group): add users sub-page to the group detail page

The Users sub-page lists the members of a group. Users can be added to the
group from a drawer, and removed from it one by one or by selection. The
members of a synchronized group are managed by its provider, so they cannot
be changed from XO.

See XO-2942

* refactor(xo6/user): share the formatting of the user providers

* fix(xo6/group): show the no attached user message in an empty group users table

* fix(xo6/group): unselect the users detached from the group users table

* fix(xo6/group): unselect the users added back to the group users table

A user detached from the side panel kept its selection flag, so adding it
back made it reappear selected, ready to be detached by a bulk action.
2026-12-02 10:38:17 +01:00
Thierry Goettelmann
480d34bac2 feat(xo6/group): add roles sub-page to the group detail page (#10648)
* feat(xo6/group): add roles sub-page to the group detail page

The Roles sub-page lists the roles assigned to a group, which all its members
inherit. Roles can be assigned to the group from a drawer, and detached from
it one by one or by selection.

See XO-2941

* fix(xo6/group): unselect the roles detached from the group roles table

* fix(xo6/group): unselect the roles added back to the group roles table

A role detached from the side panel kept its selection flag, so adding it
back made it reappear selected, ready to be detached by a bulk action.
2026-12-02 10:38:16 +01:00
Thierry Goettelmann
e9aca6b844 feat(xo6/group): add group detail page with its general information (#10647)
* feat(xo6/group): add group detail page with its general information

The group names in the groups tables and the title of the group side panel
now open the group's detail page. It opens on General, which lists the
group's own information, in the same layout as the user detail page.

See XO-2940

* fix(xo6/group): show the group names as plain text in the groups selection drawer

* feat(xo6/user): link the group a role is inherited from in the user roles table

As in the mockups, the group column links to the group page. A role inherited
from several groups shows the first one and the number of the others.
2026-12-02 10:38:16 +01:00
Thierry Goettelmann
8d7a072156 feat(xo6/user): add roles sub-page to the user detail page (#10646)
* feat(xo6/user): add roles sub-page to the user detail page

The Roles sub-page lists the roles of a user: the ones assigned directly and
the ones inherited from its groups, with the groups they come from. Roles
can be assigned to the user from a drawer, including roles it already
inherits. Only direct roles can be detached: an inherited role is revoked
from the group.

See XO-2939

* fix(xo6/user): disable the roles header checkbox on a page of inherited roles only

* fix(xo6/user): unselect the roles detached from the user roles table

* refactor(xo6/user): stop exporting getUserRoles

* fix(xo6/user): unselect the roles added back to the user roles table

A role detached from the side panel kept its selection flag, so adding it
back made it reappear selected, ready to be detached by a bulk action.

* fix(xo6/user): hide the checkbox of the inherited roles in the user roles table

An inherited role cannot be detached from the user, and its disabled
checkbox looked like an active one. As in the mockups, only the direct
roles have a checkbox.
2026-12-02 10:38:16 +01:00
Thierry Goettelmann
3aefa5ee86 feat(xo6/user): add groups sub-page to the user detail page (#10645)
* feat(xo6/user): add groups sub-page to the user detail page

The Groups sub-page lists the groups a user belongs to. The user can be
added to several groups at once from a drawer, and detached from one group
or from the selected ones. Synchronized groups are left out of the drawer
and cannot be detached, since the API rejects any change of their users.

The add and remove jobs take groups and users, so the group detail page
can reuse them to manage its members.

See XO-2938

* fix(xo6/group): add or remove group users one at a time to keep every membership

* fix(xo6/user): unselect the groups detached from the user groups table

* fix(xo6/user): unselect the groups added back to the user groups table

A group detached from the side panel kept its selection flag, so adding it
back made it reappear selected, ready to be detached by a bulk action.
2026-12-02 10:38:16 +01:00
Thierry Goettelmann
b3a39c45da feat(xo6/user): add user detail page with its general information (#10644)
* feat(xo6/user): add user detail page with its general information

The username in the users list and in the user side panel now opens the
user's detail page in XO 6, instead of the XO 5 users settings. The page
opens on General, which lists the user's own information, with a side menu
meant to host its other sub-pages.

The side menu layout is shared, so the group, role and privilege detail
pages can reuse it.

See XO-2937

* refactor(xo6): style the detail pages menu without UiMenuList
2026-12-02 10:38:16 +01:00
Thierry Goettelmann
bb144ba2df feat(xo6/role): add role creation with privileges from the roles list (#10605)
* feat(xo6/role): add role creation with privileges from the roles list

Administrators can create a role from the user management page and define
its privileges in the same form, instead of going through XO 5. Each
privilege targets one action on a resource type, scoped to all objects, a
manual selection or a query, with a preview of the matching objects.

See XO-2354

* docs(changelog): add PR link

* fix(xo6/role): move role creation page under /admin

* fix(xo6/role): read an id selector as a manual selection only when the resource allows it

* fix(xo6/role): use a non-breaking space in the role name hint

* refactor(xo6/role): use inline handlers in the new role form

* refactor(xo6/role): use named routes in the privilege scope tables

* refactor(xo6/role): remove the unused info prop of the role textarea

* refactor(xo6/role): remove explanatory comments from the role creation
2026-12-02 10:38:16 +01:00
Thierry Goettelmann
83abb31558 feat(xo6/user): add user deletion from the users list and side panel (#10356)
* feat(user): add user deletion from the users list and side panel

Delete one or more users from the users list row actions, or the
current user from the side panel. A user cannot delete itself.

See XO-2359

* docs(changelog): add PR link

* fix(xo6/user): clear the selected user only once its deletion succeeded

* fix(xo6/user): show the user delete action as a danger action

* refactor(xo6/user): remove a comment from the current user resource

* feat(xo6/user): delete several users at once from the users list

As in the mockups, the users list has a checkbox per row and a Delete table
action that deletes the selected users after confirmation.
2026-12-02 10:38:16 +01:00
Thierry Goettelmann
4e6bde5d99 feat(xo6/role): add role deletion from the roles list and side panel (#10353)
* feat(xo6/role): add role deletion from the side panel

A role that is assigned to users or groups is refused: the delete button
stays disabled and its tooltip states why, so the constraint is visible
before the confirmation modal rather than as a server error afterwards.

Deleting the currently selected role clears the selection, since its
side panel would otherwise stay open on an object that no longer exists.

See XO-2356

* docs(changelog): add PR link

* feat(xo6/role): add role deletion from the roles list

Add a delete action to each row in the roles table, replacing the
selection column with an action column, so a role can be deleted
without opening the side panel first.

See XO-2356

* docs(changelog): merge role deletion changelog entries

* fix(xo6/role): clear the selected role only once its deletion succeeded

* fix(xo6/role): show the role delete action as a danger action

* feat(xo6/role): delete several roles at once from the roles list

As in the mockups, the roles list has a checkbox per row and a Delete table
action that deletes the selected roles after confirmation.
2026-12-02 10:38:16 +01:00
Thierry Goettelmann
f0937427ad feat(xo6/role): add side panel to the roles list (#10330)
* feat(xo6/role): add side panel to the roles list

Selecting a role in the list opens a side panel showing its description,
its privileges, and the users and groups it is assigned to. Users are
split between those holding the role directly and those inheriting it
from a group.

* docs(changelog): add PR link

* refactor(xo6/role): use logicAnd and logicOr in the role users card
2026-12-02 10:38:15 +01:00
Thierry Goettelmann
886637cf11 feat(xo6/role): add roles list in user management page (#10301)
* feat(xo6/role): add roles list in user management page

* docs(changelog): add PR link

* fix(xo6/role): count users inherited from groups in the users column

The column read `role.userIds`, which the server fills from the direct
user-role assignments only. A role assigned to one user and to a group
of eight was listed as having a single user, and the side panel, which
counts the effective users, contradicted it on the same screen.

The count now unions the direct users with the members of the role's
groups, deduplicated since a user can hold the role both ways. The page
waits for the groups collection so the column does not first show the
direct count then jump to the effective one.

* fix(xo6/role): wait for groups in the roles table and test user counting

The users column now depends on the groups collection, but only the page
waited for it. The table now handles the groups loading and error states
itself, like HostsTable does for PIFs, so any consumer gets a correct
count and the page no longer subscribes to groups only for this.

Add unit tests for getRoleUserIds, which deduplicates users holding a
role both directly and through groups, and drop a comment that only
restated the code.

* fix(xo6/role): refresh the roles table through SSE

The roles list was only refreshed by the default 30 s polling, while the
users and groups it counts from are already streamed. Subscribe to the
`acl-role` events so that role, user and group changes show up at once.

Template roles are rewritten each time xo-server starts and the SSE does
not apply the `!isTemplate?` filter, so they are dropped client-side with
a predicate.

Also use a non-breaking space before the question mark of the French
"What is a role?" title.
2026-12-02 10:38:15 +01:00
Thierry Goettelmann
bc402c6c2d feat(xo6/group): add side panel to the groups list (#10291)
* feat(xo6/group): add side panel to the groups list

Selecting a group in the list opens a panel showing its identifier, its
provider and the users it contains, following the layout the users page
already uses.

Now that the panel reads the selected group from the `id` query
parameter, the groups listed in a user's panel can finally point at it.
They linked to the XO 5 settings page until now, for lack of an XO 6
destination. Both cards end up mirroring each other: group to users, and
user to groups.

* docs(changelog): add PR link
2026-12-02 10:38:15 +01:00
Thierry Goettelmann
388e48b3d1 feat(xo6/group): add groups list in user management page (#10272) 2026-12-02 10:38:14 +01:00
256 changed files with 11411 additions and 873 deletions

View File

@@ -8,28 +8,9 @@ export type SupportedResource = XoAclSupportedResource<SupportedActionsByResourc
export type SupportedActions<T extends SupportedResource> = XoAclSupportedActions<SupportedActionsByResource, T>
export type TPrivilege<T extends SupportedResource> = XoAclPrivilege<SupportedActionsByResource, T>
export const UNKNOWN = Symbol('UNKNOWN')
/**
* Lists the top-level fields read by a selector.
*/
function getSelectorFields(node: CM.Node): string[] {
if (node instanceof CM.Property || node instanceof CM.TruthyProperty) {
return [node.name]
}
if (node instanceof CM.Not) {
return getSelectorFields(node.child)
}
if (node instanceof CM.And || node instanceof CM.Or) {
return node.children.flatMap(getSelectorFields)
}
return node instanceof CM.Null ? [] : ['*']
}
export class Privilege<T extends SupportedResource> {
#action: TPrivilege<T>['action']
#selector?: (object: object) => boolean
#selectorFields: string[] = []
#resource: TPrivilege<T>['resource']
#effect: TPrivilege<T>['effect']
@@ -47,14 +28,9 @@ export class Privilege<T extends SupportedResource> {
Privilege.checkActionIsValid(resource, action)
this.#action = action
this.#selector = selector !== undefined ? CM.parse(selector).createPredicate() : undefined
this.#resource = resource
this.#effect = effect
if (selector !== undefined) {
const node = CM.parse(selector)
this.#selector = node.createPredicate()
this.#selectorFields = getSelectorFields(node)
}
}
get effect() {
@@ -68,20 +44,11 @@ export class Privilege<T extends SupportedResource> {
return this.#action === '*' || this.#action === action || action.startsWith(`${this.#action}:`)
}
#matchSelector(object: object, knownFields?: string[]) {
#matchSelector(object: object) {
if (this.#selector === undefined) {
return true
}
// `*` is a term not bound to a property (e.g. `foo`), it may match any field, including missing ones
// The `*` check is there to handle the case where a `*` field would exist
if (
knownFields !== undefined &&
this.#selectorFields.some(field => field === '*' || !(field in object || knownFields.includes(field)))
) {
return UNKNOWN
}
return this.#selector(object)
}
@@ -93,12 +60,11 @@ export class Privilege<T extends SupportedResource> {
action: SupportedActions<Resource>
resource: Resource
object: object
knownFields?: string[]
}): boolean | typeof UNKNOWN {
}): boolean {
return (
this.#matchResource(constraint.resource) &&
this.#matchAction(constraint.action) &&
this.#matchSelector(constraint.object, constraint.knownFields)
this.#matchSelector(constraint.object)
)
}

View File

@@ -7,7 +7,6 @@ import {
SupportedActions,
SupportedActionsByResource,
SupportedResource,
UNKNOWN,
} from './class/privilege.mjs'
// Export all types constructed using SUPPORTED_ACTIONS_BY_RESOURCE
@@ -24,7 +23,6 @@ export type AnyPrivilegeOnParam = {
resource: Resource
action: SupportedActions<Resource>
objects: object | object[]
knownFields?: string[]
}
}[SupportedResource]
@@ -34,14 +32,12 @@ export function hasPrivilegeOn<T extends SupportedResource>({
resource,
objects,
userPrivileges,
knownFields,
}: {
user: XoUser
resource: T
action: SupportedActions<T>
objects: object | object[]
userPrivileges: AnyPrivilege[]
knownFields?: string[]
}) {
// Function that will be called outside of the module
// We cannot be sure types are respected
@@ -67,7 +63,7 @@ export function hasPrivilegeOn<T extends SupportedResource>({
return true
}
const effectsByObject = new Map<object, { known: boolean; effect: Privilege<T>['effect'] }[]>()
const effectsByObject = new Map<object, Privilege<T>['effect'][]>()
if (Array.isArray(objects)) {
objects.forEach(obj => effectsByObject.set(obj, []))
} else {
@@ -78,49 +74,20 @@ export function hasPrivilegeOn<T extends SupportedResource>({
const privilege = new CPrivilege(userPrivilege as Privilege<typeof userPrivilege.resource>)
for (const [object, effects] of effectsByObject.entries()) {
const result = privilege.match({ action, resource, object, knownFields })
if (!result) {
if (!privilege.match({ action, resource, object })) {
continue
}
effects.push({ known: result !== UNKNOWN, effect: privilege.effect })
effects.push(privilege.effect)
}
}
let isUndecidable = false
for (const effects of effectsByObject.values()) {
let hasAllow = false
let hasKnownAllow = false
let hasUnknownDeny = false
for (const { known, effect } of effects) {
if (effect === 'allow') {
hasAllow = true
hasKnownAllow ||= known
} else if (known) {
return false
} else {
hasUnknownDeny = true
}
}
if (!hasAllow) {
return false
}
// do not throw yet: another object may still be known to be denied
if (hasUnknownDeny || !hasKnownAllow) {
isUndecidable = true
}
}
if (isUndecidable) {
const error: Error & { code?: string } = new Error(
`The privilege couldn't be decided because the object is missing fields the selectors need. action: ${action}, resource: ${resource}`
if (
Array.from(effectsByObject.values()).some(
effects => effects.length === 0 || effects.some(effect => effect === 'deny')
)
error.code = 'RBAC_UNKNOWN_RESULT'
throw error
) {
return false
}
return true
}
@@ -134,7 +101,6 @@ export function getMissingPrivileges(params: AnyPrivilegeOnParam[], userPrivileg
action: param.action as SupportedActions<typeof param.resource>,
objects: param.objects,
userPrivileges,
knownFields: param.knownFields,
})
)
.map(({ action, objects, resource }) => {
@@ -176,7 +142,6 @@ export function filterObjectsWithPrivilege<Resource extends SupportedResource, O
action: SupportedActions<Resource>
objects: Object[]
userPrivileges: AnyPrivilege[]
knownFields?: string[]
}) {
return param.objects.filter(obj => hasPrivilegeOn({ ...param, objects: obj }))
}

View File

@@ -3,7 +3,7 @@ import assert from 'node:assert'
import type { Branded } from '@vates/types/common'
import type { XoUser } from '@vates/types/xo'
import { Privilege, UNKNOWN } from '../class/privilege.mjs'
import { Privilege } from '../class/privilege.mjs'
import type { Privilege as TPrivilege } from '../index.mjs'
import {
filterObjectsWithPrivilege,
@@ -81,108 +81,6 @@ suite('Privilege.match behavior', () => {
const vmImportPrivilege = new Privilege({ action: 'import:vm', resource: 'sr', effect: 'allow' })
assert.strictEqual(vmImportPrivilege.match({ resource: 'sr', action: 'import:vdi:url', object }), false)
})
suite('on a partial object', () => {
const ownVmPrivilege = new Privilege({
action: 'read',
resource: 'vm',
selector: 'creation:creator:2',
effect: 'allow',
})
const partialObject = { id: 'alma' }
test('Should not match a missing property if known fields are not provided', () => {
assert.strictEqual(ownVmPrivilege.match({ resource: 'vm', action: 'read', object: partialObject }), false)
})
test('Should not match a missing property if it is a known field', () => {
assert.strictEqual(
ownVmPrivilege.match({
resource: 'vm',
action: 'read',
object: partialObject,
knownFields: ['id', 'creation'],
}),
false
)
})
test('Should return UNKNOWN if the selector uses an unknown field', () => {
assert.strictEqual(
ownVmPrivilege.match({ resource: 'vm', action: 'read', object: partialObject, knownFields: ['id'] }),
UNKNOWN
)
})
test('Should not match because of the resource even if the selector is unknown', () => {
assert.strictEqual(
ownVmPrivilege.match({ resource: 'host', action: 'read', object: partialObject, knownFields: ['id'] }),
false
)
})
test('Should not match because of the action even if the selector is unknown', () => {
assert.strictEqual(
ownVmPrivilege.match({ resource: 'vm', action: 'start', object: partialObject, knownFields: ['id'] }),
false
)
})
test('Should match without selector', () => {
assert.strictEqual(
privilege.match({ resource: 'vm', action: 'read', object: partialObject, knownFields: [] }),
true
)
})
test('Should resolve a field present on the object even if it is not listed', () => {
assert.strictEqual(
ownVmPrivilege.match({
resource: 'vm',
action: 'read',
object: { creation: { creator: '2' } },
knownFields: [],
}),
true
)
})
test('Should resolve a field provided by a getter', () => {
class Vm {
get creation() {
return { creator: '2' }
}
}
assert.strictEqual(
ownVmPrivilege.match({ resource: 'vm', action: 'read', object: new Vm(), knownFields: [] }),
true
)
})
test('Should return UNKNOWN on a term not bound to a property', () => {
const bareTermPrivilege = new Privilege({ action: 'read', resource: 'vm', selector: 'alma', effect: 'allow' })
assert.strictEqual(
bareTermPrivilege.match({ resource: 'vm', action: 'read', object: partialObject, knownFields: ['id'] }),
UNKNOWN
)
})
test('Should return UNKNOWN if one of the fields is unknown, even if the others decide the result', () => {
const orPrivilege = new Privilege({
action: 'read',
resource: 'vm',
selector: '|(id:alma creation:creator:2)',
effect: 'allow',
})
assert.strictEqual(
orPrivilege.match({ resource: 'vm', action: 'read', object: partialObject, knownFields: ['id'] }),
UNKNOWN
)
})
})
})
suite('ACL V2 behavior', async () => {
@@ -499,205 +397,6 @@ suite('ACL V2 behavior', async () => {
assert.strictEqual(vms.length, 2)
})
})
suite('partial objects behavior', () => {
const UNKNOWN_RESULT = { code: 'RBAC_UNKNOWN_RESULT' }
const vmReadAll = {
id: privilegeId,
action: 'read',
resource: 'vm',
effect: 'allow',
roleId,
} satisfies TPrivilege<'vm'>
const vmReadOwn = {
id: privilegeId,
action: 'read',
resource: 'vm',
selector: `creation:creator:${user.id}`,
effect: 'allow',
roleId,
} satisfies TPrivilege<'vm'>
const vmDenyReadOnPool = {
id: privilegeId,
action: 'read',
resource: 'vm',
selector: '$pool:2',
effect: 'deny',
roleId,
} satisfies TPrivilege<'vm'>
const partialVm = { id: 'partial-vm' }
const partialVmOnDeniedPool = { id: 'partial-vm-denied', $pool: '2' }
suite('hasPrivilegeOn', () => {
test('Should always return true for admin', () => {
assert.strictEqual(
hasPrivilegeOn({
user: admin,
action: 'read',
resource: 'vm',
objects: partialVm,
knownFields: ['id'],
userPrivileges: [vmReadOwn],
}),
true
)
})
test('Should keep the current behavior if known fields are not provided', () => {
assert.strictEqual(
hasPrivilegeOn({ user, action: 'read', resource: 'vm', objects: partialVm, userPrivileges: [vmReadOwn] }),
false
)
})
test('Should throw if the only allow privilege is unknown', () => {
assert.throws(
() =>
hasPrivilegeOn({
user,
action: 'read',
resource: 'vm',
objects: partialVm,
knownFields: ['id'],
userPrivileges: [vmReadOwn],
}),
UNKNOWN_RESULT
)
})
test('Should return false if the unknown field is known to be absent', () => {
assert.strictEqual(
hasPrivilegeOn({
user,
action: 'read',
resource: 'vm',
objects: partialVm,
knownFields: ['id', 'creation'],
userPrivileges: [vmReadOwn],
}),
false
)
})
test('Should return true if an allow privilege is known even if another one is unknown', () => {
assert.strictEqual(
hasPrivilegeOn({
user,
action: 'read',
resource: 'vm',
objects: partialVm,
knownFields: ['id'],
userPrivileges: [vmReadOwn, vmReadAll],
}),
true
)
})
test('Should throw if a deny privilege is unknown, even with a known allow privilege', () => {
assert.throws(
() =>
hasPrivilegeOn({
user,
action: 'read',
resource: 'vm',
objects: partialVm,
knownFields: ['id'],
userPrivileges: [vmReadAll, vmDenyReadOnPool],
}),
UNKNOWN_RESULT
)
})
test('Should return true if a deny privilege is known not to match', () => {
assert.strictEqual(
hasPrivilegeOn({
user,
action: 'read',
resource: 'vm',
objects: partialVm,
knownFields: ['id', '$pool'],
userPrivileges: [vmReadAll, vmDenyReadOnPool],
}),
true
)
})
test('Should return false if a deny privilege is known to match, even with an unknown allow privilege', () => {
assert.strictEqual(
hasPrivilegeOn({
user,
action: 'read',
resource: 'vm',
objects: partialVmOnDeniedPool,
knownFields: ['id', '$pool'],
userPrivileges: [vmReadOwn, vmDenyReadOnPool],
}),
false
)
})
test('Should return false if one of the objects is known to be denied, even if another one is unknown', () => {
assert.strictEqual(
hasPrivilegeOn({
user,
action: 'read',
resource: 'vm',
objects: [partialVm, partialVmOnDeniedPool],
knownFields: ['id'],
userPrivileges: [vmReadAll, vmDenyReadOnPool],
}),
false
)
})
test('Should throw if the other objects are allowed and one is unknown', () => {
assert.throws(
() =>
hasPrivilegeOn({
user,
action: 'read',
resource: 'vm',
objects: [{ id: 'allowed-vm', $pool: '1' }, partialVm],
knownFields: ['id'],
userPrivileges: [vmReadAll, vmDenyReadOnPool],
}),
UNKNOWN_RESULT
)
})
})
suite('getMissingPrivileges', () => {
test('Should throw if a privilege is unknown', () => {
assert.throws(
() =>
getMissingPrivileges(
[{ user, action: 'read', resource: 'vm', objects: partialVm, knownFields: ['id'] }],
[vmReadOwn]
),
UNKNOWN_RESULT
)
})
})
suite('filterObjectsWithPrivilege', () => {
test('Should throw if a privilege is unknown on one of the objects', () => {
assert.throws(
() =>
filterObjectsWithPrivilege({
user,
action: 'read',
resource: 'vm',
objects: [partialVm],
knownFields: ['id'],
userPrivileges: [vmReadOwn],
}),
UNKNOWN_RESULT
)
})
})
})
})
suite('getActionStrings', () => {

View File

@@ -6,6 +6,7 @@
prop('accent').required().enum('brand', 'info', 'warning', 'danger').preset('brand').widget(),
prop('size').required().enum('small', 'medium', 'large').preset('medium').widget(),
prop('disabled').bool().widget(),
prop('restricted').bool().widget(),
prop('selected').bool().widget(),
prop('counter')
.type('CounterValue | { value: CounterValue; accent: CounterAccent }')

View File

@@ -12,6 +12,7 @@
prop('size').type('ButtonSize').enum('small', 'medium').preset('medium').required().widget(),
prop('busy').bool().widget(),
prop('disabled').bool().widget().ctx(),
prop('restricted').bool().widget(),
prop('lockIcon').bool().widget(),
iconProp('leftIcon'),
iconProp('rightIcon'),

View File

@@ -89,7 +89,7 @@ const CONTROLLER_PREFIXES = {
* 'config.annotation'?: string,
* 'config.instanceUuid'?: string,
* 'config.firmware'?: string,
* 'config.bootOptions'?: { efiSecureBootEnabled?: unknown },
* 'config.bootOptions.efiSecureBootEnabled'?: unknown,
* 'config.template'?: unknown,
* 'config.hardware.numCPU'?: unknown,
* 'config.hardware.memoryMB'?: unknown,
@@ -379,7 +379,7 @@ export function buildInventory({
annotation: properties['config.annotation'],
instanceUuid: properties['config.instanceUuid'],
firmware: firmware === 'efi' ? 'uefi' : firmware,
secureBoot: isTrue(properties['config.bootOptions']?.efiSecureBootEnabled),
secureBoot: isTrue(properties['config.bootOptions.efiSecureBootEnabled']),
isTemplate: isTrue(properties['config.template']),
cpus: toNumber(properties['config.hardware.numCPU']),
memory: memoryMb === undefined ? undefined : memoryMb * 1024 * 1024,

View File

@@ -1,14 +1,7 @@
import assert from 'node:assert/strict'
import { describe, it } from 'node:test'
import {
buildInventory,
countSnapshots,
findDatacenter,
parseDevices,
parseGuestNics,
parseVlan,
} from './_inventory.mjs'
import { countSnapshots, findDatacenter, parseDevices, parseGuestNics, parseVlan } from './_inventory.mjs'
// shaped as the SOAP library returns them: the nested references and types are not normalized
const typed = (type, value) => ({ attributes: { 'xsi:type': type }, ...value })
@@ -209,37 +202,3 @@ describe('findDatacenter', function () {
assert.equal(findDatacenter('group-a', loop, datacenterIds), undefined)
})
})
describe('buildInventory', function () {
const EMPTY = {
about: {},
datacenters: {},
clusters: {},
hosts: {},
datastores: {},
networks: {},
portgroups: {},
folders: {},
computeResources: {},
}
it('reads secure boot from the boot options, absent before vSphere 6.5', function () {
const { vms } = buildInventory({
...EMPTY,
vms: {
'vm-65': { 'config.bootOptions': { efiSecureBootEnabled: 'true' } },
// ESXi 6.0: the boot options have no `efiSecureBootEnabled`
'vm-60': { 'config.bootOptions': { bootDelay: '0' } },
'vm-none': {},
},
})
assert.deepEqual(
vms.map(({ id, secureBoot }) => ({ id, secureBoot })),
[
{ id: 'vm-65', secureBoot: true },
{ id: 'vm-60', secureBoot: false },
{ id: 'vm-none', secureBoot: false },
]
)
})
})

View File

@@ -623,9 +623,7 @@ export default class Esxi extends EventEmitter {
'config.annotation',
'config.instanceUuid',
'config.firmware',
// the whole object rather than `config.bootOptions.efiSecureBootEnabled`: that property only
// exists since vSphere 6.5, and an unknown path fails the whole request (InvalidProperty)
'config.bootOptions',
'config.bootOptions.efiSecureBootEnabled',
'config.template',
'config.hardware.numCPU',
'config.hardware.memoryMB',
@@ -1136,11 +1134,9 @@ export default class Esxi extends EventEmitter {
* @returns {Promise<object>} the `info` of the successful task
*/
async snapshot(vmId, name, description, { signal, timeout = 30 * 60e3 } = {}) {
// not `CreateSnapshotEx_Task`: it only exists since vSphere 8 (absent from the WSDL of older
// hosts), and its only addition, the quiesce spec, is not used
return this.#runTask(
'CreateSnapshot_Task',
{ _this: vmId, name, description, memory: false, quiesce: false },
'CreateSnapshotEx_Task',
{ _this: vmId, name, description, memory: false },
{ signal, timeout }
)
}

View File

@@ -696,7 +696,7 @@ describe('tasks', function () {
const controller = new AbortController()
const { esxi, vimClient } = await connectedEsxi({
responses: {
CreateSnapshot_Task: () => startedTask(),
CreateSnapshotEx_Task: () => startedTask(),
RetrievePropertiesEx: () => {
controller.abort()
return taskInfo('running')

View File

@@ -18,6 +18,7 @@
# Directives
- [vRestricted](../lib/directives/restricted.directive.md)
- [vTooltip](../lib/directives/tooltip.directive.md)
# Utils

View File

@@ -59,12 +59,13 @@ Testing uses **Vitest 5** with a single `unit` project (see `vitest.config.ts`):
| `test/expect-loader.ts` | `hasLoader(wrapper)`: whether a `UiLoader` is rendered; `expectLoaderInsteadOf(wrapper, findContent)`: a `UiLoader` shown and the content it stands for empty (also used by XO 6) |
| `test/select.ts` | `openSelect`, `findShownSelections`, `findSelectOptionLabels`, `pickSelectOption(wrapper, label, { detailed? })`: opens a `VtsSelect`, reads the selection it shows, reads or picks its options (`detailed`: the option shows details after its label); `chooseSelectOption(wrapper, label, { container?, detailed? })`: opens the select inside `container`, then picks the option (also used by XO 6) |
| `test/is-placeholder-shown.ts` | `isPlaceholderShown(field)`: whether a readonly input shows its placeholder in place of its value |
| `test/can-focus-input.ts` | `canFocusInput(wrapper)`: whether the first input of a wrapper attached to the document takes the focus, which an `inert` ancestor prevents |
| `test/inject-or-throw.ts` | `injectOrThrow(key)`: `inject(key)`, throwing when nothing provides it |
| `test/mount-with-setup.ts` | `mountWithSetup(setup, { global?, attachTo? })`: mounts a component whose `setup` sets up what its render needs below it (a select, a provided context) and returns that render (XO 6 wraps it with its config); `mountWithSetupResult(setup, options)`: the same, keeping what `setup` builds (a form, a composable's return), `setup` returning `{ result, render }`, returns `{ wrapper, result }`; `mountComposableUnderSetup(setup, composable, options)`: runs `composable` (given what `setup` returned) in a child of the component whose `setup` provides what it injects, returns `{ provided, result }` |
| `test/mount-with-select.ts` | `renderSelect(id, { accent?, ref? }, slots?)`: renders the `VtsSelect` of a select id, `neutral` accent by default; `mountSelect`: a `VtsSelect` of string sources, its config, accent, wrapper message, option slot and a callback receiving the mounted select |
| `test/find-title.ts` | `findTitle`: the `.title` of a `VtsSuccessStateHero` or a list item, `undefined` without one (also used by XO 6) |
| `test/create-task-item.ts` | `createTaskItem`: a `Task` as the task lists display it, with the given overrides (also used by XO 6) |
| `test/find-tooltip-contents.ts` | `findTooltipContents`: the content of every tooltip currently shown, in order |
| `test/hover.ts` | `hover`: moves the mouse over an element |
| `tsconfig.vitest.json` | Type-checks test files with the Vitest globals and the `@core-test` alias |
| `tsconfig.app.json` | Type-checks the library, test files excluded |

View File

@@ -46,7 +46,7 @@ const columnTransition = `grid-template-columns ${PANEL_TRANSITION_DURATION}ms`
display: grid;
grid-template-columns: minmax(0, 1fr) 0;
grid-template-rows: minmax(0, 1fr);
overflow: clip;
overflow: hidden;
.content {
overflow-y: auto;

View File

@@ -1,38 +0,0 @@
import VtsLayoutSidebar from '@core/components/layout/VtsLayoutSidebar.vue'
import { useRightSidebarStore } from '@core/packages/sidebar'
import { canFocusInput } from '@core-test/can-focus-input.ts'
import { createGlobalTestConfig } from '@core-test/create-global-test-config.ts'
import { mount } from '@vue/test-utils'
import { h, nextTick } from 'vue'
beforeEach(() => {
localStorage.clear()
})
function mountSidebar({ isExpanded }: { isExpanded: boolean }) {
localStorage.setItem('sidebar.right.expanded', String(isExpanded))
return mount(VtsLayoutSidebar, {
props: { side: 'right' },
slots: { default: () => h('input') },
global: createGlobalTestConfig(),
attachTo: document.body,
})
}
it('lets the focus into an expanded sidebar', () => {
expect(canFocusInput(mountSidebar({ isExpanded: true }))).toBe(true)
})
it('keeps the focus out of a collapsed sidebar', () => {
expect(canFocusInput(mountSidebar({ isExpanded: false }))).toBe(false)
})
it('lets the focus in once the sidebar expands', async () => {
const wrapper = mountSidebar({ isExpanded: false })
useRightSidebarStore().toggleExpand(true)
await nextTick()
expect(canFocusInput(wrapper)).toBe(true)
})

View File

@@ -1,5 +1,5 @@
<template>
<div :class="className" class="vts-layout-sidebar" :inert="!sidebar.isExpanded">
<div :class="className" class="vts-layout-sidebar">
<VtsResizeHandle v-if="showResizeHandle" :position="resizeHandlePosition" :resizable="sidebar" />
<div v-if="slots.header || (showLock && !ui.isSmall)" class="header">
<div v-if="slots.header" class="start">

View File

@@ -1,36 +0,0 @@
import VtsSidePanel from '@core/components/panel/VtsSidePanel.vue'
import { canFocusInput } from '@core-test/can-focus-input.ts'
import { createGlobalTestConfig } from '@core-test/create-global-test-config.ts'
import { mount } from '@vue/test-utils'
import { h } from 'vue'
beforeEach(() => {
localStorage.clear()
})
function mountPanel({ hasSelection }: { hasSelection: boolean }) {
localStorage.setItem('panel.locked', 'false')
return mount(VtsSidePanel, {
props: { hasSelection, persistent: true },
slots: { default: () => h('input') },
global: createGlobalTestConfig(),
attachTo: document.body,
})
}
it('lets the focus into a panel that a selection expands', () => {
expect(canFocusInput(mountPanel({ hasSelection: true }))).toBe(true)
})
it('keeps the focus out of a collapsed panel', () => {
expect(canFocusInput(mountPanel({ hasSelection: false }))).toBe(false)
})
it('lets the focus in once a selection expands the panel', async () => {
const wrapper = mountPanel({ hasSelection: false })
await wrapper.setProps({ hasSelection: true })
expect(canFocusInput(wrapper)).toBe(true)
})

View File

@@ -1,6 +1,6 @@
<!-- v5 -->
<template>
<div class="vts-side-panel" :class="{ mobile: uiStore.isSmall }" :inert="!panelStore.isExpanded">
<div class="vts-side-panel" :class="{ mobile: uiStore.isSmall }">
<VtsResizeHandle v-if="showResizeHandle" position="start" :resizable="panelStore" />
<VtsPanel
:closable="isClosable"

View File

@@ -1,8 +1,8 @@
<template>
<UiTableCell :flexible>
<div class="user-name">
<div class="username">
<UiUserLogo size="small" />
<UiLink :href size="medium" class="link">
<UiLink :to :href size="medium" class="link">
<VtsMiddleEllipsis v-if="flexible" :text="content" />
<span v-else v-tooltip class="text-ellipsis">{{ content }}</span>
</UiLink>
@@ -15,17 +15,19 @@ import VtsMiddleEllipsis from '@core/components/middle-ellipsis/VtsMiddleEllipsi
import UiLink from '@core/components/ui/link/UiLink.vue'
import UiTableCell from '@core/components/ui/table-cell/UiTableCell.vue'
import UiUserLogo from '@core/components/ui/user-logo/UiUserLogo.vue'
import type { LinkOptions } from '@core/composables/link-component.composable.ts'
import { vTooltip } from '@core/directives/tooltip.directive.ts'
defineProps<{
content: string
href?: string
flexible?: boolean
}>()
defineProps<
Pick<LinkOptions, 'to' | 'href'> & {
content: string
flexible?: boolean
}
>()
</script>
<style scoped lang="postcss">
.user-name {
.username {
display: flex;
align-items: center;
gap: 0.8rem;

View File

@@ -0,0 +1,47 @@
import UiButtonIcon from '@core/components/ui/button-icon/UiButtonIcon.vue'
import { createGlobalTestConfig } from '@core-test/create-global-test-config.ts'
import { mount } from '@vue/test-utils'
function mountButtonIcon({ restricted = false }: { restricted?: boolean } = {}) {
const onClick = vi.fn()
const wrapper = mount(UiButtonIcon, {
global: createGlobalTestConfig(),
props: { icon: 'fa:trash', accent: 'brand', size: 'medium', restricted },
attrs: { onClick },
})
return { wrapper, onClick }
}
it('is marked as disabled but stays focusable when restricted', () => {
const { wrapper } = mountButtonIcon({ restricted: true })
expect(wrapper.attributes('aria-disabled')).toBe('true')
expect(wrapper.attributes('disabled')).toBeUndefined()
})
it('is not marked as disabled by default', () => {
const { wrapper } = mountButtonIcon()
expect(wrapper.attributes('aria-disabled')).toBeUndefined()
})
it('has the muted variant when restricted', () => {
const restrictedButtonIcon = mountButtonIcon({ restricted: true })
const buttonIcon = mountButtonIcon()
expect(restrictedButtonIcon.wrapper.classes()).toContain('muted')
expect(buttonIcon.wrapper.classes()).not.toContain('muted')
})
it('runs its click listener only when not restricted', async () => {
const restrictedButtonIcon = mountButtonIcon({ restricted: true })
const buttonIcon = mountButtonIcon()
await restrictedButtonIcon.wrapper.trigger('click')
await buttonIcon.wrapper.trigger('click')
expect(restrictedButtonIcon.onClick).not.toHaveBeenCalled()
expect(buttonIcon.onClick).toHaveBeenCalledTimes(1)
})

View File

@@ -1,7 +1,7 @@
<!-- v10 -->
<!-- v11 -->
<!-- TODO: Add complex icon -->
<template>
<button :class="classNames" :disabled class="ui-button-icon" type="button">
<button v-restricted="restricted" :class="classNames" :disabled class="ui-button-icon" type="button">
<VtsIcon :name="icon" size="current" />
<UiCounter v-if="counterProps !== undefined" v-bind="counterProps" size="small" variant="primary" class="counter" />
</button>
@@ -10,6 +10,7 @@
<script lang="ts" setup>
import VtsIcon from '@core/components/icon/VtsIcon.vue'
import UiCounter, { type CounterAccent, type CounterValue } from '@core/components/ui/counter/UiCounter.vue'
import { vRestricted } from '@core/directives/restricted.directive.ts'
import type { IconName } from '@core/icons'
import { toVariants } from '@core/utils/to-variants.util.ts'
import { computed } from 'vue'
@@ -18,11 +19,12 @@ export type ButtonIconAccent = 'brand' | 'info' | 'warning' | 'danger'
export type ButtonIconSize = 'small' | 'medium' | 'large'
const { accent, size, disabled, selected, counter, targetScale } = defineProps<{
const { accent, size, disabled, restricted, selected, counter, targetScale } = defineProps<{
icon: IconName
size: ButtonIconSize
accent: ButtonIconAccent
disabled?: boolean
restricted?: boolean
selected?: boolean
counter?: CounterValue | { value: CounterValue; accent: CounterAccent }
targetScale?: number | { x: number; y: number }
@@ -55,7 +57,7 @@ const classNames = computed(() => {
toVariants({
accent,
size,
muted: disabled,
muted: disabled || restricted,
selected,
}),
]
@@ -74,7 +76,7 @@ const classNames = computed(() => {
cursor: pointer;
outline: none;
&:disabled {
&.muted {
cursor: not-allowed;
}

View File

@@ -0,0 +1,48 @@
import UiButton from '@core/components/ui/button/UiButton.vue'
import { createGlobalTestConfig } from '@core-test/create-global-test-config.ts'
import { mount } from '@vue/test-utils'
function mountButton({ restricted = false }: { restricted?: boolean } = {}) {
const onClick = vi.fn()
const wrapper = mount(UiButton, {
global: createGlobalTestConfig(),
props: { variant: 'primary', accent: 'brand', size: 'medium', restricted },
attrs: { onClick },
slots: { default: 'Label' },
})
return { wrapper, onClick }
}
it('is marked as disabled but stays focusable when restricted', () => {
const { wrapper } = mountButton({ restricted: true })
expect(wrapper.attributes('aria-disabled')).toBe('true')
expect(wrapper.attributes('disabled')).toBeUndefined()
})
it('is not marked as disabled by default', () => {
const { wrapper } = mountButton()
expect(wrapper.attributes('aria-disabled')).toBeUndefined()
})
it('has the disabled variant when restricted', () => {
const restrictedButton = mountButton({ restricted: true })
const button = mountButton()
expect(restrictedButton.wrapper.classes()).toContain('disabled')
expect(button.wrapper.classes()).not.toContain('disabled')
})
it('runs its click listener only when not restricted', async () => {
const restrictedButton = mountButton({ restricted: true })
const button = mountButton()
await restrictedButton.wrapper.trigger('click')
await button.wrapper.trigger('click')
expect(restrictedButton.onClick).not.toHaveBeenCalled()
expect(button.onClick).toHaveBeenCalledTimes(1)
})

View File

@@ -1,6 +1,12 @@
<!-- v7 -->
<!-- v9 -->
<template>
<button :class="classNames" :disabled="busy || isDisabled || lockIcon" class="ui-button" type="button">
<button
v-restricted="restricted"
:class="classNames"
:disabled="busy || isDisabled || lockIcon"
class="ui-button"
type="button"
>
<VtsIcon :name="leftIcon" class="icon" size="current" />
<slot />
<VtsIcon :name="rightIcon" class="icon" size="current" />
@@ -13,6 +19,7 @@
import VtsIcon from '@core/components/icon/VtsIcon.vue'
import UiLoader from '@core/components/ui/loader/UiLoader.vue'
import { useDisabled } from '@core/composables/disabled.composable.ts'
import { vRestricted } from '@core/directives/restricted.directive.ts'
import type { IconName } from '@core/icons'
import { toVariants } from '@core/utils/to-variants.util.ts'
import { computed } from 'vue'
@@ -27,12 +34,13 @@ export type ButtonProps = {
size: ButtonSize
busy?: boolean
disabled?: boolean
restricted?: boolean
lockIcon?: boolean
leftIcon?: IconName
rightIcon?: IconName
}
const { accent, variant, size, disabled, busy, lockIcon } = defineProps<ButtonProps>()
const { accent, variant, size, disabled, restricted, busy, lockIcon } = defineProps<ButtonProps>()
defineSlots<{
default(): any
@@ -54,7 +62,7 @@ const classNames = computed(() => [
size,
busy,
lock: lockIcon,
disabled: isDisabled.value,
disabled: isDisabled.value || restricted,
}),
])
</script>

View File

@@ -2,7 +2,7 @@
<template>
<div class="ui-log-entry-viewer" :class="className">
<div class="label-container">
<div :class="fontClasses.labelClass" class="label">
<div v-if="label" :class="fontClasses.labelClass" class="label">
{{ label }}
</div>
<div class="actions">
@@ -36,7 +36,7 @@ const {
accent,
content: rawContent = '',
} = defineProps<{
label: string
label?: string
content: string | object | undefined
size: LogEntryViewerSize
accent: LogEntryViewerAccent
@@ -104,6 +104,7 @@ function openRawValueInNewTab() {
}
.actions {
margin-inline-start: auto;
display: flex;
gap: 0.8rem;
align-items: center;

View File

@@ -0,0 +1,33 @@
# Restricted Directive
Marks an action the user has no permission to run.
When its value is `true`, the element:
- keeps the keyboard focus, but is announced as disabled (`aria-disabled="true"`)
- ignores clicks
- shows a "Permission required" tooltip on hover and on keyboard focus, in place of any other tooltip it has
The directive adds no style. The component that uses it styles its restricted state.
## Usage
Use the directive inside a component, on the native element that runs the action.
Do not use it on a component. Give the component a `restricted` prop, and let it apply the directive to its own element:
```vue
<template>
<button v-restricted="restricted" type="button">
<slot />
</button>
</template>
<script lang="ts" setup>
import { vRestricted } from '@core/directives/restricted.directive.ts'
const { restricted } = defineProps<{
restricted?: boolean
}>()
</script>
```

View File

@@ -0,0 +1,64 @@
import { parseTooltipOptions } from '@core/directives/tooltip.directive.ts'
import i18n from '@core/i18n.ts'
import { TOOLTIP_FOCUS_EVENTS, TOOLTIP_HOVER_EVENTS, useTooltipStore } from '@core/stores/tooltip.store.ts'
import type { Directive } from 'vue'
const tooltipKeys = new WeakMap<HTMLElement, string>()
const blockClick = (event: Event) => {
event.preventDefault()
event.stopImmediatePropagation()
}
const restrict = (target: HTMLElement) => {
if (tooltipKeys.has(target)) {
return
}
target.setAttribute('aria-disabled', 'true')
target.addEventListener('click', blockClick, { capture: true })
const tooltipKey = useTooltipStore().register({
target,
options: parseTooltipOptions(i18n.global.t('permission-required')),
events: [TOOLTIP_HOVER_EVENTS, TOOLTIP_FOCUS_EVENTS],
isPrioritized: true,
})
tooltipKeys.set(target, tooltipKey)
}
const unrestrict = (target: HTMLElement) => {
const tooltipKey = tooltipKeys.get(target)
if (tooltipKey === undefined) {
return
}
target.removeAttribute('aria-disabled')
target.removeEventListener('click', blockClick, { capture: true })
useTooltipStore().unregister(tooltipKey)
tooltipKeys.delete(target)
}
const applyRestriction = (target: HTMLElement, isRestricted: boolean) => {
if (isRestricted) {
restrict(target)
return
}
unrestrict(target)
}
export const vRestricted: Directive<HTMLElement, boolean> = {
mounted(target, binding) {
applyRestriction(target, binding.value)
},
updated(target, binding) {
applyRestriction(target, binding.value)
},
beforeUnmount(target) {
unrestrict(target)
},
}

View File

@@ -0,0 +1,129 @@
import { vRestricted } from '@core/directives/restricted.directive.ts'
import { vTooltip } from '@core/directives/tooltip.directive.ts'
import { findTooltipContents } from '@core-test/find-tooltip-contents.ts'
import { hover } from '@core-test/hover.ts'
import { t } from '@core-test/i18n.ts'
import { mountWithSetup } from '@core-test/mount-with-setup.ts'
import { h, nextTick, ref, withDirectives } from 'vue'
function mountButton({ tooltip }: { tooltip?: string } = {}) {
const isRestricted = ref(true)
const onClick = vi.fn()
const wrapper = mountWithSetup(
() => () => {
const button = withDirectives(h('button', { onClick }), [[vRestricted, isRestricted.value]])
if (tooltip === undefined) {
return button
}
return withDirectives(button, [[vTooltip, tooltip]])
},
{ attachTo: document.body }
)
return { button: wrapper.element as HTMLElement, isRestricted, onClick }
}
function click(button: HTMLElement) {
const event = new MouseEvent('click', { bubbles: true, cancelable: true })
button.dispatchEvent(event)
return event
}
it('marks a restricted element as disabled for assistive technologies, without disabling it', () => {
const { button } = mountButton()
expect(button.getAttribute('aria-disabled')).toBe('true')
expect(button.hasAttribute('disabled')).toBe(false)
})
it('blocks the click listeners of a restricted element', () => {
const { button, onClick } = mountButton()
click(button)
expect(onClick).not.toHaveBeenCalled()
})
it('prevents the default action of a click on a restricted element', () => {
const { button } = mountButton()
const blockedClick = click(button)
expect(blockedClick.defaultPrevented).toBe(true)
})
it('restricts the element only while its value is true', async () => {
const { button, isRestricted, onClick } = mountButton()
isRestricted.value = false
await nextTick()
const allowedClick = click(button)
expect(button.hasAttribute('aria-disabled')).toBe(false)
expect(allowedClick.defaultPrevented).toBe(false)
expect(onClick).toHaveBeenCalledTimes(1)
isRestricted.value = true
await nextTick()
click(button)
expect(button.getAttribute('aria-disabled')).toBe('true')
expect(onClick).toHaveBeenCalledTimes(1)
})
it('shows the permission tooltip while the restricted element is hovered', () => {
const { button } = mountButton()
hover(button)
expect(findTooltipContents()).toEqual([t('permission-required')])
button.dispatchEvent(new MouseEvent('mouseleave'))
expect(findTooltipContents()).toEqual([])
})
it('shows the permission tooltip while the restricted element is focused', () => {
const { button } = mountButton()
button.focus()
expect(findTooltipContents()).toEqual([t('permission-required')])
button.blur()
expect(findTooltipContents()).toEqual([])
})
it('hides the permission tooltip when the mouse leaves a restricted element focused by a click', () => {
const { button } = mountButton()
hover(button)
button.dispatchEvent(new FocusEvent('focusin'))
button.dispatchEvent(new MouseEvent('mouseleave'))
expect(findTooltipContents()).toEqual([])
})
it('shows the permission tooltip in place of the one the element already has', () => {
const { button } = mountButton({ tooltip: 'Name' })
hover(button)
expect(findTooltipContents()).toEqual([t('permission-required')])
})
it('shows the tooltip the element already has once it is no longer restricted', async () => {
const { button, isRestricted } = mountButton({ tooltip: 'Name' })
hover(button)
isRestricted.value = false
await nextTick()
expect(findTooltipContents()).toEqual(['Name'])
})

View File

@@ -1,5 +1,5 @@
import type { TooltipEvents, TooltipOptions } from '@core/stores/tooltip.store.ts'
import { useTooltipStore } from '@core/stores/tooltip.store.ts'
import type { TooltipOptions } from '@core/stores/tooltip.store.ts'
import { TOOLTIP_FOCUS_EVENTS, TOOLTIP_HOVER_EVENTS, useTooltipStore } from '@core/stores/tooltip.store.ts'
import { isObject } from 'lodash-es'
import type { Options } from 'placement.js'
import type { Directive } from 'vue'
@@ -15,7 +15,7 @@ type TooltipDirectiveOptions =
vertical?: boolean
}
const parseOptions = (options: TooltipDirectiveOptions): TooltipOptions => {
export const parseTooltipOptions = (options: TooltipDirectiveOptions): TooltipOptions => {
const {
placement,
content,
@@ -31,22 +31,41 @@ const parseOptions = (options: TooltipDirectiveOptions): TooltipOptions => {
}
}
const tooltipKeys = new WeakMap<HTMLElement, string>()
const unregisterTooltip = (target: HTMLElement) => {
const tooltipKey = tooltipKeys.get(target)
if (tooltipKey === undefined) {
return
}
useTooltipStore().unregister(tooltipKey)
tooltipKeys.delete(target)
}
export const vTooltip: Directive<HTMLElement, TooltipDirectiveOptions> = {
mounted(target, binding) {
const store = useTooltipStore()
unregisterTooltip(target)
const events: TooltipEvents = binding.modifiers.focus
? { on: 'focusin', off: 'focusout' }
: { on: 'mouseenter', off: 'mouseleave' }
const tooltipKey = useTooltipStore().register({
target,
options: parseTooltipOptions(binding.value),
events: [binding.modifiers.focus ? TOOLTIP_FOCUS_EVENTS : TOOLTIP_HOVER_EVENTS],
})
store.register(target, parseOptions(binding.value), events)
tooltipKeys.set(target, tooltipKey)
},
updated(target, binding) {
const store = useTooltipStore()
store.updateOptions(target, parseOptions(binding.value))
const tooltipKey = tooltipKeys.get(target)
if (tooltipKey === undefined) {
return
}
useTooltipStore().updateOptions(tooltipKey, parseTooltipOptions(binding.value))
},
beforeUnmount(target) {
const store = useTooltipStore()
store.unregister(target)
unregisterTooltip(target)
},
}

View File

@@ -0,0 +1,77 @@
import { vTooltip } from '@core/directives/tooltip.directive.ts'
import { findTooltipContents } from '@core-test/find-tooltip-contents.ts'
import { hover } from '@core-test/hover.ts'
import { mountWithSetup } from '@core-test/mount-with-setup.ts'
import { defineComponent, h, nextTick, ref, type VNode, withDirectives } from 'vue'
function mountTarget(renderTarget: () => VNode | undefined) {
return mountWithSetup(() => renderTarget)
}
it('shows its content while the element is hovered', () => {
const target = mountTarget(() => withDirectives(h('div'), [[vTooltip, 'Name']])).element
hover(target)
expect(findTooltipContents()).toEqual(['Name'])
target.dispatchEvent(new MouseEvent('mouseleave'))
expect(findTooltipContents()).toEqual([])
})
it('shows its content while the element is focused, with the focus modifier', () => {
const target = mountWithSetup(
() => () => withDirectives(h('button'), [[vTooltip, 'Name', undefined, { focus: true }]]),
{ attachTo: document.body }
).element
hover(target)
expect(findTooltipContents()).toEqual([])
target.focus()
expect(findTooltipContents()).toEqual(['Name'])
})
it('follows its value', async () => {
const content = ref('Name')
const target = mountTarget(() => withDirectives(h('div'), [[vTooltip, content.value]])).element
hover(target)
content.value = 'New name'
await nextTick()
expect(findTooltipContents()).toEqual(['New name'])
})
it('removes its tooltip with the element', async () => {
const isRendered = ref(true)
const wrapper = mountTarget(() => {
if (!isRendered.value) {
return undefined
}
return withDirectives(h('div'), [[vTooltip, 'Name']])
})
hover(wrapper.element)
isRendered.value = false
await nextTick()
expect(findTooltipContents()).toEqual([])
})
it('keeps the tooltip of the parent when a component already sets one on its root element', () => {
const Child = defineComponent({
render: () => withDirectives(h('div'), [[vTooltip, 'Child']]),
})
const target = mountTarget(() => withDirectives(h(Child), [[vTooltip, 'Parent']])).element
hover(target)
expect(findTooltipContents()).toEqual(['Parent'])
})

View File

@@ -27,6 +27,7 @@ import {
faBook,
faCalendar,
faCamera,
faCertificate,
faCaretDown,
faCaretUp,
faCheck,
@@ -72,6 +73,7 @@ import {
faHeadset,
faInfo,
faInfoCircle,
faKey,
faKeyboard,
faLayerGroup,
faLink,
@@ -140,6 +142,7 @@ export const faIcons = defineIconPack({
building: { icon: faBuilding },
camera: { icon: faCamera },
calendar: { icon: faCalendar },
certificate: { icon: faCertificate },
'caret-down': { icon: faCaretDown },
'caret-up': { icon: faCaretUp },
check: { icon: faCheck },
@@ -190,6 +193,7 @@ export const faIcons = defineIconPack({
headset: { icon: faHeadset },
info: { icon: faInfo },
'info-circle': { icon: faInfoCircle },
key: { icon: faKey },
keyboard: { icon: faKeyboard },
'layer-group': { icon: faLayerGroup },
link: { icon: faLink },

View File

@@ -95,7 +95,7 @@ function handleBackdropClick() {
display: flex;
flex: 1;
min-height: 0;
overflow-x: clip;
overflow-x: hidden;
}
.header {

View File

@@ -13,10 +13,13 @@
"action:add": "Add",
"action:add-filter": "Add filter",
"action:add-group": "Add group",
"action:add-groups": "Add groups",
"action:add-host": "@:action:add @.lower:host",
"action:add-host-internal-network-in-xo-5": "Add a host internal network in XO-5",
"action:add-network-in-xo-5": "Add network in XO-5",
"action:add-roles": "Add roles",
"action:add-sort": "Add sort",
"action:add-users": "Add users",
"action:add-vifs-in-xo-5": "Add VIF in XO-5",
"action:apply": "Apply",
"action:attach": "Attach",
@@ -63,11 +66,14 @@
"action:delete-configuration": "Delete configuration",
"action:delete-filter": "Delete filter",
"action:delete-group": "Delete group",
"action:delete-n-groups": "Delete 1 group | Delete {n} groups",
"action:delete-n-jobs": "@:action:delete 1 job | @:action:delete {n} jobs",
"action:delete-n-networks": "Delete 1 network | Delete {n} networks",
"action:delete-n-roles": "Delete 1 role | Delete {n} roles",
"action:delete-n-snapshots": "Delete 1 snapshot | Delete {n} snapshots",
"action:delete-n-srs": "Delete 1 SR | Delete {n} SRs",
"action:delete-n-traffic-rules": "Delete 1 traffic rule | Delete {n} traffic rules",
"action:delete-n-users": "Delete 1 user | Delete {n} users",
"action:delete-n-vdis": "Delete 1 VDI | Delete {n} VDIs",
"action:delete-n-vifs": "Delete 1 VIF | Delete {n} VIFs",
"action:delete-n-vms": "Delete 1 VM | Delete {n} VMs",
@@ -217,11 +223,14 @@
"action:unload": "Unload",
"action:update": "Update",
"action:use-query-builder": "Use query builder",
"action:use-template": "Use this template",
"action:visit-pool-dashboard": "Visit pool dashboard",
"actions": "Actions",
"active-mapping": "Active mapping",
"adapter": "Adapter",
"add-or": "+OR",
"added": "Added",
"admin": "Admin",
"admin-login": "Admin login",
"admin-password": "Admin password",
"admin-password-confirm": "Confirm admin password",
@@ -447,6 +456,7 @@
"default-value": "Default ({value})",
"deletable-vms": "Good to go",
"deletion-blocked": "Deletion Blocked",
"deny": "Deny",
"deploy-xoa-available-on-desktop": "XOA deployment is available on your desktop interface",
"deploy-xoa-custom-ntp-servers": "Custom NTP servers (separated by spaces)",
"deploy-xoa-status:configuring": "Configuring XOA…",
@@ -506,6 +516,7 @@
"edit-vif:error-message": "An error occurred while editing the VIF. Please review your configuration settings and try again.",
"editing-vif": "Editing VIF",
"email": "Email",
"email-address": "Email address",
"email-already-added": "This email address has already been added",
"email-mandatory": "Email address is mandatory",
"empty": "Empty",
@@ -558,6 +569,7 @@
"first-of-month": "first of month",
"first-of-week": "first of week",
"first-of-year": "first of year",
"first-name": "First name",
"following-hosts-unreachable": "The following hosts are unreachable",
"for-backup": "For backup",
"for-replication": "For replication",
@@ -569,10 +581,12 @@
"form:error:field-minimum": "{field} must be {min} or more",
"form:error:field-required": "{field} is required",
"form:error:integer": "Must be an integer",
"form:error:invalid-query": "Invalid query",
"form:error:maximum": "Must be {max} or less",
"form:error:min-items": "Must contain at least {n} item | Must contain at least {n} items",
"form:error:minimum": "Must be {min} or more",
"form:error:must-match": "Must match “{text}”",
"form:error:password-mismatch": "Passwords do not match",
"form:error:required": "This field is required",
"form:n-errors-summary": "{n} field needs attention | {n} fields need attention",
"form:warning:out-of-range": "Should be between {min} and {max}",
@@ -595,6 +609,11 @@
"gpu": "GPU",
"gpus": "GPUs",
"graphics-display": "Graphics & Display",
"group": "Group",
"group-details": "Group details",
"group:delete-warning": "Deleting this group will permanently remove it and revoke all roles and permissions inherited by its members. This action cannot be undone. Proceed with caution. | Deleting these groups will permanently remove them and revoke all roles and permissions inherited by their members. This action cannot be undone. Proceed with caution.",
"group:what-is-a-group-description": "A group is a collection of users that share the same roles. Assign roles to a group to automatically grant those permissions to all its members. When a user is added to a group, they inherit all roles assigned to that group; inherited roles cannot be removed individually from a user, only by changing the group's roles or removing the user from the group.",
"group:what-is-a-group?": "What is a group?",
"groups": "Groups",
"guest-tools": "Guest tools",
"guest-tools-out-of-date": "Guest tools out of date",
@@ -685,6 +704,8 @@
"iso-dvd": "ISO/DVD",
"item": "Item",
"job": "Job",
"job-name": "Job name",
"job:add:in-progress": "Add in progress…",
"job:arg:allocated-space-required": "Allocated space is required",
"job:arg:backup-repository-required": "Backup repository is required",
"job:arg:bond-mode-required": "@:bond-mode-required",
@@ -747,11 +768,17 @@
"job:connect:in-progress": "Connect in progress…",
"job:create:in-progress": "Create in progress…",
"job:delete:in-progress": "Delete in progress…",
"job:detach:in-progress": "Detach in progress…",
"job:disable:in-progress": "Disable in progress…",
"job:disconnect:in-progress": "Disconnect in progress…",
"job:edit:in-progress": "Edit in progress…",
"job:enable:in-progress": "Enable in progress…",
"job:export:in-progress": "Export in progress…",
"job:group-delete:missing-group": "No groups to delete",
"job:group-delete:synchronized-group": "A synchronized group cannot be deleted",
"job:group-users:missing-group": "No group selected",
"job:group-users:missing-user": "No user selected",
"job:group-users:synchronized-group": "The users of a synchronized group cannot be changed",
"job:host-detach:bad-power-state": "@:host-not-running",
"job:host-detach:in-progress": "Host detach in progress…",
"job:host-detach:master-host": "Master host cannot be detached",
@@ -823,6 +850,13 @@
"job:plugin-test:not-loaded": "The plugin must be loaded to be tested",
"job:plugin-test:not-testable": "This plugin cannot be tested",
"job:pool-add-host:in-progress": "Adding host in progress…",
"job:role-delete:missing-role": "No roles to delete",
"job:role-delete:role-assigned": "A role assigned to users or groups cannot be deleted",
"job:role-groups:missing-group": "@:job:group-users:missing-group",
"job:role-groups:missing-role": "@:job:role-users:missing-role",
"job:role-users:inherited-role": "A role inherited from a group cannot be detached from a user",
"job:role-users:missing-role": "No role selected",
"job:role-users:missing-user": "No user selected",
"job:server-connect:missing-server": "No servers to connect",
"job:server-disconnect:missing-server": "No servers to disconnect",
"job:server-disconnect:server-disconnected": "One or several servers are already disconnected",
@@ -833,6 +867,8 @@
"job:traffic-rule-delete:missing-rule": "No traffic rule selected",
"job:traffic-rule-edit-order:no-free-priority": "No free priority left on this network to apply this order",
"job:traffic-rule-edit-order:not-enough-rules": "Requires at least {n} rules",
"job:user-delete:missing-user": "No users to delete",
"job:user-delete:self-deletion": "A user cannot delete itself",
"job:v2v-start:in-progress": "Migration launch in progress…",
"job:v2v-start:missing-vm": "No VMs to migrate",
"job:vbd-connect:missing-vbd": "No VBDs to connect",
@@ -937,6 +973,7 @@
"last-n-backup-runs": "Last backup run | Last {n} backup runs",
"last-n-days": "Last day | Last {n} days",
"last-n-runs": "Last run | Last {n} runs",
"last-name": "Last name",
"last-revert": "Last revert",
"last-run-number": "Last run #{n}",
"last-snapshot": "Last snapshot",
@@ -1074,6 +1111,7 @@
"n-gb": "{n} GB",
"n-gb-left": "{n} GB left",
"n-gb-required": "{n} GB required",
"n-groups": "1 group | {n} groups",
"n-hexadecimal-characters": "{n} hexadecimal characters.",
"n-hosts": "1 host | {n} hosts",
"n-hosts-awaiting-patch": "{n} host is awaiting this patch | {n} hosts are awaiting this patch",
@@ -1092,9 +1130,11 @@
"n-pools": "1 pool | {n} pools",
"n-private-networks": "1 private network | {n} private networks",
"n-ready": "1 ready | {n} ready",
"n-roles": "1 role | {n} roles",
"n-snapshots": "1 snapshot | {n} snapshots",
"n-srs": "1 SR | {n} SRs",
"n-traffic-rules": "1 traffic rule | {n} traffic rules",
"n-users": "1 user | {n} users",
"n-vbds": "1 VBD | {n} VBDs",
"n-vcpus": "1 vCPU | {n} vCPUs",
"n-vdis": "1 VDI | {n} VDIs",
@@ -1149,6 +1189,9 @@
"new-network:preferred-center-info": "The host to try first to elect as center of the network",
"new-network:select-interface": "Select an interface",
"new-traffic-rule:add": "Add new traffic rule",
"new-traffic-rule:error-message": "An error occurred while creating the traffic rule. Please review your configuration settings and try again.",
"new-user:error-already-exists": "A user with this username or email address already exists.",
"new-user:error-message": "An error occurred while creating the user. Please review your settings and try again.",
"new-vdi:accepted-formats": "Accepted formats: {formats}",
"new-vdi:add": "Add new VDI",
"new-vif": "New VIF",
@@ -1203,6 +1246,7 @@
"next-runs": "Next runs",
"nfs": "NFS",
"nic-type": "NIC type",
"no": "No",
"no-active-backup-jobs": "There are no active backup jobs on this site.",
"no-alarm-detected": "No alarms detected",
"no-alarm-triggered": "No alarm triggered",
@@ -1219,6 +1263,7 @@
"no-empty-network-to-fill": "No empty network to fill",
"no-empty-sr-to-fill": "No empty SR to fill",
"no-group-attached": "No group attached",
"no-group-detected": "No groups detected",
"no-host-attached": "No hosts attached",
"no-host-detected": "No hosts detected",
"no-job-vm": "This VM isn’t part of any running job.",
@@ -1227,10 +1272,13 @@
"no-pif-detected": "No PIFs detected",
"no-plugin-detected": "No plugins detected",
"no-pools-detected": "No pools detected",
"no-privilege-attached": "No privilege attached",
"no-remembered-connection": "No remembered connection",
"no-replicated-vm": "This VM isn’t being replicated. Configure a replication job to enable it.",
"no-result": "No results",
"no-role-applied": "No role applied",
"no-role-detected": "No roles detected",
"no-role-template-detected": "No role templates detected",
"no-run": "No run",
"no-running-vm-detected": "No running VMs detected",
"no-selected-vm-can-be-exported": "No selected VM can be exported",
@@ -1241,6 +1289,7 @@
"no-storage-repository-detected": "No storage repositories detected",
"no-task": "No tasks",
"no-task-detected": "No tasks detected",
"no-user-attached": "No users attached",
"no-user-detected": "No users detected",
"no-vdi-attached": "No VDIs attached",
"no-vdi-detected": "No VDIs detected",
@@ -1311,6 +1360,7 @@
"partial-deletion": "Partial deletion",
"partially-connected": "Partially connected",
"password": "Password",
"password-confirmation": "Password confirmation",
"password-invalid": "Password invalid",
"password-required": "Password is required.",
"patch-name": "Patch name",
@@ -1326,6 +1376,8 @@
"pbd-details": "Physical Block Device (PBD) details",
"pending": "Pending",
"per-vm-options": "Per-VM options",
"permission": "Permission",
"permission-required": "Permission required",
"physical-interface-status": "Physical interface status",
"physical-network": "Physical network",
"pif": "PIF",
@@ -1388,6 +1440,32 @@
"priority": "Priority",
"priority-within": "Priority within {name}",
"private-network": "Private network | Private networks",
"privilege": "Privilege",
"privilege-number": "Privilege #{n}",
"privilege:action": "Action",
"privilege:applied-to": "Applied to",
"privilege:create-new": "Create new privilege",
"privilege:currently-applied-to": "Currently applied to",
"privilege:details": "Privilege details",
"privilege:dynamic-selection-info": "The privilege will apply to every object matching this query.",
"privilege:edit": "Edit privilege",
"privilege:effect": "Effect",
"privilege:no-object": "No object",
"privilege:none-yet": "No privileges yet",
"privilege:one-privilege-per-action": "Each action will be a dedicated privilege",
"privilege:resource": "Resource",
"privilege:review-and-confirm": "Review & confirm",
"privilege:scope": "Scope",
"privilege:scope-preview": "Scope preview",
"privilege:scope-type": "Scope type",
"privilege:scope-type:all-objects": "All objects",
"privilege:scope-type:dynamic-selection": "Dynamic selection",
"privilege:scope-type:manual-selection": "Manual selection",
"privilege:select-scope": "Select scope",
"privilege:selector": "Selector",
"privilege:what-is-a-privilege-description": "A privilege is a granular permission that controls access to a specific action or resource in your environment, such as starting a VM, editing a network, or viewing storage. Each privilege belongs to exactly one role. Assign privileges to a role to define precisely what users with that role are allowed to do.",
"privilege:what-is-a-privilege?": "What is a privilege?",
"privileges": "Privileges",
"pro-support": "{name} pro support",
"professional-support": "Professional support",
"progress": "Progress",
@@ -1400,6 +1478,7 @@
"protection-status": "Protection status",
"protocol": "Protocol",
"protocol:port": "@:{'protocol'}:@:{'port'}",
"provider": "Provider",
"provider-solutions": "{provider} solutions",
"providers": "Providers",
"provisioning": "Provisioning",
@@ -1494,6 +1573,19 @@
"review": "Review",
"review-and-confirm": "Review & confirm",
"review-and-launch": "Review and launch",
"role": "Role",
"role-templates": "Role templates",
"role:creating": "Creating the new role…",
"role:delete-warning": "Deleting this role will permanently remove it along with all its privileges. This action cannot be undone. Proceed with caution. | Deleting these roles will permanently remove them along with all their privileges. This action cannot be undone. Proceed with caution.",
"role:details": "Role details",
"role:direct-users": "Direct",
"role:name-info": "For example: VM Operator, Network Admin, or Read-only Viewer",
"role:new": "New role",
"role:new-from-template": "New role from template",
"role:unable-to-create": "Unable to create the new role",
"role:users-from-group": "From {group} group",
"role:what-is-a-role-description": "A role is a set of privileges that can be assigned to users and groups. Assigning a role grants all of its privileges at once. A user holds the roles assigned to them directly, plus every role inherited from the groups they belong to.",
"role:what-is-a-role?": "What is a role?",
"roles": "Roles",
"roles-applied": "Roles applied",
"root-by-default": "\"root\" by default.",
@@ -1519,11 +1611,14 @@
"see-details": "See details",
"select-at-least-one-backup-repository": "Select at least one backup repository.",
"select-at-least-one-day": "Select at least one day of the month or of the week.",
"select-at-least-one-group.": "Select at least one group.",
"select-at-least-one-hour": "Select at least one hour.",
"select-at-least-one-object": "Selection of at least one object is mandatory.",
"select-at-least-one-option": "Select at least one option.",
"select-at-least-one-role.": "Select at least one role.",
"select-at-least-one-storage-repository": "Select at least one storage repository.",
"select-at-least-one-storage-target": "Select at least one storage target.",
"select-at-least-one-user.": "Select at least one user.",
"select-compression": "Select a compression",
"select-destination-host": "Select a destination host",
"select-format": "Select format",
@@ -1790,7 +1885,15 @@
"used-space-on-sr": "Used space on SR",
"user": "User",
"user-config": "User config",
"user-details": "User details",
"user-management": "User management",
"user:create-new": "Create new user",
"user:delete-warning": "Deleting this user will permanently remove their access and associated permissions. This action cannot be undone. Proceed with caution. | Deleting these users will permanently remove their access and associated permissions. This action cannot be undone. Proceed with caution.",
"user:direct-roles": "Direct roles",
"user:groups-assignment": "Groups assignment",
"user:roles-assignment": "Roles assignment",
"user:roles-from-group": "From {group} group",
"user:roles-from-groups-info": "Roles assigned through assigned groups are automatically applied to this user. You can add additional roles below if needed.",
"username": "Username",
"username-required": "Username is required.",
"users": "Users",
@@ -2001,6 +2104,7 @@
"xoa-ssh-account": "XOA SSH account",
"xoa-ssh-password-confirm-different": "SSH password confirmation is different",
"xva": "XVA",
"yes": "Yes",
"you-are-currently-on": "You are currently on: {0}",
"your-default-network-is": "Your default network is {name}",
"zstd": "ZSTD"

View File

@@ -13,10 +13,13 @@
"action:add": "Ajouter",
"action:add-filter": "Ajouter un filtre",
"action:add-group": "Ajouter un groupe",
"action:add-groups": "Ajouter des groupes",
"action:add-host": "@:action:add un @.lower:host",
"action:add-host-internal-network-in-xo-5": "Ajouter un réseau interne à l'hôte dans XO-5",
"action:add-network-in-xo-5": "Ajouter un réseau dans XO-5",
"action:add-roles": "Ajouter des rôles",
"action:add-sort": "Ajouter un tri",
"action:add-users": "Ajouter des utilisateurs",
"action:add-vifs-in-xo-5": "Ajouter un VIF dans XO-5",
"action:apply": "Appliquer",
"action:attach": "Attacher",
@@ -63,11 +66,14 @@
"action:delete-configuration": "Supprimer la configuration",
"action:delete-filter": "Supprimer le filtre",
"action:delete-group": "Supprimer le groupe",
"action:delete-n-groups": "Supprimer 1 groupe | Supprimer {n} groupes",
"action:delete-n-jobs": "@:action:delete 1 job | @:action:delete {n} jobs",
"action:delete-n-networks": "Supprimer 1 réseau | Supprimer {n} réseaux",
"action:delete-n-roles": "Supprimer 1 rôle | Supprimer {n} rôles",
"action:delete-n-snapshots": "Supprimer 1 instantané | Supprimer {n} instantanés",
"action:delete-n-srs": "Supprimer 1 SR | Supprimer {n} SRs",
"action:delete-n-traffic-rules": "Supprimer 1 règle de trafic | Supprimer {n} règles de trafic",
"action:delete-n-users": "Supprimer 1 utilisateur | Supprimer {n} utilisateurs",
"action:delete-n-vdis": "Supprimer 1 VDI | Supprimer {n} VDIs",
"action:delete-n-vifs": "Supprimer 1 VIF | Supprimer {n} VIFs",
"action:delete-n-vms": "Supprimer 1 VM | Supprimer {n} VMs",
@@ -217,11 +223,14 @@
"action:unload": "Décharger",
"action:update": "Mettre à jour",
"action:use-query-builder": "Constructeur de requête",
"action:use-template": "Utiliser ce modèle",
"action:visit-pool-dashboard": "Visiter le tableau de bord du pool",
"actions": "Actions",
"active-mapping": "Correspondance active",
"adapter": "Carte",
"add-or": "+OU",
"added": "Ajouté",
"admin": "Administrateur",
"admin-login": "Nom d'utilisateur administrateur",
"admin-password": "Mot de passe administrateur",
"admin-password-confirm": "Confirmer le mot de passe administrateur",
@@ -447,6 +456,7 @@
"default-value": "Par défaut ({value})",
"deletable-vms": "Prêtes",
"deletion-blocked": "Suppression Bloquée",
"deny": "Refuser",
"deploy-xoa-available-on-desktop": "Le déploiement de la XOA est disponible sur ordinateur",
"deploy-xoa-custom-ntp-servers": "Serveurs NTP (séparés par des espaces)",
"deploy-xoa-status:configuring": "Configuration de la XOA…",
@@ -506,6 +516,7 @@
"edit-vif:error-message": "Une erreur s'est produite lors de la modification du VIF. Veuillez vérifier vos paramètres et réessayer.",
"editing-vif": "Modification du VIF",
"email": "Email",
"email-address": "Adresse e-mail",
"email-already-added": "Cette adresse email a déjà été ajoutée",
"email-mandatory": "L'adresse email est obligatoire",
"empty": "Vide",
@@ -558,6 +569,7 @@
"first-of-month": "le premier du mois",
"first-of-week": "le premier de la semaine",
"first-of-year": "le premier de l’année",
"first-name": "Prénom",
"following-hosts-unreachable": "Les hôtes suivants sont inaccessibles",
"for-backup": "Pour la sauvegarde",
"for-replication": "Pour la réplication",
@@ -569,10 +581,12 @@
"form:error:field-minimum": "Le champ {field} doit être supérieur ou égal à {min}",
"form:error:field-required": "Le champ {field} est requis",
"form:error:integer": "Doit être un entier",
"form:error:invalid-query": "Requête invalide",
"form:error:maximum": "Doit être inférieur ou égal à {max}",
"form:error:min-items": "Doit contenir au moins {n} élément | Doit contenir au moins {n} éléments",
"form:error:minimum": "Doit être supérieur ou égal à {min}",
"form:error:must-match": "Doit correspondre à « {text} »",
"form:error:password-mismatch": "Les mots de passe ne correspondent pas",
"form:error:required": "Ce champ est requis",
"form:n-errors-summary": "{n} champ est à corriger | {n} champs sont à corriger",
"form:warning:out-of-range": "Devrait être compris entre {min} et {max}",
@@ -595,6 +609,11 @@
"gpu": "GPU",
"gpus": "GPUs",
"graphics-display": "Graphique & Affichage",
"group": "Groupe",
"group-details": "Détails du groupe",
"group:delete-warning": "Supprimer ce groupe le retirera définitivement et révoquera tous les rôles et permissions hérités par ses membres. Cette action est irréversible. Procédez avec prudence. | Supprimer ces groupes les retirera définitivement et révoquera tous les rôles et permissions hérités par leurs membres. Cette action est irréversible. Procédez avec prudence.",
"group:what-is-a-group-description": "Un groupe est un ensemble d'utilisateurs qui partagent les mêmes rôles. Attribuez des rôles à un groupe pour accorder automatiquement ces permissions à tous ses membres. Lorsqu'un utilisateur est ajouté à un groupe, il hérite de tous les rôles attribués à ce groupe ; les rôles hérités ne peuvent pas être retirés individuellement d'un utilisateur, mais uniquement en modifiant les rôles du groupe ou en retirant l'utilisateur du groupe.",
"group:what-is-a-group?": "Qu'est-ce qu'un groupe ?",
"groups": "Groupes",
"guest-tools": "Guest tools",
"guest-tools-out-of-date": "Guest tools obsolètes",
@@ -685,6 +704,8 @@
"iso-dvd": "ISO/DVD",
"item": "Élément",
"job": "Job",
"job-name": "Nom du job",
"job:add:in-progress": "Ajout en cours…",
"job:arg:allocated-space-required": "L'espace alloué est obligatoire",
"job:arg:backup-repository-required": "Le dépôt de sauvegarde est obligatoire",
"job:arg:bond-mode-required": "@:bond-mode-required",
@@ -747,11 +768,17 @@
"job:connect:in-progress": "Connexion en cours…",
"job:create:in-progress": "Création en cours…",
"job:delete:in-progress": "Suppression en cours…",
"job:detach:in-progress": "Détachement en cours…",
"job:disable:in-progress": "Désactivation en cours…",
"job:disconnect:in-progress": "Déconnexion en cours…",
"job:edit:in-progress": "Modification en cours…",
"job:enable:in-progress": "Activation en cours…",
"job:export:in-progress": "Export en cours…",
"job:group-delete:missing-group": "Aucun groupe à supprimer",
"job:group-delete:synchronized-group": "Un groupe synchronisé ne peut pas être supprimé",
"job:group-users:missing-group": "Aucun groupe sélectionné",
"job:group-users:missing-user": "Aucun utilisateur sélectionné",
"job:group-users:synchronized-group": "Les utilisateurs d'un groupe synchronisé ne peuvent pas être modifiés",
"job:host-detach:bad-power-state": "@:host-not-running",
"job:host-detach:in-progress": "Détachement de l'hôte en cours…",
"job:host-detach:master-host": "L'hôte primaire ne peut pas être détaché",
@@ -823,6 +850,13 @@
"job:plugin-test:not-loaded": "Le plugin doit être chargé pour être testé",
"job:plugin-test:not-testable": "Ce plugin ne peut pas être testé",
"job:pool-add-host:in-progress": "Ajout de l'hôte en cours…",
"job:role-delete:missing-role": "Aucun rôle à supprimer",
"job:role-delete:role-assigned": "Un rôle attribué à des utilisateurs ou à des groupes ne peut pas être supprimé",
"job:role-groups:missing-group": "@:job:group-users:missing-group",
"job:role-groups:missing-role": "@:job:role-users:missing-role",
"job:role-users:inherited-role": "Un rôle hérité d'un groupe ne peut pas être détaché d'un utilisateur",
"job:role-users:missing-role": "Aucun rôle sélectionné",
"job:role-users:missing-user": "Aucun utilisateur sélectionné",
"job:server-connect:missing-server": "Aucun serveur à connecter",
"job:server-disconnect:missing-server": "Aucun serveur à déconnecter",
"job:server-disconnect:server-disconnected": "Un ou plusieurs serveurs sont déjà déconnectés",
@@ -833,6 +867,8 @@
"job:traffic-rule-delete:missing-rule": "Aucune règle de trafic sélectionnée",
"job:traffic-rule-edit-order:no-free-priority": "Plus aucune priorité libre sur ce réseau pour appliquer cet ordre",
"job:traffic-rule-edit-order:not-enough-rules": "Nécessite au moins {n} règles",
"job:user-delete:missing-user": "Aucun utilisateur à supprimer",
"job:user-delete:self-deletion": "Un utilisateur ne peut pas se supprimer lui-même",
"job:v2v-start:in-progress": "Lancement de la migration en cours…",
"job:v2v-start:missing-vm": "Aucune VM à migrer",
"job:vbd-connect:missing-vbd": "Aucun VBD à connecter",
@@ -937,6 +973,7 @@
"last-n-backup-runs": "Dernier run de sauvegarde | {n} dernières sauvegardes",
"last-n-days": "Dernier jour | {n} derniers jours",
"last-n-runs": "Dernier run | {n} derniers runs",
"last-name": "Nom",
"last-revert": "Dernière restauration",
"last-run-number": "Dernier run #{n}",
"last-snapshot": "Dernier instantané",
@@ -1074,6 +1111,7 @@
"n-gb": "{n} Go",
"n-gb-left": "{n} Go libres",
"n-gb-required": "{n} Go requis",
"n-groups": "0 groupe | 1 groupe | {n} groupes",
"n-hexadecimal-characters": "{n} caractères hexadécimaux.",
"n-hosts": "0 hôte | 1 hôte | {n} hôtes",
"n-hosts-awaiting-patch": "{n} hôte attend ce patch | {n} hôtes attendent ce patch",
@@ -1092,9 +1130,11 @@
"n-pools": "1 pool | {n} pools",
"n-private-networks": "1 réseau privé | {n} réseaux privés",
"n-ready": "0 prête | 1 prête | {n} prêtes",
"n-roles": "0 rôle | 1 rôle | {n} rôles",
"n-snapshots": "0 instantané | 1 instantané | {n} instantanés",
"n-srs": "0 SR | 1 SR | {n} SRs",
"n-traffic-rules": "1 règle de trafic | {n} règles de trafic",
"n-users": "0 utilisateur | 1 utilisateur | {n} utilisateurs",
"n-vbds": "0 VBD | 1 VBD | {n} VBDs",
"n-vcpus": "0 vCPU | 1 vCPU | {n} vCPUs",
"n-vdis": "0 VDI | 1 VDI | {n} VDIs",
@@ -1149,6 +1189,9 @@
"new-network:preferred-center-info": "L’hôte à essayer en premier pour être élu centre du réseau",
"new-network:select-interface": "Sélectionner une interface",
"new-traffic-rule:add": "Ajouter une nouvelle règle de trafic",
"new-traffic-rule:error-message": "Une erreur s'est produite lors de la création de la règle de trafic. Veuillez vérifier vos paramètres de configuration et réessayer.",
"new-user:error-already-exists": "Un utilisateur avec ce nom d'utilisateur ou cette adresse e-mail existe déjà.",
"new-user:error-message": "Une erreur s'est produite lors de la création de l'utilisateur. Veuillez vérifier vos paramètres et réessayer.",
"new-vdi:accepted-formats": "Formats acceptés : {formats}",
"new-vdi:add": "Ajouter un nouveau VDI",
"new-vif": "Nouveau VIF",
@@ -1203,6 +1246,7 @@
"next-runs": "Prochaines exécutions",
"nfs": "NFS",
"nic-type": "Type de carte réseau (NIC)",
"no": "Non",
"no-active-backup-jobs": "Il n'y a aucune tâche de sauvegarde active sur ce site.",
"no-alarm-detected": "Aucune alarme détectée",
"no-alarm-triggered": "Aucune alarme déclenchée",
@@ -1219,6 +1263,7 @@
"no-empty-network-to-fill": "Aucun réseau vide à remplir",
"no-empty-sr-to-fill": "Aucun SR vide à remplir",
"no-group-attached": "Pas de groupe attaché",
"no-group-detected": "Aucun groupe détecté",
"no-host-attached": "Aucun hôte attaché",
"no-host-detected": "Aucun hôte détecté",
"no-job-vm": "Cette VM ne fait partie d'aucun job actif.",
@@ -1227,10 +1272,13 @@
"no-pif-detected": "Aucun PIF détecté",
"no-plugin-detected": "Aucun plugin détecté",
"no-pools-detected": "Aucun pool détecté",
"no-privilege-attached": "Aucun privilège attaché",
"no-remembered-connection": "Aucune connexion mémorisée",
"no-replicated-vm": "Cette VM n'est pas répliquée. Configurez une tâche de réplication pour l'activer.",
"no-result": "Aucun résultat",
"no-role-applied": "Pas de rôle appliqué",
"no-role-detected": "Aucun rôle détecté",
"no-role-template-detected": "Aucun modèle de rôle détecté",
"no-run": "Aucun run",
"no-running-vm-detected": "Aucune VM en cours d'exécution détectée",
"no-selected-vm-can-be-exported": "Aucune VM sélectionnée ne peut être exportée",
@@ -1241,6 +1289,7 @@
"no-storage-repository-detected": "Aucun dépôt de stockage détecté",
"no-task": "Aucune tâche",
"no-task-detected": "Aucune tâche détectée",
"no-user-attached": "Aucun utilisateur attaché",
"no-user-detected": "Aucun utilisateur détecté",
"no-vdi-attached": "Aucun VDI attaché",
"no-vdi-detected": "Aucun VDI détecté",
@@ -1311,6 +1360,7 @@
"partial-deletion": "Suppression partielle",
"partially-connected": "Partiellement connecté",
"password": "Mot de passe",
"password-confirmation": "Confirmation du mot de passe",
"password-invalid": "Mot de passe incorrect",
"password-required": "Le mot de passe est requis.",
"patch-name": "Nom du patch",
@@ -1326,6 +1376,8 @@
"pbd-details": "Détails du périphérique de bloc physique (PBD)",
"pending": "En cours",
"per-vm-options": "Options par VM",
"permission": "Permission",
"permission-required": "Permission requise",
"physical-interface-status": "Statut de l'interface physique",
"physical-network": "Réseau physique",
"pif": "PIF",
@@ -1388,6 +1440,32 @@
"priority": "Priorité",
"priority-within": "Priorité dans {name}",
"private-network": "Réseau privé | Réseaux privés",
"privilege": "Privilège",
"privilege-number": "Privilège #{n}",
"privilege:action": "Action",
"privilege:applied-to": "Appliqué à",
"privilege:create-new": "Créer un nouveau privilège",
"privilege:currently-applied-to": "Appliqué actuellement à",
"privilege:details": "Détails du privilège",
"privilege:dynamic-selection-info": "Le privilège s'appliquera à tous les objets correspondant à cette requête.",
"privilege:edit": "Modifier le privilège",
"privilege:effect": "Effet",
"privilege:no-object": "Aucun objet",
"privilege:none-yet": "Aucun privilège pour le moment",
"privilege:one-privilege-per-action": "Chaque action fera l'objet d'un privilège dédié",
"privilege:resource": "Ressource",
"privilege:review-and-confirm": "Vérifier et confirmer",
"privilege:scope": "Portée",
"privilege:scope-preview": "Aperçu de la portée",
"privilege:scope-type": "Type de portée",
"privilege:scope-type:all-objects": "Tous les objets",
"privilege:scope-type:dynamic-selection": "Sélection dynamique",
"privilege:scope-type:manual-selection": "Sélection manuelle",
"privilege:select-scope": "Sélectionner la portée",
"privilege:selector": "Sélecteur",
"privilege:what-is-a-privilege-description": "Un privilège est une permission fine qui contrôle l'accès à une action ou une ressource précise de votre environnement, comme démarrer une VM, modifier un réseau ou consulter le stockage. Chaque privilège appartient à un seul rôle. Attribuez des privilèges à un rôle pour définir précisément ce que les utilisateurs de ce rôle peuvent faire.",
"privilege:what-is-a-privilege?": "Qu'est-ce qu'un privilège ?",
"privileges": "Privilèges",
"pro-support": "Support pro {name}",
"professional-support": "Support professionnel",
"progress": "Progression",
@@ -1400,6 +1478,7 @@
"protection-status": "Statut de la protection",
"protocol": "Protocole",
"protocol:port": "@:{'protocol'}:@:{'port'}",
"provider": "Fournisseur",
"provider-solutions": "Solutions {provider}",
"providers": "Fournisseurs",
"provisioning": "Provisionnement",
@@ -1494,6 +1573,19 @@
"review": "Revue",
"review-and-confirm": "Vérifier et confirmer",
"review-and-launch": "Revue et lancement",
"role": "Rôle",
"role-templates": "Modèles de rôle",
"role:creating": "Création du nouveau rôle en cours…",
"role:delete-warning": "Supprimer ce rôle le retirera définitivement, ainsi que tous ses privilèges. Cette action est irréversible. Procédez avec prudence. | Supprimer ces rôles les retirera définitivement, ainsi que tous leurs privilèges. Cette action est irréversible. Procédez avec prudence.",
"role:details": "Détails du rôle",
"role:direct-users": "Direct",
"role:name-info": "Par exemple : Opérateur VM, Administrateur réseau ou Lecteur seul",
"role:new": "Nouveau rôle",
"role:new-from-template": "Nouveau rôle à partir d'un modèle",
"role:unable-to-create": "Impossible de créer le nouveau rôle",
"role:users-from-group": "Du groupe {group}",
"role:what-is-a-role-description": "Un rôle est un ensemble de privilèges attribuable à des utilisateurs et à des groupes. Attribuer un rôle accorde tous ses privilèges d'un coup. Un utilisateur détient les rôles qui lui sont attribués directement, ainsi que tous ceux hérités des groupes auxquels il appartient.",
"role:what-is-a-role?": "Qu'est-ce qu'un rôle ?",
"roles": "Rôles",
"roles-applied": "Rôles appliqués",
"root-by-default": "\"root\" par défaut.",
@@ -1519,11 +1611,14 @@
"see-details": "Voir les détails",
"select-at-least-one-backup-repository": "Sélectionnez au moins un backup repository.",
"select-at-least-one-day": "Sélectionnez au moins un jour du mois ou de la semaine.",
"select-at-least-one-group.": "Sélectionnez au moins un groupe.",
"select-at-least-one-hour": "Sélectionnez au moins une heure.",
"select-at-least-one-object": "La sélection d’au moins un objet est obligatoire.",
"select-at-least-one-option": "Sélectionnez au moins une option.",
"select-at-least-one-role.": "Sélectionnez au moins un rôle.",
"select-at-least-one-storage-repository": "Sélectionnez au moins un storage repository.",
"select-at-least-one-storage-target": "Sélectionnez au moins une cible de stockage.",
"select-at-least-one-user.": "Sélectionnez au moins un utilisateur.",
"select-compression": "Sélectionnez une compression",
"select-destination-host": "Sélectionnez un hôte de destination",
"select-format": "Sélectionner le format",
@@ -1790,7 +1885,15 @@
"used-space-on-sr": "Espace utilisé sur le SR",
"user": "Utilisateur",
"user-config": "Configuration utilisateur",
"user-details": "Détails de l'utilisateur",
"user-management": "Gestion des utilisateurs",
"user:create-new": "Créer un nouvel utilisateur",
"user:delete-warning": "Supprimer cet utilisateur retirera définitivement son accès et les permissions associées. Cette action est irréversible. Procédez avec prudence. | Supprimer ces utilisateurs retirera définitivement leurs accès et les permissions associées. Cette action est irréversible. Procédez avec prudence.",
"user:direct-roles": "Rôles directs",
"user:groups-assignment": "Affectation des groupes",
"user:roles-assignment": "Affectation des rôles",
"user:roles-from-group": "Du groupe {group}",
"user:roles-from-groups-info": "Les rôles des groupes affectés sont automatiquement appliqués à cet utilisateur. Vous pouvez ajouter des rôles supplémentaires ci-dessous si besoin.",
"username": "Nom d'utilisateur",
"username-required": "Le nom d'utilisateur est requis.",
"users": "Utilisateurs",
@@ -2001,6 +2104,7 @@
"xoa-ssh-account": "Compte SSH de la XOA",
"xoa-ssh-password-confirm-different": "La confirmation du mot de passe SSH est différente",
"xva": "XVA",
"yes": "Oui",
"you-are-currently-on": "Vous êtes actuellement sur : {0}",
"your-default-network-is": "Votre réseau par défaut est {name}",
"zstd": "ZSTD"

View File

@@ -14,61 +14,101 @@ export type TooltipOptions = {
export type TooltipEvents = { on: WindowEventName; off: WindowEventName }
export type TooltipRegistration = {
target: HTMLElement
options: TooltipOptions
events: TooltipEvents[]
isPrioritized?: boolean
}
type Tooltip = {
key: string
target: HTMLElement
options: TooltipOptions
isPrioritized: boolean
}
export const TOOLTIP_HOVER_EVENTS: TooltipEvents = { on: 'mouseenter', off: 'mouseleave' }
export const TOOLTIP_FOCUS_EVENTS: TooltipEvents = { on: 'focusin', off: 'focusout' }
const isPointerFocus = (eventName: WindowEventName, target: HTMLElement) =>
eventName === TOOLTIP_FOCUS_EVENTS.on && !target.matches(':focus-visible')
export const useTooltipStore = defineStore('tooltip', () => {
const targetsScopes = new WeakMap<HTMLElement, EffectScope>()
const targets = ref(new Set<HTMLElement>())
const targetsOptions = ref(new Map<HTMLElement, TooltipOptions>())
const targetsIds = ref(new Map<HTMLElement, string>())
const scopes = new Map<string, EffectScope>()
const registeredTooltips = ref(new Map<string, Tooltip>())
const activeKeys = ref(new Set<string>())
const register = (target: HTMLElement, options: TooltipOptions, events: TooltipEvents) => {
const register = ({ target, options, events, isPrioritized = false }: TooltipRegistration) => {
const key = uniqueId('tooltip-')
const scope = effectScope()
const activeOnEvents = new Set<WindowEventName>()
targetsScopes.set(target, scope)
targetsOptions.value.set(target, options)
targetsIds.value.set(target, uniqueId('tooltip-'))
scopes.set(key, scope)
registeredTooltips.value.set(key, { key, target, options, isPrioritized })
scope.run(() => {
useEventListener(target, events.on, () => {
targets.value.add(target)
events.forEach(({ on, off }) => {
useEventListener(target, on, () => {
if (isPointerFocus(on, target)) {
return
}
scope.run(() => {
useEventListener(
target,
events.off,
() => {
targets.value.delete(target)
},
{ once: true }
)
activeOnEvents.add(on)
activeKeys.value.add(key)
})
useEventListener(target, off, () => {
activeOnEvents.delete(on)
if (activeOnEvents.size === 0) {
activeKeys.value.delete(key)
}
})
})
})
return key
}
const updateOptions = (target: HTMLElement, options: TooltipOptions) => {
targetsOptions.value.set(target, options)
const updateOptions = (key: string, options: TooltipOptions) => {
const tooltip = registeredTooltips.value.get(key)
if (tooltip === undefined) {
return
}
tooltip.options = options
}
const unregister = (target: HTMLElement) => {
targets.value.delete(target)
targetsOptions.value.delete(target)
targetsScopes.get(target)?.stop()
targetsScopes.delete(target)
targetsIds.value.delete(target)
const unregister = (key: string) => {
activeKeys.value.delete(key)
registeredTooltips.value.delete(key)
scopes.get(key)?.stop()
scopes.delete(key)
}
const activeTooltips = computed(() =>
Array.from(activeKeys.value)
.map(key => registeredTooltips.value.get(key))
.filter(tooltip => tooltip !== undefined)
)
const isOverridden = (tooltip: Tooltip) => {
if (tooltip.isPrioritized) {
return false
}
return activeTooltips.value.some(
activeTooltip => activeTooltip.isPrioritized && activeTooltip.target === tooltip.target
)
}
return {
register,
unregister,
updateOptions,
tooltips: computed(() => {
return Array.from(targets.value.values()).map(target => {
return {
target,
options: targetsOptions.value.get(target)!,
key: targetsIds.value.get(target)!,
}
})
}),
tooltips: computed(() => activeTooltips.value.filter(tooltip => !isOverridden(tooltip))),
}
})

View File

@@ -0,0 +1,150 @@
import { parseTooltipOptions } from '@core/directives/tooltip.directive.ts'
import {
TOOLTIP_FOCUS_EVENTS,
TOOLTIP_HOVER_EVENTS,
type TooltipRegistration,
useTooltipStore,
} from '@core/stores/tooltip.store.ts'
import { findTooltipContents } from '@core-test/find-tooltip-contents.ts'
import { hover } from '@core-test/hover.ts'
import { mountComposable } from '@core-test/mount-composable.ts'
function mountTooltipStore() {
return mountComposable(() => ({ tooltipStore: useTooltipStore() })).wrapper.vm.tooltipStore
}
function createRegistration(content: string, overrides: Partial<TooltipRegistration> = {}): TooltipRegistration {
return {
target: document.createElement('button'),
options: parseTooltipOptions(content),
events: [TOOLTIP_HOVER_EVENTS],
...overrides,
}
}
function createFocusableRegistration(content: string): TooltipRegistration {
const registration = createRegistration(content, { events: [TOOLTIP_HOVER_EVENTS, TOOLTIP_FOCUS_EVENTS] })
document.body.append(registration.target)
onTestFinished(() => registration.target.remove())
return registration
}
describe('tooltips', () => {
it('lists a tooltip from its "on" event to its "off" event', () => {
const registration = createRegistration('Name')
mountTooltipStore().register(registration)
expect(findTooltipContents()).toEqual([])
hover(registration.target)
expect(findTooltipContents()).toEqual(['Name'])
registration.target.dispatchEvent(new MouseEvent('mouseleave'))
expect(findTooltipContents()).toEqual([])
})
it('lists a tooltip on each of its events', () => {
const registration = createFocusableRegistration('Name')
mountTooltipStore().register(registration)
registration.target.focus()
expect(findTooltipContents()).toEqual(['Name'])
registration.target.blur()
expect(findTooltipContents()).toEqual([])
})
it('lists a tooltip until all its events are off', () => {
const registration = createFocusableRegistration('Name')
mountTooltipStore().register(registration)
registration.target.focus()
hover(registration.target)
registration.target.blur()
expect(findTooltipContents()).toEqual(['Name'])
registration.target.dispatchEvent(new MouseEvent('mouseleave'))
expect(findTooltipContents()).toEqual([])
})
it('does not list a tooltip on a focus the browser does not show', () => {
const registration = createFocusableRegistration('Name')
mountTooltipStore().register(registration)
hover(registration.target)
registration.target.dispatchEvent(new FocusEvent('focusin'))
registration.target.dispatchEvent(new MouseEvent('mouseleave'))
expect(findTooltipContents()).toEqual([])
})
it('hides the other tooltips of a target while its prioritized tooltip is listed', () => {
const tooltipStore = mountTooltipStore()
const registration = createRegistration('Name')
tooltipStore.register(registration)
tooltipStore.register(createRegistration('Reason', { target: registration.target, isPrioritized: true }))
hover(registration.target)
expect(findTooltipContents()).toEqual(['Reason'])
})
it('keeps the tooltips of the other targets while a prioritized tooltip is listed', () => {
const tooltipStore = mountTooltipStore()
const registration = createRegistration('Name')
const prioritizedRegistration = createRegistration('Reason', { isPrioritized: true })
tooltipStore.register(registration)
tooltipStore.register(prioritizedRegistration)
hover(registration.target)
hover(prioritizedRegistration.target)
expect(findTooltipContents()).toEqual(['Name', 'Reason'])
})
})
describe('updateOptions', () => {
it('changes the options of a listed tooltip', () => {
const tooltipStore = mountTooltipStore()
const registration = createRegistration('Name')
const tooltipKey = tooltipStore.register(registration)
hover(registration.target)
tooltipStore.updateOptions(tooltipKey, parseTooltipOptions('New name'))
expect(findTooltipContents()).toEqual(['New name'])
})
})
describe('unregister', () => {
it('removes a listed tooltip', () => {
const tooltipStore = mountTooltipStore()
const registration = createRegistration('Name')
const tooltipKey = tooltipStore.register(registration)
hover(registration.target)
tooltipStore.unregister(tooltipKey)
expect(findTooltipContents()).toEqual([])
})
it('stops listing the tooltip on its events', () => {
const tooltipStore = mountTooltipStore()
const registration = createRegistration('Name')
const tooltipKey = tooltipStore.register(registration)
tooltipStore.unregister(tooltipKey)
hover(registration.target)
expect(findTooltipContents()).toEqual([])
})
})

View File

@@ -12,9 +12,14 @@ export type CheckboxCellBindings = {
onToggle: () => void
}
function renderHeadCheckbox(model: Ref<boolean | undefined>) {
export type CheckboxHeadCellOptions = {
disabled?: boolean
}
function renderHeadCheckbox(model: Ref<boolean | undefined>, options?: CheckboxHeadCellOptions) {
return h(UiCheckbox, {
accent: 'brand',
disabled: options?.disabled,
modelValue: model.value,
'onUpdate:modelValue': (value: boolean | undefined | string[]) => {
model.value = value === true
@@ -32,8 +37,12 @@ function renderBodyCheckbox({ selected, disabled, onToggle }: CheckboxCellBindin
}
export const useCheckboxColumn = defineColumn(() => ({
renderHead: (model: Ref<boolean | undefined>) =>
h(VtsHeaderCell, { style: { width: COLUMN_WIDTH } }, () => renderHeadCheckbox(model)),
renderBody: (bindings: CheckboxCellBindings) =>
h(UiTableCell, { style: { width: COLUMN_WIDTH } }, () => renderBodyCheckbox(bindings)),
renderHead: (model?: Ref<boolean | undefined>, options?: CheckboxHeadCellOptions) =>
h(VtsHeaderCell, { style: { width: COLUMN_WIDTH } }, () =>
model === undefined ? undefined : renderHeadCheckbox(model, options)
),
renderBody: (bindings?: CheckboxCellBindings) =>
h(UiTableCell, { style: { width: COLUMN_WIDTH } }, () =>
bindings === undefined ? undefined : renderBodyCheckbox(bindings)
),
}))

View File

@@ -1,11 +0,0 @@
import VtsUserNameCell from '@core/components/table/cells/VtsUserNameCell.vue'
import { defineColumn } from '@core/packages/table/define-column.ts'
import { renderHeadCell } from '@core/tables/helpers/render-head-cell.ts'
import type { FlexibleColumnConfig } from '@core/tables/types.ts'
import { h } from 'vue'
export const useUserNameColumn = defineColumn((config?: FlexibleColumnConfig) => ({
renderHead: () => renderHeadCell(config?.headerLabel),
renderBody: (content: string, props?: { href?: string }) =>
h(VtsUserNameCell, { content, href: props?.href, flexible: config?.flexible }),
}))

View File

@@ -0,0 +1,12 @@
import VtsUsernameCell from '@core/components/table/cells/VtsUsernameCell.vue'
import type { LinkOptions } from '@core/composables/link-component.composable.ts'
import { defineColumn } from '@core/packages/table/define-column.ts'
import { renderHeadCell } from '@core/tables/helpers/render-head-cell.ts'
import type { FlexibleColumnConfig } from '@core/tables/types.ts'
import { h } from 'vue'
export const useUsernameColumn = defineColumn((config?: FlexibleColumnConfig) => ({
renderHead: () => renderHeadCell(config?.headerLabel),
renderBody: (content: string, link?: Pick<LinkOptions, 'to' | 'href'>) =>
h(VtsUsernameCell, { content, ...link, flexible: config?.flexible }),
}))

View File

@@ -0,0 +1,20 @@
import { defineColumns } from '@core/packages/table/define-columns.ts'
import { useActionColumn } from '@core/tables/column-definitions/action-column.ts'
import { useCheckboxColumn } from '@core/tables/column-definitions/checkbox-column.ts'
import { useLinkOrTextColumn } from '@core/tables/column-definitions/link-or-text-column.ts'
import { useNumberColumn } from '@core/tables/column-definitions/number-column.ts'
import { useTextColumn } from '@core/tables/column-definitions/text-column.ts'
import { useI18n } from 'vue-i18n'
export const useGroupColumns = defineColumns(() => {
const { t } = useI18n()
return {
checkbox: useCheckboxColumn(),
name: useLinkOrTextColumn({ headerLabel: () => t('name') }),
provider: useTextColumn({ headerLabel: () => t('provider') }),
users: useNumberColumn({ headerLabel: () => t('users') }),
roles: useNumberColumn({ headerLabel: () => t('roles') }),
actions: useActionColumn({}),
}
})

View File

@@ -0,0 +1,24 @@
import { defineColumns } from '@core/packages/table/define-columns.ts'
import { useButtonIconColumn } from '@core/tables/column-definitions/button-icon-column.ts'
import { useLinkColumn } from '@core/tables/column-definitions/link-column.ts'
import { useNumberColumn } from '@core/tables/column-definitions/number-column.ts'
import { useSelectItemColumn } from '@core/tables/column-definitions/select-item-column.ts'
import { useTagColumn } from '@core/tables/column-definitions/tag-column.ts'
import { useTextColumn } from '@core/tables/column-definitions/text-column.ts'
import { useI18n } from 'vue-i18n'
export const usePrivilegeColumns = defineColumns(() => {
const { t } = useI18n()
return {
index: useLinkColumn(),
resource: useTextColumn({ headerLabel: () => t('privilege:resource') }),
scope: useTextColumn({ headerLabel: () => t('privilege:scope') }),
appliedTo: useNumberColumn({ headerLabel: () => t('privilege:applied-to') }),
action: useTextColumn({ headerLabel: () => t('privilege:action') }),
effect: useTagColumn({ headerLabel: () => t('privilege:effect') }),
edit: useButtonIconColumn({ buttonIcon: 'fa:pencil' }),
remove: useButtonIconColumn({ buttonIcon: 'fa:trash', buttonAccent: 'danger' }),
selectItem: useSelectItemColumn(),
}
})

View File

@@ -0,0 +1,13 @@
import { defineColumns } from '@core/packages/table/define-columns.ts'
import { useCheckboxColumn } from '@core/tables/column-definitions/checkbox-column.ts'
import { useLinkColumn } from '@core/tables/column-definitions/link-column.ts'
import { useI18n } from 'vue-i18n'
export const usePrivilegeScopeObjectColumns = defineColumns(() => {
const { t } = useI18n()
return {
checkbox: useCheckboxColumn(),
object: useLinkColumn({ headerLabel: () => t('name') }),
}
})

View File

@@ -0,0 +1,22 @@
import { defineColumns } from '@core/packages/table/define-columns.ts'
import { useActionColumn } from '@core/tables/column-definitions/action-column.ts'
import { useCheckboxColumn } from '@core/tables/column-definitions/checkbox-column.ts'
import { useLinkOrTextColumn } from '@core/tables/column-definitions/link-or-text-column.ts'
import { useNumberColumn } from '@core/tables/column-definitions/number-column.ts'
import { useTextColumn } from '@core/tables/column-definitions/text-column.ts'
import { useI18n } from 'vue-i18n'
export const useRoleColumns = defineColumns(() => {
const { t } = useI18n()
return {
checkbox: useCheckboxColumn(),
name: useLinkOrTextColumn({ headerLabel: () => t('name') }),
group: useLinkOrTextColumn({ headerLabel: () => t('group') }),
description: useTextColumn({ headerLabel: () => t('description') }),
users: useNumberColumn({ headerLabel: () => t('users') }),
groups: useNumberColumn({ headerLabel: () => t('groups') }),
privileges: useNumberColumn({ headerLabel: () => t('privileges') }),
actions: useActionColumn({}),
}
})

View File

@@ -0,0 +1,18 @@
import { defineColumns } from '@core/packages/table/define-columns.ts'
import { useButtonColumn } from '@core/tables/column-definitions/button-column.ts'
import { useNumberColumn } from '@core/tables/column-definitions/number-column.ts'
import { useSelectItemColumn } from '@core/tables/column-definitions/select-item-column.ts'
import { useTextColumn } from '@core/tables/column-definitions/text-column.ts'
import { useI18n } from 'vue-i18n'
export const useRoleTemplateColumns = defineColumns(() => {
const { t } = useI18n()
return {
name: useTextColumn({ headerLabel: () => t('name') }),
description: useTextColumn({ headerLabel: () => t('description') }),
privileges: useNumberColumn({ headerLabel: () => t('privileges') }),
select: useButtonColumn({ buttonVariant: 'secondary', buttonSize: 'small' }),
selectItem: useSelectItemColumn(),
}
})

View File

@@ -1,16 +1,21 @@
import { defineColumns } from '@core/packages/table/define-columns.ts'
import { useSelectItemColumn } from '@core/tables/column-definitions/select-item-column.ts'
import { useActionColumn } from '@core/tables/column-definitions/action-column.ts'
import { useCheckboxColumn } from '@core/tables/column-definitions/checkbox-column.ts'
import { useTextColumn } from '@core/tables/column-definitions/text-column.ts'
import { useTruncatedTextColumn } from '@core/tables/column-definitions/truncated-text-column.ts'
import { useUserNameColumn } from '@core/tables/column-definitions/user-name-column.ts'
import { useUsernameColumn } from '@core/tables/column-definitions/username-column.ts'
import { useI18n } from 'vue-i18n'
export const useUserColumns = defineColumns(() => {
const { t } = useI18n()
return {
username: useUserNameColumn({ headerLabel: () => t('username'), flexible: true }),
checkbox: useCheckboxColumn(),
username: useUsernameColumn({ headerLabel: () => t('username'), flexible: true }),
firstName: useTextColumn({ headerLabel: () => t('first-name') }),
lastName: useTextColumn({ headerLabel: () => t('last-name') }),
email: useTruncatedTextColumn({ headerLabel: () => t('email') }),
providers: useTruncatedTextColumn({ headerLabel: () => t('providers') }),
selectItem: useSelectItemColumn(),
actions: useActionColumn({}),
}
})

View File

@@ -1,10 +0,0 @@
import type { VueWrapper } from '@vue/test-utils'
// Whether the first input of a wrapper attached to the document takes the focus, which an `inert` ancestor prevents
export function canFocusInput(wrapper: Pick<VueWrapper, 'get'>) {
const input = wrapper.get('input').element
input.focus()
return document.activeElement === input
}

View File

@@ -0,0 +1,5 @@
import { useTooltipStore } from '@core/stores/tooltip.store.ts'
export function findTooltipContents() {
return useTooltipStore().tooltips.map(tooltip => tooltip.options.content)
}

View File

@@ -0,0 +1,3 @@
export function hover(target: Element) {
target.dispatchEvent(new MouseEvent('mouseenter'))
}

View File

@@ -35,6 +35,7 @@
"@vueuse/integrations": "^14.0.0",
"@vueuse/math": "^14.0.0",
"@vueuse/shared": "^14.0.0",
"@xen-orchestra/acl": "^1.8.0",
"@xen-orchestra/backups": "^1.0.1",
"@xen-orchestra/cron": "^1.0.7",
"@xen-orchestra/web-core": "^0.67.0",

View File

@@ -0,0 +1,9 @@
declare module '@xen-orchestra/web-core/packages/hide-permanently/types.ts' {
interface PermanentlyHideableItems {
'what-is-a-group': true
'what-is-a-privilege': true
'what-is-a-role': true
}
}
export {}

View File

@@ -65,9 +65,9 @@ const sections = computed<AdminMenuSection[]>(() => [
{
title: t('user-management'),
items: [
{ label: t('users'), href: undefined, to: { name: '/admin/user-management' } },
{ label: t('groups'), href: buildXo5Route('/settings/groups'), to: undefined },
{ label: t('roles'), href: buildXo5Route('/settings/acls'), to: undefined },
{ label: t('users'), href: undefined, to: { name: '/admin/user-management/users' } },
{ label: t('groups'), href: undefined, to: { name: '/admin/user-management/groups' } },
{ label: t('roles'), href: undefined, to: { name: '/admin/user-management/roles' } },
{
label: t('ldap-auth-providers'),
href: undefined,

View File

@@ -8,6 +8,16 @@
{{ t('users') }}
</UiTabItem>
</RouterLink>
<RouterLink v-slot="{ isExactActive, href }" :to="{ name: '/admin/user-management/groups' }" custom>
<UiTabItem :active="isExactActive" :href tag="a">
{{ t('groups') }}
</UiTabItem>
</RouterLink>
<RouterLink v-slot="{ isExactActive, href }" :to="{ name: '/admin/user-management/roles' }" custom>
<UiTabItem :active="isExactActive" :href tag="a">
{{ t('roles') }}
</UiTabItem>
</RouterLink>
</TabList>
</template>

View File

@@ -0,0 +1,18 @@
<template>
<UiAlert v-if="isInfoVisible" accent="info" close @close="hideInfo">
<span class="typo-body-bold">{{ t('group:what-is-a-group?') }}</span>
<template #description>
<span class="typo-body-regular">{{ t('group:what-is-a-group-description') }}</span>
</template>
</UiAlert>
</template>
<script lang="ts" setup>
import UiAlert from '@core/components/ui/alert/UiAlert.vue'
import { useHidePermanently } from '@core/packages/hide-permanently/use-hide-permanently.ts'
import { useI18n } from 'vue-i18n'
const { t } = useI18n()
const [isInfoVisible, hideInfo] = useHidePermanently('what-is-a-group')
</script>

View File

@@ -0,0 +1,56 @@
<template>
<DetailPageLayout>
<template #alert>
<GroupInfoAlert />
</template>
<template #menu="{ size }">
<UiMenuItem
:size
:to="{ name: '/admin/group/[id]/general', params: { id: group.id } }"
:selected="route.name === '/admin/group/[id]/general'"
>
{{ t('general') }}
</UiMenuItem>
<UiMenuItem
:size
:to="{ name: '/admin/group/[id]/roles', params: { id: group.id } }"
:selected="route.name === '/admin/group/[id]/roles'"
>
{{ t('roles') }}
</UiMenuItem>
<UiMenuItem
:size
:to="{ name: '/admin/group/[id]/users', params: { id: group.id } }"
:selected="route.name === '/admin/group/[id]/users'"
>
{{ t('users') }}
</UiMenuItem>
</template>
<slot />
<template v-if="slots.panel" #panel>
<slot name="panel" />
</template>
</DetailPageLayout>
</template>
<script lang="ts" setup>
import GroupInfoAlert from '@/modules/group/components/GroupInfoAlert.vue'
import type { FrontXoGroup } from '@/modules/group/remote-resources/use-xo-group-collection.ts'
import DetailPageLayout from '@/shared/components/DetailPageLayout.vue'
import UiMenuItem from '@core/components/ui/menu-item/UiMenuItem.vue'
import { useI18n } from 'vue-i18n'
import { useRoute } from 'vue-router'
defineProps<{
group: FrontXoGroup
}>()
const slots = defineSlots<{
default(): any
panel?(): any
}>()
const { t } = useI18n()
const route = useRoute()
</script>

View File

@@ -0,0 +1,27 @@
<template>
<UiCard>
<UiTitle>
{{ t('group-details') }}
</UiTitle>
<VtsTabularKeyValueList>
<VtsTabularKeyValueRow :label="t('name')" :value="group.name" />
<VtsTabularKeyValueRow :label="t('uuid')" :value="group.id" />
<VtsTabularKeyValueRow :label="t('provider')" :value="group.provider" />
</VtsTabularKeyValueList>
</UiCard>
</template>
<script lang="ts" setup>
import type { FrontXoGroup } from '@/modules/group/remote-resources/use-xo-group-collection.ts'
import VtsTabularKeyValueList from '@core/components/tabular-key-value-list/VtsTabularKeyValueList.vue'
import VtsTabularKeyValueRow from '@core/components/tabular-key-value-row/VtsTabularKeyValueRow.vue'
import UiCard from '@core/components/ui/card/UiCard.vue'
import UiTitle from '@core/components/ui/title/UiTitle.vue'
import { useI18n } from 'vue-i18n'
defineProps<{
group: FrontXoGroup
}>()
const { t } = useI18n()
</script>

View File

@@ -0,0 +1,58 @@
<template>
<div class="group-header">
<UiBreadcrumb :size>
<span class="name">
<VtsIcon name="object:organization" size="current" />
{{ t('user-management') }}
</span>
<UiLink :size :to="{ name: '/admin/user-management/groups' }">
{{ t('groups') }}
</UiLink>
<span class="name">
<VtsIcon name="table:group" size="current" />
{{ group.name }}
</span>
</UiBreadcrumb>
</div>
<UiHeadBar icon="table:group">
{{ group.name }}
</UiHeadBar>
</template>
<script lang="ts" setup>
import type { FrontXoGroup } from '@/modules/group/remote-resources/use-xo-group-collection.ts'
import VtsIcon from '@core/components/icon/VtsIcon.vue'
import UiBreadcrumb from '@core/components/ui/breadcrumb/UiBreadcrumb.vue'
import UiHeadBar from '@core/components/ui/head-bar/UiHeadBar.vue'
import UiLink from '@core/components/ui/link/UiLink.vue'
import { useUiStore } from '@core/stores/ui.store.ts'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
defineProps<{
group: FrontXoGroup
}>()
const { t } = useI18n()
const uiStore = useUiStore()
const size = computed(() => (uiStore.isSmall ? 'small' : 'medium'))
</script>
<style lang="postcss" scoped>
.group-header {
min-height: 5.6rem;
padding: 1.2rem 1.6rem;
display: flex;
align-items: center;
border-block-end: 0.1rem solid var(--color-neutral-border);
background-color: var(--color-neutral-background-primary);
.name {
display: flex;
align-items: center;
gap: 0.8rem;
}
}
</style>

View File

@@ -0,0 +1,136 @@
<template>
<AssignmentsTableLayout
:title="t('roles')"
:can-add="canAddRoles"
:is-adding="isAddingRoles"
:can-detach="canDetachSelectedRoles"
:is-detaching="isDetachingSelectedRoles"
:detach-error-message="detachSelectedRolesErrorMessage"
@add="addRolesUnselected()"
@detach="detachSelectedRoles({ detached: true, onSuccess: selectionBindings.onClearSelection })"
>
<template #filter>
<VtsQueryBuilder v-bind="searchBindings" :schema />
</template>
<VtsTable :state :pagination-bindings :selection-bindings sticky="right">
<thead>
<tr>
<HeadCells />
</tr>
</thead>
<tbody>
<VtsRow v-for="role of paginatedRoles" :key="role.id" :selected="selectedRoleId === role.id">
<BodyCells :item="role" />
</VtsRow>
</tbody>
</VtsTable>
</AssignmentsTableLayout>
</template>
<script lang="ts" setup>
import { useGroupRolesAdd } from '@/modules/group/composables/use-group-roles-add.composable.ts'
import type { FrontXoGroup } from '@/modules/group/remote-resources/use-xo-group-collection.ts'
import {
type FilterableRole,
useRoleQueryBuilder,
} from '@/modules/role/composables/use-role-query-builder.composable.ts'
import { useXoRoleGroupsRemoveJob } from '@/modules/role/jobs/xo-role-groups-remove.job.ts'
import type { FrontXoRole } from '@/modules/role/remote-resources/use-xo-role-collection.ts'
import AssignmentsTableLayout from '@/shared/components/AssignmentsTableLayout.vue'
import VtsQueryBuilder from '@core/components/query-builder/VtsQueryBuilder.vue'
import VtsRow from '@core/components/table/VtsRow.vue'
import VtsTable from '@core/components/table/VtsTable.vue'
import { usePagination } from '@core/composables/pagination.composable.ts'
import { useRouteQuery } from '@core/composables/route-query.composable.ts'
import { useTableSelection } from '@core/composables/table-selection.composable.ts'
import { useTableState } from '@core/composables/table-state.composable.ts'
import { useRoleColumns } from '@core/tables/column-sets/role-columns.ts'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
const { group, roles, busy, error } = defineProps<{
group: FrontXoGroup
roles: FrontXoRole[]
busy?: boolean
error?: boolean
}>()
const { t } = useI18n()
const selectedRoleId = useRouteQuery('id')
const { addRoles, canAddRoles, isAddingRoles } = useGroupRolesAdd(() => group)
const { items: filteredRoles, searchBindings, schema } = useRoleQueryBuilder('group-roles', () => roles)
const { pageRecords: paginatedRoles, paginationBindings } = usePagination('group-roles', filteredRoles)
const state = useTableState({
busy: () => busy,
error: () => error,
empty: () =>
roles.length === 0 ? t('no-role-applied') : filteredRoles.value.length === 0 ? { type: 'no-result' } : false,
})
const { selectedIds, pageSelectionModel, isSelected, toggleSelection, selectionBindings } = useTableSelection({
items: () => roles,
filteredItems: filteredRoles,
pageItems: paginatedRoles,
getItemId: role => role.id,
})
async function addRolesUnselected() {
const addedRoles = await addRoles()
addedRoles.forEach(role => toggleSelection(role.id, false))
}
const selectedRoles = computed(() => roles.filter(role => selectedIds.value.includes(role.id)))
const {
run: detachSelectedRoles,
canRun: canDetachSelectedRoles,
isRunning: isDetachingSelectedRoles,
errorMessage: detachSelectedRolesErrorMessage,
} = useXoRoleGroupsRemoveJob(selectedRoles, () => [group])
const { HeadCells, BodyCells } = useRoleColumns({
exclude: ['group', 'users', 'groups'],
head: () => ({
checkbox: r => r(pageSelectionModel),
}),
body: (role: FilterableRole) => {
const {
run: detachRole,
canRun: canDetachRole,
isRunning: isDetachingRole,
errorMessage: detachRoleErrorMessage,
} = useXoRoleGroupsRemoveJob(
() => [role],
() => [group]
)
return {
checkbox: r => r({ selected: isSelected(role.id), onToggle: () => toggleSelection(role.id) }),
name: r =>
r({ label: role.name, icon: 'fa:key', to: { name: '/admin/role/[id]/general', params: { id: role.id } } }),
description: r => r(role.description),
privileges: r => r(role.privilegesCount),
actions: r =>
r({
onClick: () => (selectedRoleId.value = role.id),
actions: [
{
label: t('action:detach'),
icon: 'action:detach',
onClick: () => detachRole({ detached: true, onSuccess: () => toggleSelection(role.id, false) }),
disabled: !canDetachRole.value,
busy: isDetachingRole.value,
hint: detachRoleErrorMessage.value,
},
],
}),
}
},
})
</script>

View File

@@ -0,0 +1,137 @@
<template>
<AssignmentsTableLayout
:title="t('users')"
:can-add="canAddUsers"
:is-adding="isAddingUsers"
:can-detach="canDetachSelectedUsers"
:is-detaching="isDetachingSelectedUsers"
:detach-error-message="detachSelectedUsersErrorMessage"
@add="addUsersUnselected()"
@detach="detachSelectedUsers({ detached: true, onSuccess: selectionBindings.onClearSelection })"
>
<template #filter>
<VtsQueryBuilder v-bind="searchBindings" :schema />
</template>
<VtsTable :state :pagination-bindings :selection-bindings sticky="right">
<thead>
<tr>
<HeadCells />
</tr>
</thead>
<tbody>
<VtsRow v-for="user of paginatedUsers" :key="user.id" :selected="selectedUserId === user.id">
<BodyCells :item="user" />
</VtsRow>
</tbody>
</VtsTable>
</AssignmentsTableLayout>
</template>
<script lang="ts" setup>
import { useGroupUsersAdd } from '@/modules/group/composables/use-group-users-add.composable.ts'
import { useXoGroupUsersRemoveJob } from '@/modules/group/jobs/xo-group-users-remove.job.ts'
import type { FrontXoGroup } from '@/modules/group/remote-resources/use-xo-group-collection.ts'
import {
type FilterableUser,
useUserQueryBuilder,
} from '@/modules/user/composables/use-user-query-builder.composable.ts'
import type { FrontXoUser } from '@/modules/user/remote-resources/use-xo-user-collection.ts'
import { getUserDisplayName } from '@/modules/user/utils/xo-user.util.ts'
import AssignmentsTableLayout from '@/shared/components/AssignmentsTableLayout.vue'
import VtsQueryBuilder from '@core/components/query-builder/VtsQueryBuilder.vue'
import VtsRow from '@core/components/table/VtsRow.vue'
import VtsTable from '@core/components/table/VtsTable.vue'
import { usePagination } from '@core/composables/pagination.composable.ts'
import { useRouteQuery } from '@core/composables/route-query.composable.ts'
import { useTableSelection } from '@core/composables/table-selection.composable.ts'
import { useTableState } from '@core/composables/table-state.composable.ts'
import { useUserColumns } from '@core/tables/column-sets/user-columns.ts'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
const { group, users, busy, error } = defineProps<{
group: FrontXoGroup
users: FrontXoUser[]
busy?: boolean
error?: boolean
}>()
const { t } = useI18n()
const selectedUserId = useRouteQuery('id')
const { addUsers, canAddUsers, isAddingUsers } = useGroupUsersAdd(() => group)
const { items: filteredUsers, searchBindings, schema } = useUserQueryBuilder('group-users', () => users)
const { pageRecords: paginatedUsers, paginationBindings } = usePagination('group-users', filteredUsers)
const state = useTableState({
busy: () => busy,
error: () => error,
empty: () =>
users.length === 0 ? t('no-user-attached') : filteredUsers.value.length === 0 ? { type: 'no-result' } : false,
})
const { selectedIds, pageSelectionModel, isSelected, toggleSelection, selectionBindings } = useTableSelection({
items: () => users,
filteredItems: filteredUsers,
pageItems: paginatedUsers,
getItemId: user => user.id,
})
async function addUsersUnselected() {
const addedUsers = await addUsers()
addedUsers.forEach(user => toggleSelection(user.id, false))
}
const selectedUsers = computed(() => users.filter(user => selectedIds.value.includes(user.id)))
const {
run: detachSelectedUsers,
canRun: canDetachSelectedUsers,
isRunning: isDetachingSelectedUsers,
errorMessage: detachSelectedUsersErrorMessage,
} = useXoGroupUsersRemoveJob(() => [group], selectedUsers)
const { HeadCells, BodyCells } = useUserColumns({
exclude: ['providers'],
head: () => ({
checkbox: r => r(pageSelectionModel),
}),
body: (user: FilterableUser) => {
const {
run: detachUser,
canRun: canDetachUser,
isRunning: isDetachingUser,
errorMessage: detachUserErrorMessage,
} = useXoGroupUsersRemoveJob(
() => [group],
() => [user]
)
return {
checkbox: r => r({ selected: isSelected(user.id), onToggle: () => toggleSelection(user.id) }),
username: r => r(getUserDisplayName(user), { to: { name: '/admin/user/[id]/general', params: { id: user.id } } }),
firstName: r => r(user.firstname),
lastName: r => r(user.lastname),
email: r => r(user.email),
actions: r =>
r({
onClick: () => (selectedUserId.value = user.id),
actions: [
{
label: t('action:detach'),
icon: 'action:detach',
onClick: () => detachUser({ detached: true, onSuccess: () => toggleSelection(user.id, false) }),
disabled: !canDetachUser.value,
busy: isDetachingUser.value,
hint: detachUserErrorMessage.value,
},
],
}),
}
},
})
</script>

View File

@@ -0,0 +1,96 @@
<template>
<div class="groups-selection-table">
<VtsQueryBuilder v-bind="searchBindings" :schema />
<VtsTable :state :pagination-bindings :selection-bindings>
<thead>
<tr>
<HeadCells />
</tr>
</thead>
<tbody>
<VtsRow v-for="group of paginatedGroups" :key="group.id">
<BodyCells :item="group" />
</VtsRow>
</tbody>
</VtsTable>
</div>
</template>
<script lang="ts" setup>
import {
type FilterableGroup,
useGroupQueryBuilder,
} from '@/modules/group/composables/use-group-query-builder.composable.ts'
import type { FrontXoGroup } from '@/modules/group/remote-resources/use-xo-group-collection.ts'
import VtsQueryBuilder from '@core/components/query-builder/VtsQueryBuilder.vue'
import VtsRow from '@core/components/table/VtsRow.vue'
import VtsTable from '@core/components/table/VtsTable.vue'
import { usePagination } from '@core/composables/pagination.composable.ts'
import { useTableSelection } from '@core/composables/table-selection.composable.ts'
import { useTableState } from '@core/composables/table-state.composable.ts'
import { useGroupColumns } from '@core/tables/column-sets/group-columns.ts'
import { watch } from 'vue'
import { useI18n } from 'vue-i18n'
const { groups, busy, error } = defineProps<{
groups: FrontXoGroup[]
busy?: boolean
error?: boolean
}>()
const selectedGroupIds = defineModel<FrontXoGroup['id'][]>('selectedGroupIds', { required: true })
const { t } = useI18n()
const {
items: filteredGroups,
searchBindings,
schema,
} = useGroupQueryBuilder('groups-selection', () => groups, {
ignoreRoute: true,
})
const { pageRecords: paginatedGroups, paginationBindings } = usePagination('groups-selection', filteredGroups, {
ignoreRoute: true,
})
const state = useTableState({
busy: () => busy,
error: () => error,
empty: () =>
groups.length === 0 ? t('no-group-detected') : filteredGroups.value.length === 0 ? { type: 'no-result' } : false,
})
const { selectedIds, pageSelectionModel, isSelected, toggleSelection, selectionBindings } = useTableSelection({
items: () => groups,
filteredItems: filteredGroups,
pageItems: paginatedGroups,
getItemId: group => group.id,
})
watch(selectedIds, ids => {
selectedGroupIds.value = groups.filter(group => ids.includes(group.id)).map(group => group.id)
})
const { HeadCells, BodyCells } = useGroupColumns({
exclude: ['actions'],
head: () => ({
checkbox: r => r(pageSelectionModel),
}),
body: (group: FilterableGroup) => ({
checkbox: r => r({ selected: isSelected(group.id), onToggle: () => toggleSelection(group.id) }),
name: r => r({ label: group.name, icon: 'table:group' }),
provider: r => r(group.provider ?? ''),
users: r => r(group.usersCount),
roles: r => r(group.rolesCount),
}),
})
</script>
<style lang="postcss" scoped>
.groups-selection-table {
display: flex;
flex-direction: column;
gap: 0.8rem;
}
</style>

View File

@@ -0,0 +1,73 @@
<template>
<UiDrawer @confirm="confirm()" @dismiss="emit('cancel')">
<template #title>
{{ title }}
</template>
<template #content>
<div class="content">
<GroupsSelectionTable v-model:selected-group-ids="selectedGroupIds" :groups />
<UiInfo v-if="isSelectionErrorVisible" accent="danger">
{{ t('select-at-least-one-group.') }}
</UiInfo>
</div>
</template>
<template #buttons>
<VtsOverlayCancelButton @click="emit('cancel')" />
<VtsOverlayConfirmButton>
{{ t('action:add') }}
</VtsOverlayConfirmButton>
</template>
</UiDrawer>
</template>
<script lang="ts" setup>
import GroupsSelectionTable from '@/modules/group/components/drawer/GroupsSelectionTable.vue'
import type { FrontXoGroup } from '@/modules/group/remote-resources/use-xo-group-collection.ts'
import VtsOverlayCancelButton from '@core/components/overlay/VtsOverlayCancelButton.vue'
import VtsOverlayConfirmButton from '@core/components/overlay/VtsOverlayConfirmButton.vue'
import UiDrawer from '@core/components/ui/drawer/UiDrawer.vue'
import UiInfo from '@core/components/ui/info/UiInfo.vue'
import { computed, ref } from 'vue'
import { useI18n } from 'vue-i18n'
const { groups } = defineProps<{
groups: FrontXoGroup[]
title: string
}>()
const emit = defineEmits<{
confirm: [groups: FrontXoGroup[]]
cancel: []
}>()
const { t } = useI18n()
const selectedGroupIds = ref<FrontXoGroup['id'][]>([])
const hasTriedToConfirm = ref(false)
const isSelectionErrorVisible = computed(() => hasTriedToConfirm.value && selectedGroupIds.value.length === 0)
function confirm() {
hasTriedToConfirm.value = true
if (selectedGroupIds.value.length === 0) {
return
}
emit(
'confirm',
groups.filter(group => selectedGroupIds.value.includes(group.id))
)
}
</script>
<style lang="postcss" scoped>
.content {
display: flex;
flex-direction: column;
gap: 0.8rem;
}
</style>

View File

@@ -0,0 +1,148 @@
<template>
<div class="groups-table">
<UiTitle>
{{ t('groups') }}
</UiTitle>
<VtsQueryBuilder v-bind="searchBindings" :schema />
<div class="container">
<VtsTableBulkActions :actions="bulkActions" />
<VtsTable :state :pagination-bindings :selection-bindings sticky="right">
<thead>
<tr>
<HeadCells />
</tr>
</thead>
<tbody>
<VtsRow v-for="group of paginatedGroups" :key="group.id" :selected="selectedGroupId === group.id">
<BodyCells :item="group" />
</VtsRow>
</tbody>
</VtsTable>
</div>
</div>
</template>
<script setup lang="ts">
import { useGroupDelete } from '@/modules/group/composables/use-group-delete.composable.ts'
import {
type FilterableGroup,
useGroupQueryBuilder,
} from '@/modules/group/composables/use-group-query-builder.composable.ts'
import type { FrontXoGroup } from '@/modules/group/remote-resources/use-xo-group-collection.ts'
import type { ActionItem } from '@core/components/menu/VtsActionsMenu.vue'
import VtsQueryBuilder from '@core/components/query-builder/VtsQueryBuilder.vue'
import VtsRow from '@core/components/table/VtsRow.vue'
import VtsTable from '@core/components/table/VtsTable.vue'
import VtsTableBulkActions from '@core/components/table/VtsTableBulkActions.vue'
import UiTitle from '@core/components/ui/title/UiTitle.vue'
import { usePagination } from '@core/composables/pagination.composable.ts'
import { useRouteQuery } from '@core/composables/route-query.composable.ts'
import { useTableSelection } from '@core/composables/table-selection.composable.ts'
import { useTableState } from '@core/composables/table-state.composable.ts'
import { useGroupColumns } from '@core/tables/column-sets/group-columns.ts'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
const {
groups: rawGroups,
busy,
error,
} = defineProps<{
groups: FrontXoGroup[]
busy?: boolean
error?: boolean
}>()
const { t } = useI18n()
const selectedGroupId = useRouteQuery('id')
const { items: filteredGroups, searchBindings, schema } = useGroupQueryBuilder('groups', () => rawGroups)
const state = useTableState({
busy: () => busy,
error: () => error,
empty: () =>
rawGroups.length === 0 ? t('no-group-detected') : filteredGroups.value.length === 0 ? { type: 'no-result' } : false,
})
const { pageRecords: paginatedGroups, paginationBindings } = usePagination('groups', filteredGroups)
const { selectedIds, pageSelectionModel, isSelected, toggleSelection, selectionBindings } = useTableSelection({
items: () => rawGroups,
filteredItems: filteredGroups,
pageItems: paginatedGroups,
getItemId: group => group.id,
})
const selectedGroups = computed(() => rawGroups.filter(group => selectedIds.value.includes(group.id)))
const {
deleteGroups: deleteSelectedGroups,
canDeleteGroups: canDeleteSelectedGroups,
isDeletingGroups: isDeletingSelectedGroups,
deleteGroupsErrorMessage: deleteSelectedGroupsErrorMessage,
} = useGroupDelete(selectedGroups)
const bulkActions = computed<ActionItem[]>(() => [
{
label: t('action:delete'),
icon: 'action:delete',
accent: 'danger',
onClick: () => deleteSelectedGroups(),
disabled: !canDeleteSelectedGroups.value,
busy: isDeletingSelectedGroups.value,
hint: deleteSelectedGroupsErrorMessage.value,
},
])
const { HeadCells, BodyCells } = useGroupColumns({
head: () => ({
checkbox: r => r(pageSelectionModel),
}),
body: (group: FilterableGroup) => {
const { deleteGroups, canDeleteGroups, isDeletingGroups, deleteGroupsErrorMessage } = useGroupDelete(() => [group])
return {
checkbox: r => r({ selected: isSelected(group.id), onToggle: () => toggleSelection(group.id) }),
name: r =>
r({
label: group.name,
icon: 'table:group',
to: { name: '/admin/group/[id]/general', params: { id: group.id } },
}),
provider: r => r(group.provider ?? ''),
users: r => r(group.usersCount),
roles: r => r(group.rolesCount),
actions: r =>
r({
onClick: () => (selectedGroupId.value = group.id),
actions: [
{
label: t('action:delete'),
icon: 'action:delete',
accent: 'danger',
onClick: () => deleteGroups(),
disabled: !canDeleteGroups.value,
busy: isDeletingGroups.value,
hint: deleteGroupsErrorMessage.value,
},
],
}),
}
},
})
</script>
<style scoped lang="postcss">
.groups-table,
.container {
display: flex;
flex-direction: column;
gap: 2.4rem;
}
.container {
gap: 0.8rem;
}
</style>

View File

@@ -0,0 +1,45 @@
<template>
<VtsSidePanel :has-selection="group !== undefined" @close="emit('close')">
<template v-if="group" #actions>
<slot name="actions">
<VtsDeleteButton
:disabled="!canDeleteGroups"
:busy="isDeletingGroups"
:tooltip="deleteGroupsErrorMessage ?? false"
@click="deleteGroups()"
/>
</slot>
</template>
<template v-if="group" #default>
<GroupInfosCard :group />
<GroupUsersCard :group />
<GroupRolesCard :group />
</template>
</VtsSidePanel>
</template>
<script setup lang="ts">
import GroupInfosCard from '@/modules/group/components/list/panel/cards/GroupInfosCard.vue'
import GroupRolesCard from '@/modules/group/components/list/panel/cards/GroupRolesCard.vue'
import GroupUsersCard from '@/modules/group/components/list/panel/cards/GroupUsersCard.vue'
import { useGroupDelete } from '@/modules/group/composables/use-group-delete.composable.ts'
import type { FrontXoGroup } from '@/modules/group/remote-resources/use-xo-group-collection.ts'
import VtsDeleteButton from '@core/components/delete-button/VtsDeleteButton.vue'
import VtsSidePanel from '@core/components/panel/VtsSidePanel.vue'
const { group } = defineProps<{
group?: FrontXoGroup
}>()
const emit = defineEmits<{
close: []
}>()
defineSlots<{
actions?(): any
}>()
const { deleteGroups, canDeleteGroups, isDeletingGroups, deleteGroupsErrorMessage } = useGroupDelete(() =>
group !== undefined ? [group] : []
)
</script>

View File

@@ -0,0 +1,45 @@
<template>
<UiPanelCard class="group-infos-card">
<UiPanelCardTitle
:id="group.id"
size="medium"
:label="group.name"
icon="table:group"
:to="{ name: '/admin/group/[id]/general', params: { id: group.id } }"
/>
<div class="content">
<VtsCardRowKeyValue truncate align-top>
<template #key>{{ t('provider') }}</template>
<template #value>{{ group.provider }}</template>
<template v-if="group.provider" #addons>
<VtsCopyButton :value="group.provider" />
</template>
</VtsCardRowKeyValue>
</div>
</UiPanelCard>
</template>
<script lang="ts" setup>
import type { FrontXoGroup } from '@/modules/group/remote-resources/use-xo-group-collection.ts'
import VtsCardRowKeyValue from '@core/components/card/VtsCardRowKeyValue.vue'
import VtsCopyButton from '@core/components/copy-button/VtsCopyButton.vue'
import UiPanelCard from '@core/components/ui/panel-card/UiPanelCard.vue'
import UiPanelCardTitle from '@core/components/ui/panel-card-title/UiPanelCardTitle.vue'
import { useI18n } from 'vue-i18n'
defineProps<{
group: FrontXoGroup
}>()
const { t } = useI18n()
</script>
<style scoped lang="postcss">
.group-infos-card {
.content {
display: flex;
flex-direction: column;
gap: 0.4rem;
}
}
</style>

View File

@@ -0,0 +1,58 @@
<template>
<UiPanelCard>
<UiPanelCardTitle
size="medium"
:label="t('roles-applied')"
:counter="areRolesReady ? groupRoles.length : undefined"
/>
<VtsStateHero v-if="hasRoleFetchError" type="error" format="card" horizontal size="extra-small">
{{ t('error-no-data') }}
</VtsStateHero>
<VtsStateHero v-else-if="!areRolesReady" type="busy" format="card" horizontal size="extra-small" />
<UiLinkList
v-else-if="groupRoles.length > 0"
variant="vertical"
:visible-items="5"
:total-items="groupRoles.length"
>
<UiLink
v-for="role of groupRoles"
:key="role.id"
icon="fa:key"
size="small"
:to="{ name: '/admin/user-management/roles', query: { id: role.id } }"
>
{{ role.name }}
</UiLink>
</UiLinkList>
<VtsStateHero v-else type="no-data" format="card" horizontal size="extra-small">
{{ t('no-role-applied') }}
</VtsStateHero>
</UiPanelCard>
</template>
<script lang="ts" setup>
import type { FrontXoGroup } from '@/modules/group/remote-resources/use-xo-group-collection.ts'
import { useXoRoleCollection } from '@/modules/role/remote-resources/use-xo-role-collection.ts'
import VtsStateHero from '@core/components/state-hero/VtsStateHero.vue'
import UiLink from '@core/components/ui/link/UiLink.vue'
import UiLinkList from '@core/components/ui/link-list/UiLinkList.vue'
import UiPanelCard from '@core/components/ui/panel-card/UiPanelCard.vue'
import UiPanelCardTitle from '@core/components/ui/panel-card-title/UiPanelCardTitle.vue'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
const { group } = defineProps<{
group: FrontXoGroup
}>()
const { t } = useI18n()
const { roles, areRolesReady, hasRoleFetchError } = useXoRoleCollection()
const groupRoles = computed(() => roles.value.filter(role => role.groupIds.includes(group.id)))
</script>

View File

@@ -0,0 +1,44 @@
<template>
<UiPanelCard class="group-users-card">
<UiPanelCardTitle size="medium" :label="t('users')" :counter="groupUsers.length" />
<UiLinkList v-if="groupUsers.length > 0" variant="vertical">
<UiLink
v-for="user in groupUsers"
:key="user.id"
icon="fa:circle-user"
size="small"
:to="{ name: '/admin/user-management/users', query: { id: user.id } }"
>
{{ getUserDisplayName(user) }}
</UiLink>
</UiLinkList>
<VtsStateHero v-else type="no-data" format="card" horizontal size="extra-small">
{{ t('no-user-attached') }}
</VtsStateHero>
</UiPanelCard>
</template>
<script lang="ts" setup>
import type { FrontXoGroup } from '@/modules/group/remote-resources/use-xo-group-collection.ts'
import { useXoUserCollection } from '@/modules/user/remote-resources/use-xo-user-collection.ts'
import { getUserDisplayName } from '@/modules/user/utils/xo-user.util.ts'
import VtsStateHero from '@core/components/state-hero/VtsStateHero.vue'
import UiLink from '@core/components/ui/link/UiLink.vue'
import UiLinkList from '@core/components/ui/link-list/UiLinkList.vue'
import UiPanelCard from '@core/components/ui/panel-card/UiPanelCard.vue'
import UiPanelCardTitle from '@core/components/ui/panel-card-title/UiPanelCardTitle.vue'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
const { group } = defineProps<{
group: FrontXoGroup
}>()
const { t } = useI18n()
const { getUsersByIds } = useXoUserCollection()
const groupUsers = computed(() => getUsersByIds(group.users))
</script>

View File

@@ -0,0 +1,59 @@
import { useXoGroupDeleteJob } from '@/modules/group/jobs/xo-group-delete.job.ts'
import type { FrontXoGroup } from '@/modules/group/remote-resources/use-xo-group-collection.ts'
import { useDeleteModal } from '@core/composables/modals/use-delete-modal.ts'
import { useRouteQuery } from '@core/composables/route-query.composable.ts'
import { toComputed } from '@core/utils/to-computed.util.ts'
import type { MaybeRefOrGetter } from 'vue'
import { useI18n } from 'vue-i18n'
export function useGroupDelete(rawGroups: MaybeRefOrGetter<FrontXoGroup[]>) {
const groups = toComputed(rawGroups)
const { t } = useI18n()
const selectedGroupId = useRouteQuery('id')
const {
run,
canRun: canDeleteGroups,
isRunning: isDeletingGroups,
errorMessage: deleteGroupsErrorMessage,
} = useXoGroupDeleteJob(groups)
const { open } = useDeleteModal()
function confirmDelete() {
const groupIds = groups.value.map(group => group.id)
run({
detached: true,
onSuccess: results => {
const isSelectedGroupDeleted = results.some(
(result, index) => result.status === 'fulfilled' && groupIds[index] === selectedGroupId.value
)
if (isSelectedGroupDeleted) {
selectedGroupId.value = ''
}
},
})
}
function deleteGroups() {
const count = groups.value.length
return open({
events: {
onConfirm: confirmDelete,
},
props: {
subject: t('n-groups', { n: count }),
description: t('group:delete-warning', { n: count }),
confirmLabel: t('action:delete-n-groups', { n: count }),
accent: 'danger',
},
})
}
return { deleteGroups, canDeleteGroups, isDeletingGroups, deleteGroupsErrorMessage }
}

View File

@@ -0,0 +1,39 @@
import type { FrontXoGroup } from '@/modules/group/remote-resources/use-xo-group-collection.ts'
import { useQueryBuilderSchema } from '@core/packages/query-builder/schema/use-query-builder-schema.ts'
import { useQueryBuilderFilter } from '@core/packages/query-builder/use-query-builder-filter.ts'
import { useNumberSchema } from '@core/utils/query-builder/use-number-schema.ts'
import { useStringSchema } from '@core/utils/query-builder/use-string-schema.ts'
import { computed, type MaybeRefOrGetter, toValue } from 'vue'
import { useI18n } from 'vue-i18n'
export type FilterableGroup = FrontXoGroup & { usersCount: number; rolesCount: number }
function toFilterableGroup(group: FrontXoGroup): FilterableGroup {
return {
...group,
usersCount: group.users.length,
rolesCount: group.aclRoleIds.length,
}
}
export function useGroupQueryBuilder(
id: string,
groups: MaybeRefOrGetter<FrontXoGroup[]>,
options?: Parameters<typeof useQueryBuilderFilter>[2]
) {
const { t } = useI18n()
const filterableGroups = computed(() => toValue(groups).map(group => toFilterableGroup(group)))
const { items, searchBindings } = useQueryBuilderFilter(id, filterableGroups, options)
const schema = useQueryBuilderSchema<FilterableGroup>({
'': useStringSchema(t('any-property')),
name: useStringSchema(t('name')),
provider: useStringSchema(t('provider')),
usersCount: useNumberSchema(t('users')),
rolesCount: useNumberSchema(t('roles')),
})
return { items, searchBindings, schema }
}

View File

@@ -0,0 +1,47 @@
import type { FrontXoGroup } from '@/modules/group/remote-resources/use-xo-group-collection.ts'
import { useXoRoleGroupsAddJob } from '@/modules/role/jobs/xo-role-groups-add.job.ts'
import { type FrontXoRole, useXoRoleCollection } from '@/modules/role/remote-resources/use-xo-role-collection.ts'
import { useOverlay } from '@core/packages/overlay/use-overlay.ts'
import { toComputed } from '@core/utils/to-computed.util.ts'
import { computed, type MaybeRefOrGetter, ref } from 'vue'
import { useI18n } from 'vue-i18n'
export function useGroupRolesAdd(rawGroup: MaybeRefOrGetter<FrontXoGroup>) {
const group = toComputed(rawGroup)
const { t } = useI18n()
const { roles } = useXoRoleCollection()
const selectableRoles = computed(() => roles.value.filter(role => !role.groupIds.includes(group.value.id)))
const rolesToAdd = ref<FrontXoRole[]>([])
const { run, isRunning: isAddingRoles } = useXoRoleGroupsAddJob(rolesToAdd, () => [group.value])
const canAddRoles = computed(() => selectableRoles.value.length > 0)
const { open } = useOverlay({
component: () => import('@/modules/role/components/drawer/SelectRolesDrawer.vue'),
events: {
onConfirm: (selectedRoles: FrontXoRole[]) => selectedRoles,
onCancel: true,
},
})
async function addRoles(): Promise<FrontXoRole[]> {
const response = await open({ props: { roles: selectableRoles.value, title: t('action:add-roles') } })
if (response.event !== 'onConfirm') {
return []
}
rolesToAdd.value = response.payload
run({ detached: true })
return response.payload
}
return { addRoles, canAddRoles, isAddingRoles }
}

View File

@@ -0,0 +1,47 @@
import { useXoGroupUsersAddJob } from '@/modules/group/jobs/xo-group-users-add.job.ts'
import type { FrontXoGroup } from '@/modules/group/remote-resources/use-xo-group-collection.ts'
import { type FrontXoUser, useXoUserCollection } from '@/modules/user/remote-resources/use-xo-user-collection.ts'
import { useOverlay } from '@core/packages/overlay/use-overlay.ts'
import { toComputed } from '@core/utils/to-computed.util.ts'
import { computed, type MaybeRefOrGetter, ref } from 'vue'
import { useI18n } from 'vue-i18n'
export function useGroupUsersAdd(rawGroup: MaybeRefOrGetter<FrontXoGroup>) {
const group = toComputed(rawGroup)
const { t } = useI18n()
const { users } = useXoUserCollection()
const selectableUsers = computed(() => users.value.filter(user => !group.value.users.includes(user.id)))
const usersToAdd = ref<FrontXoUser[]>([])
const { run, isRunning: isAddingUsers } = useXoGroupUsersAddJob(() => [group.value], usersToAdd)
const canAddUsers = computed(() => group.value.provider === undefined && selectableUsers.value.length > 0)
const { open } = useOverlay({
component: () => import('@/modules/user/components/drawer/SelectUsersDrawer.vue'),
events: {
onConfirm: (selectedUsers: FrontXoUser[]) => selectedUsers,
onCancel: true,
},
})
async function addUsers(): Promise<FrontXoUser[]> {
const response = await open({ props: { users: selectableUsers.value, title: t('action:add-users') } })
if (response.event !== 'onConfirm') {
return []
}
usersToAdd.value = response.payload
run({ detached: true })
return response.payload
}
return { addUsers, canAddUsers, isAddingUsers }
}

View File

@@ -0,0 +1,7 @@
import type { FrontXoGroup } from '@/modules/group/remote-resources/use-xo-group-collection.ts'
import { defineJobArg } from '@core/packages/job'
export const xoGroupsArg = defineJobArg({
identify: (group: FrontXoGroup) => group.id,
toArray: true,
})

View File

@@ -0,0 +1,45 @@
import { xoGroupsArg } from '@/modules/group/jobs/xo-group-args.ts'
import { type FrontXoGroup, useXoGroupCollection } from '@/modules/group/remote-resources/use-xo-group-collection.ts'
import { useXoUserCollection } from '@/modules/user/remote-resources/use-xo-user-collection.ts'
import { fetchDelete } from '@/shared/utils/fetch.util.ts'
import { defineJob, JobError, JobRunningError } from '@core/packages/job'
import { useI18n } from 'vue-i18n'
export const useXoGroupDeleteJob = defineJob('group.delete', [xoGroupsArg], () => {
const { t } = useI18n()
const { $context: groupContext } = useXoGroupCollection()
const { $context: userContext } = useXoUserCollection()
return {
async run(groups: FrontXoGroup[]) {
const results = await Promise.allSettled(groups.map(group => fetchDelete(`groups/${group.id}`)))
results.forEach((result, index) => {
if (result.status === 'rejected') {
console.error(`Failed to delete group ${groups[index].id}:`, result.reason)
}
})
groupContext.forceReload()
userContext.forceReload()
return results
},
validate: (isRunning, groups: FrontXoGroup[]) => {
if (groups.length === 0) {
throw new JobError(t('job:group-delete:missing-group'))
}
if (isRunning) {
throw new JobRunningError(t('job:delete:in-progress'))
}
if (groups.some(group => group.provider !== undefined)) {
throw new JobError(t('job:group-delete:synchronized-group'))
}
},
}
})

View File

@@ -0,0 +1,51 @@
import { xoGroupsArg } from '@/modules/group/jobs/xo-group-args.ts'
import { type FrontXoGroup, useXoGroupCollection } from '@/modules/group/remote-resources/use-xo-group-collection.ts'
import { xoUsersArg } from '@/modules/user/jobs/xo-user-args.ts'
import { type FrontXoUser, useXoUserCollection } from '@/modules/user/remote-resources/use-xo-user-collection.ts'
import { fetchPut } from '@/shared/utils/fetch.util.ts'
import { settleSequentially } from '@/shared/utils/promise.util.ts'
import { defineJob, JobError, JobRunningError } from '@core/packages/job'
import { useI18n } from 'vue-i18n'
export const useXoGroupUsersAddJob = defineJob('group.users.add', [xoGroupsArg, xoUsersArg], () => {
const { t } = useI18n()
const { $context: groupContext } = useXoGroupCollection()
const { $context: userContext } = useXoUserCollection()
return {
async run(groups: FrontXoGroup[], users: FrontXoUser[]) {
const results = await settleSequentially(
groups.flatMap(group => users.map(user => () => fetchPut(`groups/${group.id}/users/${user.id}`)))
)
results
.filter(result => result.status === 'rejected')
.forEach(result => console.error('Failed to add a user to a group:', result.reason))
groupContext.forceReload()
userContext.forceReload()
return results
},
validate: (isRunning, groups: FrontXoGroup[], users: FrontXoUser[]) => {
if (groups.length === 0) {
throw new JobError(t('job:group-users:missing-group'))
}
if (users.length === 0) {
throw new JobError(t('job:group-users:missing-user'))
}
if (isRunning) {
throw new JobRunningError(t('job:add:in-progress'))
}
if (groups.some(group => group.provider !== undefined)) {
throw new JobError(t('job:group-users:synchronized-group'))
}
},
}
})

View File

@@ -0,0 +1,51 @@
import { xoGroupsArg } from '@/modules/group/jobs/xo-group-args.ts'
import { type FrontXoGroup, useXoGroupCollection } from '@/modules/group/remote-resources/use-xo-group-collection.ts'
import { xoUsersArg } from '@/modules/user/jobs/xo-user-args.ts'
import { type FrontXoUser, useXoUserCollection } from '@/modules/user/remote-resources/use-xo-user-collection.ts'
import { fetchDelete } from '@/shared/utils/fetch.util.ts'
import { settleSequentially } from '@/shared/utils/promise.util.ts'
import { defineJob, JobError, JobRunningError } from '@core/packages/job'
import { useI18n } from 'vue-i18n'
export const useXoGroupUsersRemoveJob = defineJob('group.users.remove', [xoGroupsArg, xoUsersArg], () => {
const { t } = useI18n()
const { $context: groupContext } = useXoGroupCollection()
const { $context: userContext } = useXoUserCollection()
return {
async run(groups: FrontXoGroup[], users: FrontXoUser[]) {
const results = await settleSequentially(
groups.flatMap(group => users.map(user => () => fetchDelete(`groups/${group.id}/users/${user.id}`)))
)
results
.filter(result => result.status === 'rejected')
.forEach(result => console.error('Failed to remove a user from a group:', result.reason))
groupContext.forceReload()
userContext.forceReload()
return results
},
validate: (isRunning, groups: FrontXoGroup[], users: FrontXoUser[]) => {
if (groups.length === 0) {
throw new JobError(t('job:group-users:missing-group'))
}
if (users.length === 0) {
throw new JobError(t('job:group-users:missing-user'))
}
if (isRunning) {
throw new JobRunningError(t('job:detach:in-progress'))
}
if (groups.some(group => group.provider !== undefined)) {
throw new JobError(t('job:group-users:synchronized-group'))
}
},
}
})

View File

@@ -6,7 +6,7 @@ import type { XoGroup } from '@vates/types'
export type FrontXoGroup = Pick<XoGroup, (typeof groupFields)[number]>
const groupFields = ['id', 'name'] as const satisfies readonly (keyof XoGroup)[]
const groupFields = ['id', 'name', 'provider', 'users', 'aclRoleIds'] as const satisfies readonly (keyof XoGroup)[]
export const useXoGroupCollection = defineRemoteResource({
url: `${BASE_URL}/groups?fields=${groupFields.join(',')}&ndjson=true`,

View File

@@ -0,0 +1,18 @@
<template>
<UiAlert v-if="isInfoVisible" accent="info" close @close="hideInfo">
<span class="typo-body-bold">{{ t('role:what-is-a-role?') }}</span>
<template #description>
<span class="typo-body-regular">{{ t('role:what-is-a-role-description') }}</span>
</template>
</UiAlert>
</template>
<script lang="ts" setup>
import UiAlert from '@core/components/ui/alert/UiAlert.vue'
import { useHidePermanently } from '@core/packages/hide-permanently/use-hide-permanently.ts'
import { useI18n } from 'vue-i18n'
const { t } = useI18n()
const [isInfoVisible, hideInfo] = useHidePermanently('what-is-a-role')
</script>

View File

@@ -0,0 +1,63 @@
<template>
<DetailPageLayout>
<template #alert>
<RoleInfoAlert />
</template>
<template #menu="{ size }">
<UiMenuItem
:size
:to="{ name: '/admin/role/[id]/general', params: { id: role.id } }"
:selected="route.name === '/admin/role/[id]/general'"
>
{{ t('general') }}
</UiMenuItem>
<UiMenuItem
:size
:to="{ name: '/admin/role/[id]/users', params: { id: role.id } }"
:selected="route.name === '/admin/role/[id]/users'"
>
{{ t('users') }}
</UiMenuItem>
<UiMenuItem
:size
:to="{ name: '/admin/role/[id]/groups', params: { id: role.id } }"
:selected="route.name === '/admin/role/[id]/groups'"
>
{{ t('groups') }}
</UiMenuItem>
<UiMenuItem
:size
:to="{ name: '/admin/role/[id]/privileges', params: { id: role.id } }"
:selected="route.name === '/admin/role/[id]/privileges'"
>
{{ t('privileges') }}
</UiMenuItem>
</template>
<slot />
<template v-if="slots.panel" #panel>
<slot name="panel" />
</template>
</DetailPageLayout>
</template>
<script lang="ts" setup>
import RoleInfoAlert from '@/modules/role/components/RoleInfoAlert.vue'
import type { FrontXoRole } from '@/modules/role/remote-resources/use-xo-role-collection.ts'
import DetailPageLayout from '@/shared/components/DetailPageLayout.vue'
import UiMenuItem from '@core/components/ui/menu-item/UiMenuItem.vue'
import { useI18n } from 'vue-i18n'
import { useRoute } from 'vue-router'
defineProps<{
role: FrontXoRole
}>()
const slots = defineSlots<{
default(): any
panel?(): any
}>()
const { t } = useI18n()
const route = useRoute()
</script>

View File

@@ -0,0 +1,27 @@
<template>
<UiCard>
<UiTitle>
{{ t('role:details') }}
</UiTitle>
<VtsTabularKeyValueList>
<VtsTabularKeyValueRow :label="t('name')" :value="role.name" />
<VtsTabularKeyValueRow :label="t('uuid')" :value="role.id" />
<VtsTabularKeyValueRow :label="t('description')" :value="role.description" />
</VtsTabularKeyValueList>
</UiCard>
</template>
<script lang="ts" setup>
import type { FrontXoRole } from '@/modules/role/remote-resources/use-xo-role-collection.ts'
import VtsTabularKeyValueList from '@core/components/tabular-key-value-list/VtsTabularKeyValueList.vue'
import VtsTabularKeyValueRow from '@core/components/tabular-key-value-row/VtsTabularKeyValueRow.vue'
import UiCard from '@core/components/ui/card/UiCard.vue'
import UiTitle from '@core/components/ui/title/UiTitle.vue'
import { useI18n } from 'vue-i18n'
defineProps<{
role: FrontXoRole
}>()
const { t } = useI18n()
</script>

View File

@@ -0,0 +1,58 @@
<template>
<div class="role-header">
<UiBreadcrumb :size>
<span class="name">
<VtsIcon name="object:organization" size="current" />
{{ t('user-management') }}
</span>
<UiLink :size :to="{ name: '/admin/user-management/roles' }">
{{ t('roles') }}
</UiLink>
<span class="name">
<VtsIcon name="fa:key" size="current" />
{{ role.name }}
</span>
</UiBreadcrumb>
</div>
<UiHeadBar icon="fa:key">
{{ role.name }}
</UiHeadBar>
</template>
<script lang="ts" setup>
import type { FrontXoRole } from '@/modules/role/remote-resources/use-xo-role-collection.ts'
import VtsIcon from '@core/components/icon/VtsIcon.vue'
import UiBreadcrumb from '@core/components/ui/breadcrumb/UiBreadcrumb.vue'
import UiHeadBar from '@core/components/ui/head-bar/UiHeadBar.vue'
import UiLink from '@core/components/ui/link/UiLink.vue'
import { useUiStore } from '@core/stores/ui.store.ts'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
defineProps<{
role: FrontXoRole
}>()
const { t } = useI18n()
const uiStore = useUiStore()
const size = computed(() => (uiStore.isSmall ? 'small' : 'medium'))
</script>
<style lang="postcss" scoped>
.role-header {
min-height: 5.6rem;
padding: 1.2rem 1.6rem;
display: flex;
align-items: center;
border-block-end: 0.1rem solid var(--color-neutral-border);
background-color: var(--color-neutral-background-primary);
.name {
display: flex;
align-items: center;
gap: 0.8rem;
}
}
</style>

View File

@@ -0,0 +1,140 @@
<template>
<AssignmentsTableLayout
:title="t('groups')"
:can-add="canAddGroups"
:is-adding="isAddingGroups"
:can-detach="canDetachSelectedGroups"
:is-detaching="isDetachingSelectedGroups"
:detach-error-message="detachSelectedGroupsErrorMessage"
@add="addGroupsUnselected()"
@detach="detachSelectedGroups({ detached: true, onSuccess: selectionBindings.onClearSelection })"
>
<template #filter>
<VtsQueryBuilder v-bind="searchBindings" :schema />
</template>
<VtsTable :state :pagination-bindings :selection-bindings sticky="right">
<thead>
<tr>
<HeadCells />
</tr>
</thead>
<tbody>
<VtsRow v-for="group of paginatedGroups" :key="group.id" :selected="selectedGroupId === group.id">
<BodyCells :item="group" />
</VtsRow>
</tbody>
</VtsTable>
</AssignmentsTableLayout>
</template>
<script lang="ts" setup>
import {
type FilterableGroup,
useGroupQueryBuilder,
} from '@/modules/group/composables/use-group-query-builder.composable.ts'
import type { FrontXoGroup } from '@/modules/group/remote-resources/use-xo-group-collection.ts'
import { useRoleGroupsAdd } from '@/modules/role/composables/use-role-groups-add.composable.ts'
import { useXoRoleGroupsRemoveJob } from '@/modules/role/jobs/xo-role-groups-remove.job.ts'
import type { FrontXoRole } from '@/modules/role/remote-resources/use-xo-role-collection.ts'
import AssignmentsTableLayout from '@/shared/components/AssignmentsTableLayout.vue'
import VtsQueryBuilder from '@core/components/query-builder/VtsQueryBuilder.vue'
import VtsRow from '@core/components/table/VtsRow.vue'
import VtsTable from '@core/components/table/VtsTable.vue'
import { usePagination } from '@core/composables/pagination.composable.ts'
import { useRouteQuery } from '@core/composables/route-query.composable.ts'
import { useTableSelection } from '@core/composables/table-selection.composable.ts'
import { useTableState } from '@core/composables/table-state.composable.ts'
import { useGroupColumns } from '@core/tables/column-sets/group-columns.ts'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
const { role, groups, busy, error } = defineProps<{
role: FrontXoRole
groups: FrontXoGroup[]
busy?: boolean
error?: boolean
}>()
const { t } = useI18n()
const selectedGroupId = useRouteQuery('id')
const { addGroups, canAddGroups, isAddingGroups } = useRoleGroupsAdd(() => role)
const { items: filteredGroups, searchBindings, schema } = useGroupQueryBuilder('role-groups', () => groups)
const { pageRecords: paginatedGroups, paginationBindings } = usePagination('role-groups', filteredGroups)
const state = useTableState({
busy: () => busy,
error: () => error,
empty: () =>
groups.length === 0 ? t('no-group-attached') : filteredGroups.value.length === 0 ? { type: 'no-result' } : false,
})
const { selectedIds, pageSelectionModel, isSelected, toggleSelection, selectionBindings } = useTableSelection({
items: () => groups,
filteredItems: filteredGroups,
pageItems: paginatedGroups,
getItemId: group => group.id,
})
async function addGroupsUnselected() {
const addedGroups = await addGroups()
addedGroups.forEach(group => toggleSelection(group.id, false))
}
const selectedGroups = computed(() => groups.filter(group => selectedIds.value.includes(group.id)))
const {
run: detachSelectedGroups,
canRun: canDetachSelectedGroups,
isRunning: isDetachingSelectedGroups,
errorMessage: detachSelectedGroupsErrorMessage,
} = useXoRoleGroupsRemoveJob(() => [role], selectedGroups)
const { HeadCells, BodyCells } = useGroupColumns({
head: () => ({
checkbox: r => r(pageSelectionModel),
}),
body: (group: FilterableGroup) => {
const {
run: detachGroup,
canRun: canDetachGroup,
isRunning: isDetachingGroup,
errorMessage: detachGroupErrorMessage,
} = useXoRoleGroupsRemoveJob(
() => [role],
() => [group]
)
return {
checkbox: r => r({ selected: isSelected(group.id), onToggle: () => toggleSelection(group.id) }),
name: r =>
r({
label: group.name,
icon: 'table:group',
to: { name: '/admin/group/[id]/general', params: { id: group.id } },
}),
provider: r => r(group.provider ?? ''),
users: r => r(group.usersCount),
roles: r => r(group.rolesCount),
actions: r =>
r({
onClick: () => (selectedGroupId.value = group.id),
actions: [
{
label: t('action:detach'),
icon: 'action:detach',
onClick: () => detachGroup({ detached: true, onSuccess: () => toggleSelection(group.id, false) }),
disabled: !canDetachGroup.value,
busy: isDetachingGroup.value,
hint: detachGroupErrorMessage.value,
},
],
}),
}
},
})
</script>

View File

@@ -0,0 +1,107 @@
<template>
<div class="role-privileges-table">
<UiTitle>
{{ t('privileges') }}
</UiTitle>
<VtsQueryBuilder v-bind="searchBindings" :schema />
<VtsTable :state :pagination-bindings sticky="right">
<thead>
<tr>
<HeadCells />
</tr>
</thead>
<tbody>
<VtsRow
v-for="privilege of paginatedPrivileges"
:key="privilege.id"
:selected="selectedPrivilegeId === privilege.id"
>
<BodyCells :item="privilege" />
</VtsRow>
</tbody>
</VtsTable>
</div>
</template>
<script lang="ts" setup>
import { usePrivilegeAppliedToCount } from '@/modules/role/composables/use-privilege-applied-to-count.composable.ts'
import { usePrivilegeQueryBuilder } from '@/modules/role/composables/use-privilege-query-builder.composable.ts'
import { usePrivilegeScopeTypeLabels } from '@/modules/role/composables/use-privilege-scope-type-labels.composable.ts'
import type { FrontXoPrivilege } from '@/modules/role/remote-resources/use-xo-role-privileges-collection.ts'
import { getPrivilegeScopeType } from '@/modules/role/utils/privilege-scope.util.ts'
import { EFFECT_ACCENTS } from '@/modules/role/utils/xo-privilege.util.ts'
import VtsQueryBuilder from '@core/components/query-builder/VtsQueryBuilder.vue'
import VtsRow from '@core/components/table/VtsRow.vue'
import VtsTable from '@core/components/table/VtsTable.vue'
import UiTitle from '@core/components/ui/title/UiTitle.vue'
import { usePagination } from '@core/composables/pagination.composable.ts'
import { useRouteQuery } from '@core/composables/route-query.composable.ts'
import { useTableState } from '@core/composables/table-state.composable.ts'
import { usePrivilegeColumns } from '@core/tables/column-sets/privilege-columns.ts'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
const { privileges, busy, error } = defineProps<{
privileges: FrontXoPrivilege[]
busy?: boolean
error?: boolean
}>()
const { t } = useI18n()
const selectedPrivilegeId = useRouteQuery('id')
const {
items: filteredPrivileges,
searchBindings,
schema,
} = usePrivilegeQueryBuilder('role-privileges', () => privileges)
const state = useTableState({
busy: () => busy,
error: () => error,
empty: () =>
privileges.length === 0
? t('no-privilege-attached')
: filteredPrivileges.value.length === 0
? { type: 'no-result' }
: false,
})
const { pageRecords: paginatedPrivileges, paginationBindings } = usePagination('role-privileges', filteredPrivileges)
const scopeTypeLabels = usePrivilegeScopeTypeLabels()
const privilegeNumberById = computed(
() => new Map(privileges.map((privilege, index) => [privilege.id, String(index + 1)]))
)
const { HeadCells, BodyCells } = usePrivilegeColumns({
exclude: ['edit', 'remove'],
body: (privilege: FrontXoPrivilege) => {
const appliedToCount = usePrivilegeAppliedToCount(privilege)
return {
index: r =>
r({
label: privilegeNumberById.value.get(privilege.id) ?? '',
to: { name: '/admin/privilege/[id]/general', params: { id: privilege.id } },
}),
resource: r => r(privilege.resource),
scope: r => r(scopeTypeLabels[getPrivilegeScopeType(privilege.resource, privilege.selector)]),
appliedTo: r => r(appliedToCount.value),
action: r => r(privilege.action),
effect: r => r(t(privilege.effect), EFFECT_ACCENTS[privilege.effect]),
selectItem: r => r(() => (selectedPrivilegeId.value = privilege.id)),
}
},
})
</script>
<style lang="postcss" scoped>
.role-privileges-table {
display: flex;
flex-direction: column;
gap: 2.4rem;
}
</style>

View File

@@ -0,0 +1,140 @@
<template>
<AssignmentsTableLayout
:title="t('users')"
:can-add="canAddUsers"
:is-adding="isAddingUsers"
:can-detach="canDetachSelectedUsers"
:is-detaching="isDetachingSelectedUsers"
:detach-error-message="detachSelectedUsersErrorMessage"
@add="addUsersUnselected()"
@detach="detachSelectedUsers({ detached: true, onSuccess: selectionBindings.onClearSelection })"
>
<template #filter>
<VtsQueryBuilder v-bind="searchBindings" :schema />
</template>
<VtsTable :state :pagination-bindings :selection-bindings sticky="right">
<thead>
<tr>
<HeadCells />
</tr>
</thead>
<tbody>
<VtsRow v-for="user of paginatedUsers" :key="user.id" :selected="selectedUserId === user.id">
<BodyCells :item="user" />
</VtsRow>
</tbody>
</VtsTable>
</AssignmentsTableLayout>
</template>
<script lang="ts" setup>
import { useRoleUsersAdd } from '@/modules/role/composables/use-role-users-add.composable.ts'
import type { RoleUser } from '@/modules/role/composables/use-xo-role-users.composable.ts'
import { useXoRoleUsersRemoveJob } from '@/modules/role/jobs/xo-role-users-remove.job.ts'
import type { FrontXoRole } from '@/modules/role/remote-resources/use-xo-role-collection.ts'
import {
type FilterableUser,
useUserQueryBuilder,
} from '@/modules/user/composables/use-user-query-builder.composable.ts'
import { getUserDisplayName } from '@/modules/user/utils/xo-user.util.ts'
import AssignmentsTableLayout from '@/shared/components/AssignmentsTableLayout.vue'
import VtsQueryBuilder from '@core/components/query-builder/VtsQueryBuilder.vue'
import VtsRow from '@core/components/table/VtsRow.vue'
import VtsTable from '@core/components/table/VtsTable.vue'
import { usePagination } from '@core/composables/pagination.composable.ts'
import { useRouteQuery } from '@core/composables/route-query.composable.ts'
import { useTableSelection } from '@core/composables/table-selection.composable.ts'
import { useTableState } from '@core/composables/table-state.composable.ts'
import { useUserColumns } from '@core/tables/column-sets/user-columns.ts'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
const { role, users, busy, error } = defineProps<{
role: FrontXoRole
users: RoleUser[]
busy?: boolean
error?: boolean
}>()
const { t } = useI18n()
const selectedUserId = useRouteQuery('id')
const { addUsers, canAddUsers, isAddingUsers } = useRoleUsersAdd(() => role)
const { items: filteredUsers, searchBindings, schema } = useUserQueryBuilder('role-users', () => users)
const { pageRecords: paginatedUsers, paginationBindings } = usePagination('role-users', filteredUsers)
const state = useTableState({
busy: () => busy,
error: () => error,
empty: () =>
users.length === 0 ? t('no-user-attached') : filteredUsers.value.length === 0 ? { type: 'no-result' } : false,
})
const { selectedIds, pageSelectionModel, isSelected, toggleSelection, selectionBindings } = useTableSelection({
items: () => users.filter(user => user.isDirect),
filteredItems: () => filteredUsers.value.filter(user => user.isDirect),
pageItems: () => paginatedUsers.value.filter(user => user.isDirect),
getItemId: user => user.id,
})
async function addUsersUnselected() {
const addedUsers = await addUsers()
addedUsers.forEach(user => toggleSelection(user.id, false))
}
const hasNoDirectUserOnPage = computed(() => paginatedUsers.value.every(user => !user.isDirect))
const selectedUsers = computed(() => users.filter(user => selectedIds.value.includes(user.id)))
const {
run: detachSelectedUsers,
canRun: canDetachSelectedUsers,
isRunning: isDetachingSelectedUsers,
errorMessage: detachSelectedUsersErrorMessage,
} = useXoRoleUsersRemoveJob(() => [role], selectedUsers)
const { HeadCells, BodyCells } = useUserColumns({
exclude: ['providers'],
head: () => ({
checkbox: r => r(pageSelectionModel, { disabled: hasNoDirectUserOnPage.value }),
}),
body: (user: FilterableUser<RoleUser>) => {
const {
run: detachUser,
canRun: canDetachUser,
isRunning: isDetachingUser,
errorMessage: detachUserErrorMessage,
} = useXoRoleUsersRemoveJob(
() => [role],
() => [user]
)
return {
checkbox: r =>
user.isDirect ? r({ selected: isSelected(user.id), onToggle: () => toggleSelection(user.id) }) : r(),
username: r => r(getUserDisplayName(user), { to: { name: '/admin/user/[id]/general', params: { id: user.id } } }),
firstName: r => r(user.firstname),
lastName: r => r(user.lastname),
email: r => r(user.email),
actions: r =>
r({
onClick: () => (selectedUserId.value = user.id),
actions: [
{
label: t('action:detach'),
icon: 'action:detach',
onClick: () => detachUser({ detached: true, onSuccess: () => toggleSelection(user.id, false) }),
disabled: !canDetachUser.value,
busy: isDetachingUser.value,
hint: detachUserErrorMessage.value,
},
],
}),
}
},
})
</script>

View File

@@ -0,0 +1,304 @@
<template>
<UiDrawer @confirm="onSubmit()" @dismiss="emit('cancel')">
<template #title>
{{ privilegeToEdit === undefined ? t('privilege:create-new') : t('privilege:edit') }}
</template>
<template #content>
<UiStepper :steps :current-step="currentStepIndex">
<div v-if="currentStep === 'details'" class="fields">
<RoleFormSelect v-bind="resourceSelectBindings" />
<RoleFormSelect v-bind="actionsSelectBindings" />
<RoleFormSelect v-bind="effectSelectBindings" />
</div>
<div v-else-if="currentStep === 'scope'" class="scope">
<UiRadioButtonGroup accent="brand" gap="wide" :label="t('privilege:scope-type')">
<UiRadioButton
v-for="scopeType of PRIVILEGE_SCOPE_TYPES"
:key="scopeType"
v-model="formData.scope.scopeType"
accent="brand"
:value="scopeType"
:disabled="!availableScopeTypes.includes(scopeType)"
>
{{ scopeTypeLabels[scopeType] }}
</UiRadioButton>
</UiRadioButtonGroup>
<div
v-if="formData.scope.scopeType === 'manual-selection' && selectableResource !== undefined"
class="selector"
>
<PrivilegeScopeResourceTable
v-model:selected-ids="formData.scope.selectedIds"
:resource="selectableResource"
/>
<UiInfo v-if="selectedIdsError !== undefined" accent="danger" wrap>
{{ selectedIdsError }}
</UiInfo>
</div>
<template v-else-if="formData.scope.scopeType === 'dynamic-selection'">
<div class="selector">
<VtsQueryBuilder v-bind="selectorSearchBindings" :schema="selectorSchema" />
<UiInfo :accent="selectorMessage.accent" wrap>
{{ selectorMessage.content }}
</UiInfo>
</div>
<PrivilegeScopePreviewTable
v-if="isSelectorPreviewEnabled && selectableResource !== undefined"
:resource="selectableResource"
:matches="selectorMatches"
:is-ready="areSelectorMatchesReady"
:has-error="hasSelectorMatchesError"
/>
</template>
</div>
<div v-else class="review">
<UiTitle>
{{ t('privilege:details') }}
<template #action>
<UiButton left-icon="fa:edit" variant="tertiary" accent="brand" size="medium" @click="backTo('details')">
{{ t('action:edit') }}
</UiButton>
</template>
</UiTitle>
<dl class="review-fields">
<dt>{{ t('privilege:resource') }}</dt>
<dd>{{ formData.details.resource }}</dd>
<dt>{{ t('privilege:action') }}</dt>
<dd>{{ formData.details.actions.join(', ') }}</dd>
<dt>{{ t('privilege:effect') }}</dt>
<dd>
<UiTagsList>
<UiTag :accent="EFFECT_ACCENTS[formData.details.effect]" variant="secondary">
{{ t(formData.details.effect) }}
</UiTag>
</UiTagsList>
</dd>
</dl>
<UiTitle class="scope-title">
{{ t('privilege:scope') }}
<template #action>
<UiButton left-icon="fa:edit" variant="tertiary" accent="brand" size="medium" @click="backTo('scope')">
{{ t('action:edit') }}
</UiButton>
</template>
</UiTitle>
<dl class="review-fields">
<dt>{{ t('privilege:scope-type') }}</dt>
<dd>{{ scopeTypeLabels[formData.scope.scopeType] }}</dd>
<template v-if="formData.scope.scopeType === 'manual-selection' && selectableResource !== undefined">
<dt class="top-aligned">{{ t('privilege:scope') }}</dt>
<dd>
<PrivilegeScopeObjectsList :resource="selectableResource" :ids="formData.scope.selectedIds" />
</dd>
</template>
<template v-if="formData.scope.scopeType === 'dynamic-selection' && selectableResource !== undefined">
<dt class="top-aligned">{{ t('privilege:selector') }}</dt>
<dd>
<UiLogEntryViewer :content="formData.scope.selector" size="medium" accent="info" />
</dd>
<dt class="top-aligned">{{ t('privilege:scope-preview') }}</dt>
<dd class="scope-preview">
<PrivilegeScopeObjectsList :resource="selectableResource" :ids="selectorMatchIds" />
</dd>
</template>
</dl>
</div>
</UiStepper>
</template>
<template #buttons>
<VtsOverlayCancelButton v-if="currentStep === 'details'" @click="emit('cancel')" />
<VtsOverlayButton v-else variant="secondary" @click="back()">
{{ t('action:go-back') }}
</VtsOverlayButton>
<VtsOverlayConfirmButton>
{{ confirmLabel }}
</VtsOverlayConfirmButton>
</template>
</UiDrawer>
</template>
<script lang="ts" setup>
import PrivilegeScopeObjectsList from '@/modules/role/components/drawer/scope/PrivilegeScopeObjectsList.vue'
import PrivilegeScopePreviewTable from '@/modules/role/components/drawer/scope/PrivilegeScopePreviewTable.vue'
import PrivilegeScopeResourceTable from '@/modules/role/components/drawer/scope/PrivilegeScopeResourceTable.vue'
import RoleFormSelect from '@/modules/role/components/form/inputs/RoleFormSelect.vue'
import { usePrivilegeScopeTypeLabels } from '@/modules/role/composables/use-privilege-scope-type-labels.composable.ts'
import { useNewPrivilegeForm } from '@/modules/role/form/new-privilege/use-new-privilege-form.ts'
import type { NewPrivilegePayload } from '@/modules/role/types.ts'
import { PRIVILEGE_SCOPE_TYPES } from '@/modules/role/utils/privilege-scope.util.ts'
import { EFFECT_ACCENTS } from '@/modules/role/utils/xo-privilege.util.ts'
import type { InfoAccent } from '@core/components/ui/info/UiInfo.vue'
import type { StepDefinition } from '@core/components/ui/stepper/UiStepper.vue'
import VtsOverlayButton from '@core/components/overlay/VtsOverlayButton.vue'
import VtsOverlayCancelButton from '@core/components/overlay/VtsOverlayCancelButton.vue'
import VtsOverlayConfirmButton from '@core/components/overlay/VtsOverlayConfirmButton.vue'
import VtsQueryBuilder from '@core/components/query-builder/VtsQueryBuilder.vue'
import UiButton from '@core/components/ui/button/UiButton.vue'
import UiDrawer from '@core/components/ui/drawer/UiDrawer.vue'
import UiInfo from '@core/components/ui/info/UiInfo.vue'
import UiLogEntryViewer from '@core/components/ui/log-entry-viewer/UiLogEntryViewer.vue'
import UiRadioButton from '@core/components/ui/radio-button/UiRadioButton.vue'
import UiRadioButtonGroup from '@core/components/ui/radio-button-group/UiRadioButtonGroup.vue'
import UiStepper from '@core/components/ui/stepper/UiStepper.vue'
import UiTag from '@core/components/ui/tag/UiTag.vue'
import UiTagsList from '@core/components/ui/tag/UiTagsList.vue'
import UiTitle from '@core/components/ui/title/UiTitle.vue'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
const { privilegeToEdit } = defineProps<{
privilegeToEdit?: NewPrivilegePayload
}>()
const emit = defineEmits<{
confirm: [privileges: NewPrivilegePayload[]]
cancel: []
}>()
const { t } = useI18n()
const scopeTypeLabels = usePrivilegeScopeTypeLabels()
const {
formData,
currentStep,
next,
back,
backTo,
resourceSelectBindings,
actionsSelectBindings,
effectSelectBindings,
selectableResource,
availableScopeTypes,
selectorSchema,
selectorError,
selectorSearchBindings,
selectedIdsError,
isSelectorPreviewEnabled,
selectorMatches,
areSelectorMatchesReady,
hasSelectorMatchesError,
validateAndBuildPayloads,
} = useNewPrivilegeForm(privilegeToEdit)
const selectorMatchIds = computed(() => selectorMatches.value.map(match => match.id))
const steps = computed<StepDefinition[]>(() => [
{ label: t('privilege:details') },
{ label: t('privilege:select-scope') },
{ label: t('privilege:review-and-confirm') },
])
const selectorMessage = computed<{ content: string; accent: InfoAccent }>(() => {
if (selectorError.value !== undefined) {
return { content: selectorError.value, accent: 'danger' }
}
return { content: t('privilege:dynamic-selection-info'), accent: 'info' }
})
const confirmLabel = computed(() => {
if (currentStep.value !== 'review') {
return t('action:continue')
}
return privilegeToEdit === undefined ? t('action:create') : t('action:save')
})
const stepNames = ['details', 'scope', 'review'] as const
const currentStepIndex = computed(() => stepNames.indexOf(currentStep.value))
async function onSubmit() {
if (currentStep.value !== 'review') {
await next()
return
}
const privileges = await validateAndBuildPayloads()
if (privileges !== undefined) {
emit('confirm', privileges)
}
}
</script>
<style lang="postcss" scoped>
.fields {
display: flex;
flex-direction: column;
gap: 2.4rem;
@media (--medium-or-large) {
display: grid;
grid-template-columns: repeat(3, 1fr);
align-items: start;
}
}
.scope {
display: flex;
flex-direction: column;
gap: 2.4rem;
.selector {
display: flex;
flex-direction: column;
gap: 0.4rem;
}
}
.review {
display: grid;
grid-template-columns: auto 1fr;
gap: 1.6rem 6.4rem;
> * {
grid-column: 1 / -1;
}
.scope-title {
margin-block-start: 1.6rem;
}
.review-fields {
display: grid;
grid-template-columns: subgrid;
align-items: center;
row-gap: 0.8rem;
margin: 0;
}
dt {
color: var(--color-neutral-txt-secondary);
&.top-aligned {
align-self: start;
}
}
dd {
margin: 0;
}
.scope-preview {
max-height: 24rem;
overflow: auto;
}
}
</style>

View File

@@ -0,0 +1,112 @@
<template>
<div class="roles-selection-table">
<VtsQueryBuilder v-bind="searchBindings" :schema />
<VtsTable :state :pagination-bindings :selection-bindings>
<thead>
<tr>
<HeadCells />
</tr>
</thead>
<tbody>
<VtsRow v-for="role of paginatedRoles" :key="role.id">
<BodyCells :item="role" />
</VtsRow>
</tbody>
</VtsTable>
</div>
</template>
<script lang="ts" setup>
import {
type FilterableRole,
useRoleQueryBuilder,
} from '@/modules/role/composables/use-role-query-builder.composable.ts'
import type { FrontXoRole } from '@/modules/role/remote-resources/use-xo-role-collection.ts'
import VtsQueryBuilder from '@core/components/query-builder/VtsQueryBuilder.vue'
import VtsRow from '@core/components/table/VtsRow.vue'
import VtsTable from '@core/components/table/VtsTable.vue'
import { usePagination } from '@core/composables/pagination.composable.ts'
import { useTableSelection } from '@core/composables/table-selection.composable.ts'
import { useTableState } from '@core/composables/table-state.composable.ts'
import { useRoleColumns } from '@core/tables/column-sets/role-columns.ts'
import { computed, watch } from 'vue'
import { useI18n } from 'vue-i18n'
const {
roles,
inheritedRoleIds = [],
busy,
error,
} = defineProps<{
roles: FrontXoRole[]
inheritedRoleIds?: FrontXoRole['id'][]
busy?: boolean
error?: boolean
}>()
const selectedRoleIds = defineModel<FrontXoRole['id'][]>('selectedRoleIds', { required: true })
const { t } = useI18n()
const {
items: filteredRoles,
searchBindings,
schema,
} = useRoleQueryBuilder('roles-selection', () => roles, {
ignoreRoute: true,
})
const { pageRecords: paginatedRoles, paginationBindings } = usePagination('roles-selection', filteredRoles, {
ignoreRoute: true,
})
const state = useTableState({
busy: () => busy,
error: () => error,
empty: () =>
roles.length === 0 ? t('no-role-detected') : filteredRoles.value.length === 0 ? { type: 'no-result' } : false,
})
const selectableRoles = computed(() => roles.filter(role => !inheritedRoleIds.includes(role.id)))
const { selectedIds, pageSelectionModel, isSelected, toggleSelection, selectionBindings } = useTableSelection({
items: selectableRoles,
filteredItems: filteredRoles,
pageItems: paginatedRoles,
getItemId: role => role.id,
})
const hasNoSelectableRoleOnPage = computed(() => paginatedRoles.value.every(role => inheritedRoleIds.includes(role.id)))
watch(selectedIds, ids => {
selectedRoleIds.value = selectableRoles.value.filter(role => ids.includes(role.id)).map(role => role.id)
})
const { HeadCells, BodyCells } = useRoleColumns({
exclude: ['group', 'actions'],
head: () => ({
checkbox: r => r(pageSelectionModel, { disabled: hasNoSelectableRoleOnPage.value }),
}),
body: (role: FilterableRole) => ({
checkbox: r =>
r({
selected: inheritedRoleIds.includes(role.id) || isSelected(role.id),
disabled: inheritedRoleIds.includes(role.id),
onToggle: () => toggleSelection(role.id),
}),
name: r => r({ label: role.name, icon: 'fa:key' }),
description: r => r(role.description),
users: r => r(role.usersCount),
groups: r => r(role.groupsCount),
privileges: r => r(role.privilegesCount),
}),
})
</script>
<style lang="postcss" scoped>
.roles-selection-table {
display: flex;
flex-direction: column;
gap: 0.8rem;
}
</style>

View File

@@ -0,0 +1,73 @@
<template>
<UiDrawer @confirm="confirm()" @dismiss="emit('cancel')">
<template #title>
{{ title }}
</template>
<template #content>
<div class="content">
<RolesSelectionTable v-model:selected-role-ids="selectedRoleIds" :roles />
<UiInfo v-if="isSelectionErrorVisible" accent="danger">
{{ t('select-at-least-one-role.') }}
</UiInfo>
</div>
</template>
<template #buttons>
<VtsOverlayCancelButton @click="emit('cancel')" />
<VtsOverlayConfirmButton>
{{ t('action:add') }}
</VtsOverlayConfirmButton>
</template>
</UiDrawer>
</template>
<script lang="ts" setup>
import RolesSelectionTable from '@/modules/role/components/drawer/RolesSelectionTable.vue'
import type { FrontXoRole } from '@/modules/role/remote-resources/use-xo-role-collection.ts'
import VtsOverlayCancelButton from '@core/components/overlay/VtsOverlayCancelButton.vue'
import VtsOverlayConfirmButton from '@core/components/overlay/VtsOverlayConfirmButton.vue'
import UiDrawer from '@core/components/ui/drawer/UiDrawer.vue'
import UiInfo from '@core/components/ui/info/UiInfo.vue'
import { computed, ref } from 'vue'
import { useI18n } from 'vue-i18n'
const { roles } = defineProps<{
roles: FrontXoRole[]
title: string
}>()
const emit = defineEmits<{
confirm: [roles: FrontXoRole[]]
cancel: []
}>()
const { t } = useI18n()
const selectedRoleIds = ref<FrontXoRole['id'][]>([])
const hasTriedToConfirm = ref(false)
const isSelectionErrorVisible = computed(() => hasTriedToConfirm.value && selectedRoleIds.value.length === 0)
function confirm() {
hasTriedToConfirm.value = true
if (selectedRoleIds.value.length === 0) {
return
}
emit(
'confirm',
roles.filter(role => selectedRoleIds.value.includes(role.id))
)
}
</script>
<style lang="postcss" scoped>
.content {
display: flex;
flex-direction: column;
gap: 0.8rem;
}
</style>

View File

@@ -0,0 +1,131 @@
<template>
<div class="privilege-scope-hosts-table">
<VtsQueryBuilder v-bind="searchBindings" :schema />
<VtsTable :state :pagination-bindings :selection-bindings="readonly ? undefined : selectionBindings">
<thead>
<tr>
<HeadCells />
</tr>
</thead>
<tbody>
<VtsRow v-for="host of paginatedHosts" :key="host.id">
<BodyCells :item="host" />
</VtsRow>
</tbody>
</VtsTable>
</div>
</template>
<script lang="ts" setup>
import { useHostQueryBuilder } from '@/modules/host/composables/use-host-query-builder.composable.ts'
import { type FrontXoHost, useXoHostCollection } from '@/modules/host/remote-resources/use-xo-host-collection.ts'
import { getHostIcon } from '@/modules/host/utils/xo-host.util.ts'
import { useXoPifCollection } from '@/modules/pif/remote-resources/use-xo-pif-collection.ts'
import { getHostIpAddresses } from '@/modules/pif/utils/xo-pif.util.ts'
import VtsQueryBuilder from '@core/components/query-builder/VtsQueryBuilder.vue'
import VtsRow from '@core/components/table/VtsRow.vue'
import VtsTable from '@core/components/table/VtsTable.vue'
import { usePagination } from '@core/composables/pagination.composable.ts'
import { useTableSelection } from '@core/composables/table-selection.composable.ts'
import { useTableState } from '@core/composables/table-state.composable.ts'
import { icon } from '@core/icons'
import { useHostColumns } from '@core/tables/column-sets/host-columns.ts'
import { logicAnd, logicNot, logicOr } from '@vueuse/math'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
const { visibleIds, readonly = false } = defineProps<{
visibleIds?: string[]
readonly?: boolean
}>()
const selectedIds = defineModel<string[]>('selectedIds', { default: () => [] })
const { t } = useI18n()
const { hosts, areHostsReady, hasHostFetchError, isMasterHost } = useXoHostCollection()
const visibleHosts = computed(() =>
visibleIds === undefined ? hosts.value : hosts.value.filter(host => visibleIds.includes(host.id))
)
const { pifsByHost, arePifsReady, hasPifFetchError } = useXoPifCollection()
const isReady = logicAnd(areHostsReady, arePifsReady)
const {
items: filteredHosts,
searchBindings,
schema,
} = useHostQueryBuilder('privilege-scope-hosts', visibleHosts, {
ignoreRoute: true,
})
const state = useTableState({
busy: logicNot(isReady),
error: logicOr(hasHostFetchError, hasPifFetchError),
empty: () =>
visibleHosts.value.length === 0
? t('no-host-detected')
: filteredHosts.value.length === 0
? { type: 'no-result' }
: false,
})
const { pageRecords: paginatedHosts, paginationBindings } = usePagination('privilege-scope-hosts', filteredHosts, {
ignoreRoute: true,
})
const { pageSelectionModel, isSelected, toggleSelection, selectionBindings } = useTableSelection({
items: visibleHosts,
filteredItems: filteredHosts,
pageItems: paginatedHosts,
getItemId: (host): string => host.id,
selectedIds,
})
function getMasterIcon(host: FrontXoHost) {
if (!isMasterHost(host.id)) {
return undefined
}
return {
icon: icon('status:primary-circle'),
tooltip: t('master'),
}
}
const { HeadCells, BodyCells } = useHostColumns({
exclude: ['srStatus', 'selectItem', 'actions'],
head: () => ({
checkbox: r => (readonly ? r() : r(pageSelectionModel)),
}),
body: (host: FrontXoHost) => {
const ipAddresses = computed(() => getHostIpAddresses(host.address, pifsByHost.value.get(host.id)))
const hostIcon = computed(() => getHostIcon(host))
const rightIcon = computed(() => getMasterIcon(host))
return {
checkbox: r => (readonly ? r() : r({ selected: isSelected(host.id), onToggle: () => toggleSelection(host.id) })),
host: r =>
r({
label: host.name_label,
to: { name: '/host/[id]/dashboard', params: { id: host.id } },
icon: hostIcon.value,
rightIcon: rightIcon.value,
}),
description: r => r(host.name_description),
ipAddresses: r => r(ipAddresses.value),
tags: r => r(host.tags),
}
},
})
</script>
<style lang="postcss" scoped>
.privilege-scope-hosts-table {
display: flex;
flex-direction: column;
gap: 0.8rem;
}
</style>

View File

@@ -0,0 +1,34 @@
<template>
<ul class="privilege-scope-objects-list">
<li v-for="object of selectedObjects" :key="object.id">
<UiLink size="medium" :to="object.to" :icon="object.icon">{{ object.label }}</UiLink>
</li>
</ul>
</template>
<script lang="ts" setup>
import { usePrivilegeScopeObjectsByIds } from '@/modules/role/composables/use-privilege-scope-objects-by-ids.composable.ts'
import type { SelectablePrivilegeResource } from '@/modules/role/utils/privilege-catalogue.util.ts'
import UiLink from '@core/components/ui/link/UiLink.vue'
const { resource, ids } = defineProps<{
resource: SelectablePrivilegeResource
ids: string[]
}>()
const { objects: selectedObjects } = usePrivilegeScopeObjectsByIds(
() => resource,
() => ids
)
</script>
<style lang="postcss" scoped>
.privilege-scope-objects-list {
display: flex;
flex-direction: column;
gap: 0.4rem;
margin: 0;
padding: 0;
list-style: none;
}
</style>

View File

@@ -0,0 +1,97 @@
<template>
<div class="privilege-scope-objects-table">
<VtsQueryBuilder v-bind="searchBindings" :schema />
<VtsTable :state :pagination-bindings :selection-bindings="readonly ? undefined : selectionBindings">
<thead>
<tr>
<HeadCells />
</tr>
</thead>
<tbody>
<VtsRow v-for="object of paginatedObjects" :key="object.id">
<BodyCells :item="object" />
</VtsRow>
</tbody>
</VtsTable>
</div>
</template>
<script lang="ts" setup>
import type { PrivilegeScopeObject } from '@/modules/role/types.ts'
import VtsQueryBuilder from '@core/components/query-builder/VtsQueryBuilder.vue'
import VtsRow from '@core/components/table/VtsRow.vue'
import VtsTable from '@core/components/table/VtsTable.vue'
import { usePagination } from '@core/composables/pagination.composable.ts'
import { useTableSelection } from '@core/composables/table-selection.composable.ts'
import { useTableState } from '@core/composables/table-state.composable.ts'
import { useQueryBuilderSchema } from '@core/packages/query-builder/schema/use-query-builder-schema.ts'
import { useQueryBuilderFilter } from '@core/packages/query-builder/use-query-builder-filter.ts'
import { usePrivilegeScopeObjectColumns } from '@core/tables/column-sets/privilege-scope-object-columns.ts'
import { useStringSchema } from '@core/utils/query-builder/use-string-schema.ts'
import { useI18n } from 'vue-i18n'
const {
tableId,
objects,
isReady,
hasError,
emptyMessage,
readonly = false,
} = defineProps<{
tableId: string
objects: PrivilegeScopeObject[]
isReady: boolean
hasError: boolean
emptyMessage: string
readonly?: boolean
}>()
const selectedIds = defineModel<string[]>('selectedIds', { default: () => [] })
const { t } = useI18n()
const { items: filteredObjects, searchBindings } = useQueryBuilderFilter(tableId, () => objects, { ignoreRoute: true })
const schema = useQueryBuilderSchema<PrivilegeScopeObject>({
'': useStringSchema(t('any-property')),
label: useStringSchema(t('name')),
})
const state = useTableState({
busy: () => !isReady,
error: () => hasError,
empty: () =>
objects.length === 0 ? emptyMessage : filteredObjects.value.length === 0 ? { type: 'no-result' } : false,
})
const { pageRecords: paginatedObjects, paginationBindings } = usePagination(tableId, filteredObjects, {
ignoreRoute: true,
})
const { pageSelectionModel, isSelected, toggleSelection, selectionBindings } = useTableSelection({
items: () => objects,
filteredItems: filteredObjects,
pageItems: paginatedObjects,
getItemId: object => object.id,
selectedIds,
})
const { HeadCells, BodyCells } = usePrivilegeScopeObjectColumns({
head: () => ({
checkbox: r => (readonly ? r() : r(pageSelectionModel)),
}),
body: (object: PrivilegeScopeObject) => ({
checkbox: r =>
readonly ? r() : r({ selected: isSelected(object.id), onToggle: () => toggleSelection(object.id) }),
object: r => r({ label: object.label, to: object.to, icon: object.icon }),
}),
})
</script>
<style lang="postcss" scoped>
.privilege-scope-objects-table {
display: flex;
flex-direction: column;
gap: 0.8rem;
}
</style>

View File

@@ -0,0 +1,59 @@
<template>
<VtsTable :state :pagination-bindings>
<thead>
<tr>
<HeadCells />
</tr>
</thead>
<tbody>
<VtsRow v-for="object of paginatedObjects" :key="object.id">
<BodyCells :item="object" />
</VtsRow>
</tbody>
</VtsTable>
</template>
<script lang="ts" setup>
import { usePrivilegeScopeObjects } from '@/modules/role/composables/use-privilege-scope-objects.composable.ts'
import type { PrivilegeSelectorMatch } from '@/modules/role/remote-resources/use-xo-privilege-selector-matches-collection.ts'
import type { PrivilegeScopeObject } from '@/modules/role/types.ts'
import type { SelectablePrivilegeResource } from '@/modules/role/utils/privilege-catalogue.util.ts'
import VtsRow from '@core/components/table/VtsRow.vue'
import VtsTable from '@core/components/table/VtsTable.vue'
import { usePagination } from '@core/composables/pagination.composable.ts'
import { useTableState } from '@core/composables/table-state.composable.ts'
import { usePrivilegeScopeObjectColumns } from '@core/tables/column-sets/privilege-scope-object-columns.ts'
import { computed } from 'vue'
const { resource, matches, isReady, hasError } = defineProps<{
resource: SelectablePrivilegeResource
matches: PrivilegeSelectorMatch[]
isReady: boolean
hasError: boolean
}>()
const { objects, isReady: areObjectsReady } = usePrivilegeScopeObjects(() => resource)
const objectsById = computed(() => new Map(objects.value.map(object => [object.id, object])))
const matchedObjects = computed<PrivilegeScopeObject[]>(() =>
matches.map(match => objectsById.value.get(match.id) ?? { id: match.id, label: match.name })
)
const state = useTableState({
busy: () => !isReady || !areObjectsReady.value,
error: () => hasError,
empty: () => (matches.length === 0 ? { type: 'no-result' } : false),
})
const { pageRecords: paginatedObjects, paginationBindings } = usePagination('privilege-scope-preview', matchedObjects, {
ignoreRoute: true,
})
const { HeadCells, BodyCells } = usePrivilegeScopeObjectColumns({
exclude: ['checkbox'],
body: (object: PrivilegeScopeObject) => ({
object: r => r({ label: object.label, to: object.to, icon: object.icon }),
}),
})
</script>

View File

@@ -0,0 +1,59 @@
<template>
<PrivilegeScopeVmsTable v-if="resource === 'vm'" v-model:selected-ids="selectedIds" :visible-ids :readonly />
<PrivilegeScopeHostsTable v-else-if="resource === 'host'" v-model:selected-ids="selectedIds" :visible-ids :readonly />
<PrivilegeScopeSrsTable v-else-if="resource === 'sr'" v-model:selected-ids="selectedIds" :visible-ids :readonly />
<PrivilegeScopeObjectsTable
v-else
:key="resource"
v-model:selected-ids="selectedIds"
:table-id="`privilege-scope-${resource}`"
:objects="visibleObjects"
:is-ready
:has-error
:empty-message
:readonly
/>
</template>
<script lang="ts" setup>
import PrivilegeScopeHostsTable from '@/modules/role/components/drawer/scope/PrivilegeScopeHostsTable.vue'
import PrivilegeScopeObjectsTable from '@/modules/role/components/drawer/scope/PrivilegeScopeObjectsTable.vue'
import PrivilegeScopeSrsTable from '@/modules/role/components/drawer/scope/PrivilegeScopeSrsTable.vue'
import PrivilegeScopeVmsTable from '@/modules/role/components/drawer/scope/PrivilegeScopeVmsTable.vue'
import { usePrivilegeScopeObjects } from '@/modules/role/composables/use-privilege-scope-objects.composable.ts'
import type { SelectablePrivilegeResource } from '@/modules/role/utils/privilege-catalogue.util.ts'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
const {
resource,
visibleIds,
readonly = false,
} = defineProps<{
resource: SelectablePrivilegeResource
visibleIds?: string[]
readonly?: boolean
}>()
const selectedIds = defineModel<string[]>('selectedIds', { default: () => [] })
const { t } = useI18n()
const { objects, isReady, hasError } = usePrivilegeScopeObjects(() => resource)
const visibleObjects = computed(() =>
visibleIds === undefined ? objects.value : objects.value.filter(object => visibleIds.includes(object.id))
)
const emptyMessage = computed(() => {
if (resource === 'pool') {
return t('no-pools-detected')
}
if (resource === 'backup-repository') {
return t('no-backup-repository-detected')
}
return t('no-data')
})
</script>

View File

@@ -0,0 +1,133 @@
<template>
<div class="privilege-scope-srs-table">
<VtsQueryBuilder v-bind="searchBindings" :schema />
<VtsTable :state :pagination-bindings :selection-bindings="readonly ? undefined : selectionBindings">
<thead>
<tr>
<HeadCells />
</tr>
</thead>
<tbody>
<VtsRow v-for="sr of paginatedSrs" :key="sr.id">
<BodyCells :item="sr" />
</VtsRow>
</tbody>
</VtsTable>
</div>
</template>
<script lang="ts" setup>
import { useSrQueryBuilder } from '@/modules/storage-repository/composables/use-sr-query-builder.composable.ts'
import { useXoSrUtils } from '@/modules/storage-repository/composables/xo-sr-utils.composable.ts'
import {
type FrontXoSr,
useXoSrCollection,
} from '@/modules/storage-repository/remote-resources/use-xo-sr-collection.ts'
import { getSrPageLocation } from '@/modules/storage-repository/utils/xo-sr.util.ts'
import VtsQueryBuilder from '@core/components/query-builder/VtsQueryBuilder.vue'
import VtsRow from '@core/components/table/VtsRow.vue'
import VtsTable from '@core/components/table/VtsTable.vue'
import { usePagination } from '@core/composables/pagination.composable.ts'
import { useTableSelection } from '@core/composables/table-selection.composable.ts'
import { useTableState } from '@core/composables/table-state.composable.ts'
import { icon } from '@core/icons'
import { useSrColumns } from '@core/tables/column-sets/sr-columns.ts'
import { SR_SCOPE_TYPE, type SrScope } from '@core/types/storage-repository.type.ts'
import { logicNot } from '@vueuse/math'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
const { visibleIds, readonly = false } = defineProps<{
visibleIds?: string[]
readonly?: boolean
}>()
const selectedIds = defineModel<string[]>('selectedIds', { default: () => [] })
const SCOPE: SrScope = { type: SR_SCOPE_TYPE.POOL }
const { t } = useI18n()
const { srs, areSrsReady, hasSrFetchError, isDefaultSr } = useXoSrCollection()
const visibleSrs = computed(() =>
visibleIds === undefined ? srs.value : srs.value.filter(sr => visibleIds.includes(sr.id))
)
const {
items: filteredSrs,
searchBindings,
schema,
} = useSrQueryBuilder('privilege-scope-srs', visibleSrs, {
ignoreRoute: true,
})
const state = useTableState({
busy: logicNot(areSrsReady),
error: hasSrFetchError,
empty: () =>
visibleSrs.value.length === 0
? t('no-storage-repository-detected')
: filteredSrs.value.length === 0
? { type: 'no-result' }
: false,
})
const { pageRecords: paginatedSrs, paginationBindings } = usePagination('privilege-scope-srs', filteredSrs, {
ignoreRoute: true,
})
const { pageSelectionModel, isSelected, toggleSelection, selectionBindings } = useTableSelection({
items: visibleSrs,
filteredItems: filteredSrs,
pageItems: paginatedSrs,
getItemId: (sr): string => sr.id,
selectedIds,
})
function getPrimaryIcon(sr: FrontXoSr) {
if (!isDefaultSr(sr)) {
return undefined
}
return {
icon: icon('status:primary-circle'),
tooltip: t('default-storage-repository'),
}
}
const { HeadCells, BodyCells } = useSrColumns({
exclude: ['actions'],
head: () => ({
checkbox: r => (readonly ? r() : r(pageSelectionModel)),
}),
body: (sr: FrontXoSr) => {
const rightIcon = computed(() => getPrimaryIcon(sr))
const { srStatusIcon, getSrAccessModeLabel } = useXoSrUtils(sr, () => SCOPE)
return {
checkbox: r => (readonly ? r() : r({ selected: isSelected(sr.id), onToggle: () => toggleSelection(sr.id) })),
storageRepository: r =>
r({
label: sr.name_label,
to: getSrPageLocation(sr, SCOPE),
icon: srStatusIcon.value,
rightIcon: rightIcon.value,
}),
description: r => r(sr.name_description),
storageFormat: r => r(sr.SR_type),
accessMode: r => r(getSrAccessModeLabel(sr)),
usedSpace: r => r(sr.physical_usage, sr.size),
}
},
})
</script>
<style lang="postcss" scoped>
.privilege-scope-srs-table {
display: flex;
flex-direction: column;
gap: 0.8rem;
}
</style>

View File

@@ -0,0 +1,106 @@
<template>
<div class="privilege-scope-vms-table">
<VtsQueryBuilder v-bind="searchBindings" :schema />
<VtsTable :state :pagination-bindings :selection-bindings="readonly ? undefined : selectionBindings">
<thead>
<tr>
<HeadCells />
</tr>
</thead>
<tbody>
<VtsRow v-for="vm of paginatedVms" :key="vm.id">
<BodyCells :item="vm" />
</VtsRow>
</tbody>
</VtsTable>
</div>
</template>
<script lang="ts" setup>
import type { VmDisplayData } from '@/modules/vm/composables/use-vm-enhanced-data.composable.ts'
import { useVmQueryBuilder } from '@/modules/vm/composables/use-vm-query-builder.composable.ts'
import { useXoVmCollection } from '@/modules/vm/remote-resources/use-xo-vm-collection.ts'
import VtsQueryBuilder from '@core/components/query-builder/VtsQueryBuilder.vue'
import VtsRow from '@core/components/table/VtsRow.vue'
import VtsTable from '@core/components/table/VtsTable.vue'
import { usePagination } from '@core/composables/pagination.composable.ts'
import { useTableSelection } from '@core/composables/table-selection.composable.ts'
import { useTableState } from '@core/composables/table-state.composable.ts'
import { useVmColumns } from '@core/tables/column-sets/vm-columns.ts'
import { logicNot } from '@vueuse/math'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
const { visibleIds, readonly = false } = defineProps<{
visibleIds?: string[]
readonly?: boolean
}>()
const selectedIds = defineModel<string[]>('selectedIds', { default: () => [] })
const { t } = useI18n()
const { vms, areVmsReady, hasVmFetchError } = useXoVmCollection()
const visibleVms = computed(() =>
visibleIds === undefined ? vms.value : vms.value.filter(vm => visibleIds.includes(vm.id))
)
const {
items: filteredVms,
searchBindings,
schema,
getDisplayData,
} = useVmQueryBuilder('privilege-scope-vms', visibleVms, {
ignoreRoute: true,
})
const state = useTableState({
busy: logicNot(areVmsReady),
error: hasVmFetchError,
empty: () =>
visibleVms.value.length === 0
? t('no-vm-detected')
: filteredVms.value.length === 0
? { type: 'no-result' }
: false,
})
const displayVms = computed(() => filteredVms.value.map(vm => getDisplayData(vm)))
const { pageRecords: paginatedVms, paginationBindings } = usePagination('privilege-scope-vms', displayVms, {
ignoreRoute: true,
})
const { pageSelectionModel, isSelected, toggleSelection, selectionBindings } = useTableSelection({
items: visibleVms,
filteredItems: filteredVms,
pageItems: paginatedVms,
getItemId: (vm): string => vm.id,
selectedIds,
})
const { HeadCells, BodyCells } = useVmColumns({
exclude: ['lastBackupDate', 'actions'],
head: () => ({
checkbox: r => (readonly ? r() : r(pageSelectionModel)),
}),
body: (vm: VmDisplayData) => ({
checkbox: r => (readonly ? r() : r({ selected: isSelected(vm.id), onToggle: () => toggleSelection(vm.id) })),
vm: r => r({ label: vm.name_label, to: { name: '/vm/[id]/dashboard', params: { id: vm.id } }, icon: vm.vmIcon }),
ipAddresses: r => r(vm.ipAddresses),
vcpus: r => r(vm.CPUs.number),
ram: r => r(vm.formattedRam.value, vm.formattedRam.prefix),
diskSpace: r => r(vm.formattedDiskSpace.value, vm.formattedDiskSpace.unit),
tags: r => r(vm.tags),
}),
})
</script>
<style lang="postcss" scoped>
.privilege-scope-vms-table {
display: flex;
flex-direction: column;
gap: 0.8rem;
}
</style>

View File

@@ -0,0 +1,25 @@
<template>
<VtsInputWrapper :label :message="messages" wrap-message>
<VtsSelect :id accent="neutral" />
</VtsInputWrapper>
</template>
<script lang="ts" setup>
import type { InputWrapperMessage } from '@core/components/input-wrapper/VtsInputWrapper.vue'
import type { FormSelectId } from '@core/packages/form-select'
import VtsInputWrapper from '@core/components/input-wrapper/VtsInputWrapper.vue'
import VtsSelect from '@core/components/select/VtsSelect.vue'
import { computed } from 'vue'
const { info, warning, error } = defineProps<{
id: FormSelectId
label: string
info?: string
warning?: InputWrapperMessage
error?: InputWrapperMessage
}>()
const messages = computed<InputWrapperMessage>(
() => [info, warning, error].filter(message => message !== undefined) as InputWrapperMessage
)
</script>

View File

@@ -0,0 +1,28 @@
<template>
<VtsInputWrapper :label :message="messages" wrap-message>
<UiInput v-model.trim="model" accent="neutral" :required @blur="emit('blur')" />
</VtsInputWrapper>
</template>
<script lang="ts" setup>
import type { InputWrapperMessage } from '@core/components/input-wrapper/VtsInputWrapper.vue'
import VtsInputWrapper from '@core/components/input-wrapper/VtsInputWrapper.vue'
import UiInput from '@core/components/ui/input/UiInput.vue'
import { computed } from 'vue'
const { info, warning, error } = defineProps<{
label: string
info?: string
warning?: InputWrapperMessage
error?: InputWrapperMessage
required?: boolean
}>()
const emit = defineEmits<{ blur: [] }>()
const model = defineModel<string>({ required: true })
const messages = computed<InputWrapperMessage>(
() => [info, warning, error].filter(message => message !== undefined) as InputWrapperMessage
)
</script>

View File

@@ -0,0 +1,15 @@
<template>
<UiTextarea v-model.trim="model" accent="neutral">
{{ label }}
</UiTextarea>
</template>
<script lang="ts" setup>
import UiTextarea from '@core/components/ui/text-area/UiTextarea.vue'
defineProps<{
label: string
}>()
const model = defineModel<string>({ required: true })
</script>

View File

@@ -0,0 +1,114 @@
<template>
<VtsForm class="new-role-form" @submit="onSubmit()">
<section class="section">
<UiTitle>{{ t('role:details') }}</UiTitle>
<div class="fields">
<RoleFormTextInput v-bind="nameInputBindings" />
<RoleFormTextarea v-bind="descriptionInputBindings" />
</div>
</section>
<section class="section">
<UiTitle>
{{ t('privileges') }}
<template #action>
<UiButton left-icon="fa:plus" variant="tertiary" accent="brand" size="medium" @click="addPrivileges()">
{{ t('new') }}
</UiButton>
</template>
</UiTitle>
<NewRolePrivilegesTable
:privileges
@edit="privilege => editPrivilege(privilege)"
@remove="privilege => removePrivilege(privilege)"
/>
</section>
<div class="buttons">
<UiButton variant="tertiary" accent="danger" size="medium" @click="emit('cancel')">
{{ t('cancel') }}
</UiButton>
<UiButton type="submit" variant="primary" accent="brand" size="medium">
{{ t('action:create') }}
</UiButton>
</div>
</VtsForm>
</template>
<script setup lang="ts">
import RoleFormTextarea from '@/modules/role/components/form/inputs/RoleFormTextarea.vue'
import RoleFormTextInput from '@/modules/role/components/form/inputs/RoleFormTextInput.vue'
import NewRolePrivilegesTable from '@/modules/role/components/form/new/NewRolePrivilegesTable.vue'
import { useNewRolePrivileges } from '@/modules/role/composables/use-new-role-privileges.composable.ts'
import { useNewRoleForm } from '@/modules/role/form/new/use-new-role-form.ts'
import type { NewRolePayload } from '@/modules/role/types.ts'
import VtsForm from '@core/components/form/VtsForm.vue'
import UiButton from '@core/components/ui/button/UiButton.vue'
import UiTitle from '@core/components/ui/title/UiTitle.vue'
import { objectOmit } from '@vueuse/core'
import { useI18n } from 'vue-i18n'
const { initialRole } = defineProps<{
initialRole?: NewRolePayload
}>()
const emit = defineEmits<{
create: [role: NewRolePayload]
cancel: []
}>()
const { t } = useI18n()
const { nameInputBindings, descriptionInputBindings, validateAndBuildPayload } = useNewRoleForm(initialRole)
const { privileges, addPrivileges, editPrivilege, removePrivilege } = useNewRolePrivileges(initialRole?.privileges)
async function onSubmit() {
const role = await validateAndBuildPayload()
if (role === undefined) {
return
}
emit('create', {
...role,
privileges: privileges.value.map(privilege => objectOmit(privilege, ['key'])),
})
}
</script>
<style lang="postcss" scoped>
.new-role-form {
display: flex;
flex-direction: column;
gap: 4rem;
.section {
display: flex;
flex-direction: column;
gap: 2.4rem;
}
.fields {
display: flex;
flex-direction: column;
gap: 2.4rem;
max-width: 78rem;
@media (--medium-or-large) {
display: grid;
grid-template-columns: repeat(2, 1fr);
align-items: start;
}
}
.buttons {
display: flex;
justify-content: center;
align-items: center;
gap: 2.4rem;
}
}
</style>

View File

@@ -0,0 +1,62 @@
<template>
<NewRoleForm
v-if="initialRole !== undefined"
:initial-role
@create="role => emit('create', role)"
@cancel="emit('cancel')"
/>
<VtsStateHero v-else-if="isRoleTemplateMissing" format="card" type="not-found" size="large">
{{ t('object-not-found', { id: roleTemplateId }) }}
</VtsStateHero>
<VtsStateHero v-else-if="hasFetchError" format="card" type="error" size="large">
{{ t('error-no-data') }}
</VtsStateHero>
<VtsStateHero v-else format="card" type="busy" size="large" />
</template>
<script setup lang="ts">
import NewRoleForm from '@/modules/role/components/form/new/NewRoleForm.vue'
import { useXoRolePrivilegesCollection } from '@/modules/role/remote-resources/use-xo-role-privileges-collection.ts'
import {
type FrontXoRoleTemplate,
useXoRoleTemplateCollection,
} from '@/modules/role/remote-resources/use-xo-role-template-collection.ts'
import type { NewRolePayload } from '@/modules/role/types.ts'
import { toNewRolePayload } from '@/modules/role/utils/role-template.util.ts'
import VtsStateHero from '@core/components/state-hero/VtsStateHero.vue'
import { logicAnd, logicOr } from '@vueuse/math'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
const { roleTemplateId } = defineProps<{
roleTemplateId: FrontXoRoleTemplate['id']
}>()
const emit = defineEmits<{
create: [role: NewRolePayload]
cancel: []
}>()
const { t } = useI18n()
const { useGetRoleTemplateById, areRoleTemplatesReady, hasRoleTemplateFetchError } = useXoRoleTemplateCollection()
const roleTemplate = useGetRoleTemplateById(() => roleTemplateId)
const isRoleTemplateMissing = logicAnd(areRoleTemplatesReady, () => roleTemplate.value === undefined)
const { privileges, arePrivilegesReady, hasPrivilegeFetchError } = useXoRolePrivilegesCollection(
{ isEnabled: computed(() => roleTemplate.value !== undefined) },
() => roleTemplateId
)
const hasFetchError = logicOr(hasRoleTemplateFetchError, hasPrivilegeFetchError)
const initialRole = computed(() => {
if (roleTemplate.value === undefined || !arePrivilegesReady.value) {
return undefined
}
return toNewRolePayload(roleTemplate.value, privileges.value)
})
</script>

View File

@@ -0,0 +1,67 @@
<template>
<VtsTable :state :pagination-bindings sticky="right">
<thead>
<tr>
<HeadCells />
</tr>
</thead>
<tbody>
<VtsRow v-for="privilege of paginatedPrivileges" :key="privilege.key">
<BodyCells :item="privilege" />
</VtsRow>
</tbody>
</VtsTable>
</template>
<script lang="ts" setup>
import { usePrivilegeAppliedToCount } from '@/modules/role/composables/use-privilege-applied-to-count.composable.ts'
import { usePrivilegeScopeTypeLabels } from '@/modules/role/composables/use-privilege-scope-type-labels.composable.ts'
import type { StagedPrivilege } from '@/modules/role/types.ts'
import { getPrivilegeScopeType } from '@/modules/role/utils/privilege-scope.util.ts'
import { EFFECT_ACCENTS } from '@/modules/role/utils/xo-privilege.util.ts'
import VtsRow from '@core/components/table/VtsRow.vue'
import VtsTable from '@core/components/table/VtsTable.vue'
import { usePagination } from '@core/composables/pagination.composable.ts'
import { useTableState } from '@core/composables/table-state.composable.ts'
import { usePrivilegeColumns } from '@core/tables/column-sets/privilege-columns.ts'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
const { privileges } = defineProps<{
privileges: StagedPrivilege[]
}>()
const emit = defineEmits<{
edit: [privilege: StagedPrivilege]
remove: [privilege: StagedPrivilege]
}>()
const { t } = useI18n()
const state = useTableState({
empty: () => (privileges.length === 0 ? t('privilege:none-yet') : false),
})
const { pageRecords: paginatedPrivileges, paginationBindings } = usePagination('new-role-privileges', () => privileges)
const scopeTypeLabels = usePrivilegeScopeTypeLabels()
const { HeadCells, BodyCells } = usePrivilegeColumns({
exclude: ['index', 'selectItem'],
body: (privilege: StagedPrivilege) => {
const scopeLabel = computed(() => scopeTypeLabels[getPrivilegeScopeType(privilege.resource, privilege.selector)])
const appliedToCount = usePrivilegeAppliedToCount(privilege)
return {
resource: r => r(privilege.resource),
scope: r => r(scopeLabel.value),
appliedTo: r => r(appliedToCount.value),
action: r => r(privilege.action),
effect: r => r(t(privilege.effect), EFFECT_ACCENTS[privilege.effect]),
edit: r => r(() => emit('edit', privilege)),
remove: r => r(() => emit('remove', privilege)),
}
},
})
</script>

View File

@@ -0,0 +1,161 @@
<template>
<div class="roles-table">
<UiTitle>
{{ t('roles') }}
<template #action>
<slot name="title-action" />
</template>
</UiTitle>
<VtsQueryBuilder v-bind="searchBindings" :schema />
<div class="container">
<VtsTableBulkActions :actions="bulkActions" />
<VtsTable :state :pagination-bindings :selection-bindings sticky="right">
<thead>
<tr>
<HeadCells />
</tr>
</thead>
<tbody>
<VtsRow v-for="role of paginatedRoles" :key="role.id" :selected="selectedRoleId === role.id">
<BodyCells :item="role" />
</VtsRow>
</tbody>
</VtsTable>
</div>
</div>
</template>
<script setup lang="ts">
import { useXoGroupCollection } from '@/modules/group/remote-resources/use-xo-group-collection.ts'
import { useRoleDelete } from '@/modules/role/composables/use-role-delete.composable.ts'
import {
type FilterableRole,
useRoleQueryBuilder,
} from '@/modules/role/composables/use-role-query-builder.composable.ts'
import type { FrontXoRole } from '@/modules/role/remote-resources/use-xo-role-collection.ts'
import type { ActionItem } from '@core/components/menu/VtsActionsMenu.vue'
import VtsQueryBuilder from '@core/components/query-builder/VtsQueryBuilder.vue'
import VtsRow from '@core/components/table/VtsRow.vue'
import VtsTable from '@core/components/table/VtsTable.vue'
import VtsTableBulkActions from '@core/components/table/VtsTableBulkActions.vue'
import UiTitle from '@core/components/ui/title/UiTitle.vue'
import { usePagination } from '@core/composables/pagination.composable.ts'
import { useRouteQuery } from '@core/composables/route-query.composable.ts'
import { useTableSelection } from '@core/composables/table-selection.composable.ts'
import { useTableState } from '@core/composables/table-state.composable.ts'
import { useRoleColumns } from '@core/tables/column-sets/role-columns.ts'
import { logicAnd, logicNot, logicOr } from '@vueuse/math'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
const {
roles: rawRoles,
busy,
error,
} = defineProps<{
roles: FrontXoRole[]
busy?: boolean
error?: boolean
}>()
defineSlots<{
'title-action'(): any
}>()
const { t } = useI18n()
const selectedRoleId = useRouteQuery('id')
const { areGroupsReady, hasGroupFetchError } = useXoGroupCollection()
const isReady = logicAnd(() => !busy, areGroupsReady)
const hasError = logicOr(() => error, hasGroupFetchError)
const { items: filteredRoles, searchBindings, schema } = useRoleQueryBuilder('roles', () => rawRoles)
const state = useTableState({
busy: logicNot(isReady),
error: hasError,
empty: () =>
rawRoles.length === 0 ? t('no-role-detected') : filteredRoles.value.length === 0 ? { type: 'no-result' } : false,
})
const { pageRecords: paginatedRoles, paginationBindings } = usePagination('roles', filteredRoles)
const { selectedIds, pageSelectionModel, isSelected, toggleSelection, selectionBindings } = useTableSelection({
items: () => rawRoles,
filteredItems: filteredRoles,
pageItems: paginatedRoles,
getItemId: role => role.id,
})
const selectedRoles = computed(() => rawRoles.filter(role => selectedIds.value.includes(role.id)))
const {
deleteRoles: deleteSelectedRoles,
canDeleteRoles: canDeleteSelectedRoles,
isDeletingRoles: isDeletingSelectedRoles,
deleteRolesErrorMessage: deleteSelectedRolesErrorMessage,
} = useRoleDelete(selectedRoles)
const bulkActions = computed<ActionItem[]>(() => [
{
label: t('action:delete'),
icon: 'action:delete',
accent: 'danger',
onClick: () => deleteSelectedRoles(),
disabled: !canDeleteSelectedRoles.value,
busy: isDeletingSelectedRoles.value,
hint: deleteSelectedRolesErrorMessage.value,
},
])
const { HeadCells, BodyCells } = useRoleColumns({
exclude: ['group'],
head: () => ({
checkbox: r => r(pageSelectionModel),
}),
body: (role: FilterableRole) => {
const { deleteRoles, canDeleteRoles, isDeletingRoles, deleteRolesErrorMessage } = useRoleDelete(() => [role])
return {
checkbox: r => r({ selected: isSelected(role.id), onToggle: () => toggleSelection(role.id) }),
name: r =>
r({ label: role.name, icon: 'fa:key', to: { name: '/admin/role/[id]/general', params: { id: role.id } } }),
description: r => r(role.description),
users: r => r(role.usersCount),
groups: r => r(role.groupsCount),
privileges: r => r(role.privilegesCount),
actions: r =>
r({
onClick: () => (selectedRoleId.value = role.id),
actions: [
{
label: t('action:delete'),
icon: 'action:delete',
accent: 'danger',
onClick: () => deleteRoles(),
disabled: !canDeleteRoles.value,
busy: isDeletingRoles.value,
hint: deleteRolesErrorMessage.value,
},
],
}),
}
},
})
</script>
<style scoped lang="postcss">
.roles-table,
.container {
display: flex;
flex-direction: column;
gap: 2.4rem;
}
.container {
gap: 0.8rem;
}
</style>

View File

@@ -0,0 +1,47 @@
<template>
<VtsSidePanel :has-selection="role !== undefined" @close="emit('close')">
<template v-if="role" #actions>
<slot name="actions">
<VtsDeleteButton
:disabled="!canDeleteRoles"
:busy="isDeletingRoles"
:tooltip="deleteRolesErrorMessage ?? false"
@click="deleteRoles()"
/>
</slot>
</template>
<template v-if="role" #default>
<RoleInfosCard :role />
<RoleUsersCard :role />
<RoleGroupsCard :role />
<RolePrivilegesCard :role />
</template>
</VtsSidePanel>
</template>
<script setup lang="ts">
import RoleGroupsCard from '@/modules/role/components/list/panel/cards/RoleGroupsCard.vue'
import RoleInfosCard from '@/modules/role/components/list/panel/cards/RoleInfosCard.vue'
import RolePrivilegesCard from '@/modules/role/components/list/panel/cards/RolePrivilegesCard.vue'
import RoleUsersCard from '@/modules/role/components/list/panel/cards/RoleUsersCard.vue'
import { useRoleDelete } from '@/modules/role/composables/use-role-delete.composable.ts'
import type { FrontXoRole } from '@/modules/role/remote-resources/use-xo-role-collection.ts'
import VtsDeleteButton from '@core/components/delete-button/VtsDeleteButton.vue'
import VtsSidePanel from '@core/components/panel/VtsSidePanel.vue'
const { role } = defineProps<{
role?: FrontXoRole
}>()
const emit = defineEmits<{
close: []
}>()
defineSlots<{
actions?(): any
}>()
const { deleteRoles, canDeleteRoles, isDeletingRoles, deleteRolesErrorMessage } = useRoleDelete(() =>
role !== undefined ? [role] : []
)
</script>

View File

@@ -0,0 +1,53 @@
<template>
<UiPanelCard class="role-groups-card">
<UiPanelCardTitle size="medium" :label="t('groups')" :counter="areGroupsReady ? roleGroups.length : undefined" />
<VtsStateHero v-if="hasGroupFetchError" type="error" format="card" horizontal size="extra-small">
{{ t('error-no-data') }}
</VtsStateHero>
<VtsStateHero v-else-if="!areGroupsReady" type="busy" format="card" horizontal size="extra-small" />
<UiLinkList
v-else-if="roleGroups.length > 0"
variant="vertical"
:visible-items="5"
:total-items="roleGroups.length"
>
<UiLink
v-for="group of roleGroups"
:key="group.id"
icon="table:group"
size="small"
:to="{ name: '/admin/user-management/groups', query: { id: group.id } }"
>
{{ group.name }}
</UiLink>
</UiLinkList>
<VtsStateHero v-else type="no-data" format="card" horizontal size="extra-small">
{{ t('no-group-attached') }}
</VtsStateHero>
</UiPanelCard>
</template>
<script lang="ts" setup>
import { useXoGroupCollection } from '@/modules/group/remote-resources/use-xo-group-collection.ts'
import type { FrontXoRole } from '@/modules/role/remote-resources/use-xo-role-collection.ts'
import VtsStateHero from '@core/components/state-hero/VtsStateHero.vue'
import UiLink from '@core/components/ui/link/UiLink.vue'
import UiLinkList from '@core/components/ui/link-list/UiLinkList.vue'
import UiPanelCard from '@core/components/ui/panel-card/UiPanelCard.vue'
import UiPanelCardTitle from '@core/components/ui/panel-card-title/UiPanelCardTitle.vue'
import { useI18n } from 'vue-i18n'
const { role } = defineProps<{
role: FrontXoRole
}>()
const { t } = useI18n()
const { useGetGroupsByIds, areGroupsReady, hasGroupFetchError } = useXoGroupCollection()
const roleGroups = useGetGroupsByIds(() => role.groupIds)
</script>

View File

@@ -0,0 +1,45 @@
<template>
<UiPanelCard class="role-infos-card">
<UiPanelCardTitle :id="role.id" size="medium" :label="role.name" icon="fa:key" :to="detailRoute" />
<div class="content">
<VtsCardRowKeyValue truncate align-top>
<template #key>{{ t('description') }}</template>
<template #value>{{ role.description }}</template>
<template v-if="role.description" #addons>
<VtsCopyButton :value="role.description" />
</template>
</VtsCardRowKeyValue>
</div>
</UiPanelCard>
</template>
<script lang="ts" setup>
import type { FrontXoRole } from '@/modules/role/remote-resources/use-xo-role-collection.ts'
import type { FrontXoRoleTemplate } from '@/modules/role/remote-resources/use-xo-role-template-collection.ts'
import VtsCardRowKeyValue from '@core/components/card/VtsCardRowKeyValue.vue'
import VtsCopyButton from '@core/components/copy-button/VtsCopyButton.vue'
import UiPanelCard from '@core/components/ui/panel-card/UiPanelCard.vue'
import UiPanelCardTitle from '@core/components/ui/panel-card-title/UiPanelCardTitle.vue'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
const { role } = defineProps<{
role: FrontXoRole | FrontXoRoleTemplate
}>()
const { t } = useI18n()
const detailRoute = computed(() =>
'isTemplate' in role ? undefined : ({ name: '/admin/role/[id]/general', params: { id: role.id } } as const)
)
</script>
<style scoped lang="postcss">
.role-infos-card {
.content {
display: flex;
flex-direction: column;
gap: 0.4rem;
}
}
</style>

View File

@@ -0,0 +1,63 @@
<template>
<UiPanelCard class="role-privileges-card">
<UiPanelCardTitle
size="medium"
:label="t('privileges')"
:counter="arePrivilegesReady ? privileges.length : undefined"
/>
<VtsStateHero v-if="hasPrivilegeFetchError" type="error" format="card" horizontal size="extra-small">
{{ t('error-no-data') }}
</VtsStateHero>
<VtsStateHero v-else-if="!arePrivilegesReady" type="busy" format="card" horizontal size="extra-small" />
<UiCollapsibleList v-else-if="privileges.length > 0" tag="div" :total-items="privileges.length">
<div v-for="(privilege, index) of privileges" :key="privilege.id" class="privilege">
<UiPanelCardTitle :id="privilege.id" size="small" :label="t('privilege-number', { n: index + 1 })" />
<PrivilegeDetailsRows :privilege />
</div>
</UiCollapsibleList>
<VtsStateHero v-else type="no-data" format="card" horizontal size="extra-small">
{{ t('no-privilege-attached') }}
</VtsStateHero>
</UiPanelCard>
</template>
<script lang="ts" setup>
import PrivilegeDetailsRows from '@/modules/role/components/privilege/PrivilegeDetailsRows.vue'
import type { FrontXoRole } from '@/modules/role/remote-resources/use-xo-role-collection.ts'
import { useXoRolePrivilegesCollection } from '@/modules/role/remote-resources/use-xo-role-privileges-collection.ts'
import type { FrontXoRoleTemplate } from '@/modules/role/remote-resources/use-xo-role-template-collection.ts'
import VtsStateHero from '@core/components/state-hero/VtsStateHero.vue'
import UiCollapsibleList from '@core/components/ui/collapsible-list/UiCollapsibleList.vue'
import UiPanelCard from '@core/components/ui/panel-card/UiPanelCard.vue'
import UiPanelCardTitle from '@core/components/ui/panel-card-title/UiPanelCardTitle.vue'
import { useI18n } from 'vue-i18n'
const { role } = defineProps<{
role: FrontXoRole | FrontXoRoleTemplate
}>()
const { t } = useI18n()
const { privileges, arePrivilegesReady, hasPrivilegeFetchError } = useXoRolePrivilegesCollection({}, () => role.id)
</script>
<style scoped lang="postcss">
.role-privileges-card {
.privilege {
display: flex;
flex-direction: column;
gap: 0.8rem;
padding-block-end: 1.6rem;
border-block-end: 0.1rem solid var(--color-neutral-border);
&:last-child {
padding-block-end: 0;
border-block-end: none;
}
}
}
</style>

View File

@@ -0,0 +1,99 @@
<template>
<UiPanelCard class="role-users-card">
<UiPanelCardTitle size="medium" :label="t('users')" :counter="isReady ? totalUserCount : undefined" />
<VtsStateHero v-if="hasFetchError" type="error" format="card" horizontal size="extra-small">
{{ t('error-no-data') }}
</VtsStateHero>
<VtsStateHero v-else-if="!isReady" type="busy" format="card" horizontal size="extra-small" />
<template v-else-if="sections.length > 0">
<div v-for="section of sections" :key="section.key" class="section">
<UiPanelCardTitle size="small" :label="section.label" />
<UiLinkList variant="vertical" :visible-items="5" :total-items="section.users.length">
<UiLink
v-for="user of section.users"
:key="user.id"
icon="fa:circle-user"
size="small"
:to="{ name: '/admin/user-management/users', query: { id: user.id } }"
>
{{ getUserDisplayName(user) }}
</UiLink>
</UiLinkList>
</div>
</template>
<VtsStateHero v-else type="no-data" format="card" horizontal size="extra-small">
{{ t('no-user-attached') }}
</VtsStateHero>
</UiPanelCard>
</template>
<script lang="ts" setup>
import { useXoGroupCollection } from '@/modules/group/remote-resources/use-xo-group-collection.ts'
import type { FrontXoRole } from '@/modules/role/remote-resources/use-xo-role-collection.ts'
import { getRoleUserIds } from '@/modules/role/utils/xo-role.util.ts'
import { type FrontXoUser, useXoUserCollection } from '@/modules/user/remote-resources/use-xo-user-collection.ts'
import { getUserDisplayName } from '@/modules/user/utils/xo-user.util.ts'
import VtsStateHero from '@core/components/state-hero/VtsStateHero.vue'
import UiLink from '@core/components/ui/link/UiLink.vue'
import UiLinkList from '@core/components/ui/link-list/UiLinkList.vue'
import UiPanelCard from '@core/components/ui/panel-card/UiPanelCard.vue'
import UiPanelCardTitle from '@core/components/ui/panel-card-title/UiPanelCardTitle.vue'
import { logicAnd, logicOr } from '@vueuse/math'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
type UserSection = {
key: string
label: string
users: FrontXoUser[]
}
const { role } = defineProps<{
role: FrontXoRole
}>()
const { t } = useI18n()
const { getUsersByIds, useGetUsersByIds, areUsersReady, hasUserFetchError } = useXoUserCollection()
const { useGetGroupsByIds, areGroupsReady, hasGroupFetchError } = useXoGroupCollection()
const isReady = logicAnd(areUsersReady, areGroupsReady)
const hasFetchError = logicOr(hasUserFetchError, hasGroupFetchError)
const directUsers = useGetUsersByIds(() => role.userIds)
const roleGroups = useGetGroupsByIds(() => role.groupIds)
const sections = computed<UserSection[]>(() => {
const inheritedSections = roleGroups.value
.map(group => ({
key: group.id,
label: t('role:users-from-group', { group: group.name }),
users: getUsersByIds(group.users),
}))
.filter(section => section.users.length > 0)
if (directUsers.value.length === 0) {
return inheritedSections
}
return [...inheritedSections, { key: 'direct', label: t('role:direct-users'), users: directUsers.value }]
})
const totalUserCount = computed(() => getRoleUserIds(role, roleGroups.value).length)
</script>
<style scoped lang="postcss">
.role-users-card {
.section {
display: flex;
flex-direction: column;
gap: 0.8rem;
}
}
</style>

Some files were not shown because too many files have changed in this diff Show More